Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| aa840b9f31 | |||
| d2f597cec8 | |||
| cc5738d036 | |||
| 3cd094a8c5 | |||
| 9ace5da517 | |||
| 0017b0ca4c | |||
| 9903e22c2a | |||
| 8885162147 | |||
| 20f244c014 | |||
| 9baeeb7ff0 | |||
| 28d80ad7e3 | |||
| 80e0677b3a | |||
| a6a05febfd | |||
| 1405208c3e | |||
| 64abc56989 | |||
| 918fe01ea1 | |||
| 130ef28a16 | |||
| 983b702488 | |||
| 72d092d0f3 | |||
| d6e2c68dbf | |||
| 1dbde8b830 | |||
| 14dff24f85 | |||
| 74eb5a4a4c | |||
| 66c4ba5c5f | |||
| 86b8da08bf | |||
| 7842170a0e | |||
| 087168044e | |||
| 0f3b5851eb | |||
| cb5a56de15 | |||
| 865412ea7a | |||
| 47caff4034 | |||
| cef2c62c3c | |||
| ef872f6b12 | |||
| 5aa90c230a | |||
| 92cf95e1af | |||
| 532338cdea | |||
| 5d2d5ea4cb | |||
| 0b8ba5c43a | |||
| 4ce7f21017 | |||
| 11dabc4714 | |||
| c67b52b828 | |||
| 3aec97a8b7 | |||
| 5d80c480ef | |||
| 4275f9bcc9 | |||
| 2188d7a5e8 | |||
| d8ff604b6f | |||
| f6d00f51f3 | |||
| 32df6dadf8 | |||
| 362d97af70 | |||
| 461cae1490 | |||
| e6eb3157a3 | |||
| f7faabf699 | |||
| 987efe54f8 | |||
| bcfd6aef07 | |||
| f13efbad67 | |||
| a69db40067 | |||
| e27a5da077 | |||
| 7e4c643c4d | |||
| 4a30d64193 | |||
| a31d987548 | |||
| c6c8bdf3f8 |
@@ -10,4 +10,7 @@ WebApp/
|
||||
**/uv.lock
|
||||
!WebApi/uv.lock
|
||||
dist/
|
||||
# The image compiles its own manifest.
|
||||
Transformation/target/
|
||||
Transformation/logs/
|
||||
**/node_modules/
|
||||
|
||||
@@ -14,3 +14,4 @@ dist/imagenes/
|
||||
dist/.env
|
||||
dist/datos/
|
||||
dist/*.tar.gz
|
||||
graphify-out/
|
||||
@@ -7,7 +7,3 @@
|
||||
[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
|
||||
|
||||
@@ -20,10 +20,14 @@ from core.indicadores.cohortes import (
|
||||
)
|
||||
from core.indicadores.catalogos import (
|
||||
CatEstudioBase,
|
||||
CatMapeoBase,
|
||||
CatResultadoBase,
|
||||
CatSistemaFuenteBase,
|
||||
CatValorBase,
|
||||
estado_de_valor_conocido,
|
||||
reglas_de_mapeo,
|
||||
tipo_de_valor_conocido,
|
||||
vigencia_ordenada,
|
||||
)
|
||||
from core.indicadores.plata import (
|
||||
ObservacionClinicaBase,
|
||||
@@ -157,6 +161,16 @@ class CatValor(CaCuModel, CatValorBase, table=True):
|
||||
__table_args__ = (estado_de_valor_conocido(),)
|
||||
|
||||
|
||||
class CatSistemaFuente(CaCuModel, CatSistemaFuenteBase, table=True):
|
||||
__tablename__ = "cat_sistema_fuente"
|
||||
__table_args__ = (vigencia_ordenada("cat_sistema_fuente"),)
|
||||
|
||||
|
||||
class CatMapeo(CaCuModel, CatMapeoBase, table=True):
|
||||
__tablename__ = "cat_mapeo"
|
||||
__table_args__ = reglas_de_mapeo()
|
||||
|
||||
|
||||
# --- La plata de dos tablas (F5, ADR-MD-007) ---
|
||||
|
||||
|
||||
|
||||
@@ -20,10 +20,14 @@ from core.indicadores.cohortes import (
|
||||
)
|
||||
from core.indicadores.catalogos import (
|
||||
CatEstudioBase,
|
||||
CatMapeoBase,
|
||||
CatResultadoBase,
|
||||
CatSistemaFuenteBase,
|
||||
CatValorBase,
|
||||
estado_de_valor_conocido,
|
||||
reglas_de_mapeo,
|
||||
tipo_de_valor_conocido,
|
||||
vigencia_ordenada,
|
||||
)
|
||||
from core.indicadores.plata import (
|
||||
ObservacionClinicaBase,
|
||||
@@ -157,6 +161,16 @@ class CatValor(CaMaModel, CatValorBase, table=True):
|
||||
__table_args__ = (estado_de_valor_conocido(),)
|
||||
|
||||
|
||||
class CatSistemaFuente(CaMaModel, CatSistemaFuenteBase, table=True):
|
||||
__tablename__ = "cat_sistema_fuente"
|
||||
__table_args__ = (vigencia_ordenada("cat_sistema_fuente"),)
|
||||
|
||||
|
||||
class CatMapeo(CaMaModel, CatMapeoBase, table=True):
|
||||
__tablename__ = "cat_mapeo"
|
||||
__table_args__ = reglas_de_mapeo()
|
||||
|
||||
|
||||
# --- La plata de dos tablas (F5, ADR-MD-007) ---
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from enum import Enum
|
||||
|
||||
class TipoEstudio(str, Enum):
|
||||
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders (indicadores_kit cama)
|
||||
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders
|
||||
BIOPSIA_CHICA = "BIOPSIA_CHICA"
|
||||
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Catálogos de la plata (F1)
|
||||
|
||||
Un TOML por proyecto: estudio → resultado → valor.
|
||||
El paso `catalogos` de `webapi.orquestacion` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
|
||||
El paso `catalogos` de `webapi.orchestration` 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
|
||||
@@ -19,5 +19,21 @@ valores = [ # solo codigo; el orden de la lista es el de
|
||||
]
|
||||
```
|
||||
|
||||
A result read from a document's text (a report's interpretation, a PDF's text layer, a note) also says how it's
|
||||
printed. These keys don't reach any table; the silver load reads them (`webapi.orchestration.silver.extracted`):
|
||||
|
||||
```toml
|
||||
[<estudio>.resultados.<resultado>]
|
||||
etiquetas_fuente = ["Densidad mamaria", "Densidad"] # the captions it's printed under
|
||||
buscar_en_texto = true # codigo only: also as a mention anywhere in the text
|
||||
provisional = true # captions and spellings not yet confirmed with the hospital's documents
|
||||
valores = [
|
||||
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C", "ACR C"] }, # each spelling of the value
|
||||
]
|
||||
```
|
||||
|
||||
A spelling with no alias is stored as `valor_fuente` without `valor_id` and counted as out of catalog; adding it
|
||||
as an alias and reloading turns it into the code. One spelling on two values of a result is rejected.
|
||||
|
||||
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.
|
||||
|
||||
@@ -30,6 +30,27 @@ valores = [
|
||||
{ valor = "B6", etiqueta = "BI-RADS 6" },
|
||||
]
|
||||
|
||||
# Read from the radiologist's interpretation (`mast_interpretacion`). Provisional: captions and spellings are
|
||||
# assumptions until the hospital's reports are seen; adding one is a line in `etiquetas_fuente` or `alias`.
|
||||
[mastografia.resultados.densidad]
|
||||
etiqueta = "Densidad mamaria (ACR)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Densidad mamaria", "Densidad", "Composición mamaria", "Patrón mamario"]
|
||||
valores = [
|
||||
{ valor = "A", etiqueta = "Predominantemente grasa", alias = ["Tipo A", "ACR A", "Categoría A", "(A)", "Grasa"] },
|
||||
{ valor = "B", etiqueta = "Densidades fibroglandulares dispersas", alias = ["Tipo B", "ACR B", "Categoría B", "(B)", "Fibroglandular dispersa"] },
|
||||
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C", "ACR C", "Categoría C", "(C)", "Heterogéneamente densas"] },
|
||||
{ valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D", "ACR D", "Categoría D", "(D)", "Extremadamente densas"] },
|
||||
]
|
||||
|
||||
[mastografia.resultados.tamano_lesion_mm]
|
||||
etiqueta = "Tamaño de la lesión"
|
||||
tipo_valor = "numero"
|
||||
unidad = "mm"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Tamaño de la lesión", "Tamaño del nódulo", "Diámetro mayor", "Mide"]
|
||||
|
||||
[biopsia]
|
||||
etiqueta = "Biopsia de mama"
|
||||
codigos_hospital = ["BIOPSIA_CHICA"]
|
||||
@@ -48,6 +69,85 @@ valores = [
|
||||
etiqueta = "Fecha de solicitud"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
# Read from the pathology report's text layer (`bx_pdf_blob`). Provisional, as the mammography's.
|
||||
[biopsia.resultados.tipo_histologico]
|
||||
etiqueta = "Tipo histológico"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Tipo histológico", "Diagnóstico histopatológico", "Diagnóstico"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "DUCTAL_INFILTRANTE", etiqueta = "Carcinoma ductal infiltrante", alias = ["Ductal infiltrante", "Carcinoma ductal invasor", "Carcinoma infiltrante de tipo no especial", "CDI"] },
|
||||
{ valor = "LOBULILLAR_INFILTRANTE", etiqueta = "Carcinoma lobulillar infiltrante", alias = ["Lobulillar infiltrante", "Carcinoma lobulillar invasor", "CLI"] },
|
||||
{ valor = "DUCTAL_IN_SITU", etiqueta = "Carcinoma ductal in situ", alias = ["Ductal in situ", "CDIS"] },
|
||||
{ valor = "OTRO", etiqueta = "Otro tipo histológico" },
|
||||
]
|
||||
|
||||
[biopsia.resultados.grado_nottingham]
|
||||
etiqueta = "Grado histológico (Nottingham)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Grado histológico", "Grado de Nottingham", "Grado Scarff-Bloom-Richardson", "SBR"]
|
||||
valores = [
|
||||
{ valor = "G1", etiqueta = "Grado 1", alias = ["1", "I", "Grado I", "Bien diferenciado"] },
|
||||
{ valor = "G2", etiqueta = "Grado 2", alias = ["2", "II", "Grado II", "Moderadamente diferenciado"] },
|
||||
{ valor = "G3", etiqueta = "Grado 3", alias = ["3", "III", "Grado III", "Poco diferenciado"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.receptor_estrogeno]
|
||||
etiqueta = "Receptor de estrógeno"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Receptores de estrógeno", "Receptor de estrógenos", "Receptores estrogénicos", "RE", "ER"]
|
||||
valores = [
|
||||
{ valor = "POSITIVO", etiqueta = "Positivo", alias = ["Pos", "+"] },
|
||||
{ valor = "NEGATIVO", etiqueta = "Negativo", alias = ["Neg", "-"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.receptor_estrogeno_pct]
|
||||
etiqueta = "Receptor de estrógeno, células teñidas"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Receptores de estrógeno", "Receptor de estrógenos", "Receptores estrogénicos", "RE", "ER"]
|
||||
|
||||
[biopsia.resultados.receptor_progesterona]
|
||||
etiqueta = "Receptor de progesterona"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Receptores de progesterona", "Receptor de progesterona", "Receptores progestágenos", "RP", "PR"]
|
||||
valores = [
|
||||
{ valor = "POSITIVO", etiqueta = "Positivo", alias = ["Pos", "+"] },
|
||||
{ valor = "NEGATIVO", etiqueta = "Negativo", alias = ["Neg", "-"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.receptor_progesterona_pct]
|
||||
etiqueta = "Receptor de progesterona, células teñidas"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Receptores de progesterona", "Receptor de progesterona", "Receptores progestágenos", "RP", "PR"]
|
||||
|
||||
# A bare "positivo" is left unmatched on purpose: it doesn't say whether it's 3+ or an amplified 2+.
|
||||
[biopsia.resultados.her2]
|
||||
etiqueta = "HER2 (inmunohistoquímica)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["HER2", "HER-2", "HER2/neu", "C-erbB-2"]
|
||||
valores = [
|
||||
{ valor = "H0", etiqueta = "0", alias = ["0", "Negativo (0)", "Score 0"] },
|
||||
{ valor = "H1", etiqueta = "1+", alias = ["1+", "Negativo (1+)", "Score 1+"] },
|
||||
{ valor = "H2", etiqueta = "2+", alias = ["2+", "Equívoco", "Indeterminado", "Score 2+"] },
|
||||
{ valor = "H3", etiqueta = "3+", alias = ["3+", "Positivo (3+)", "Score 3+"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.ki67_pct]
|
||||
etiqueta = "Ki-67"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Ki-67", "Ki67", "Índice de proliferación"]
|
||||
|
||||
[nota_medica]
|
||||
etiqueta = "Nota médica"
|
||||
|
||||
@@ -56,6 +156,25 @@ etiqueta = "Diagnóstico"
|
||||
tipo_valor = "externo"
|
||||
sistema = "CIE-10"
|
||||
|
||||
# Read from the note's diagnosis and prognosis texts. Provisional; a stage mentioned without a caption counts too
|
||||
# ("... estadio clínico IIA (T2N0M0)").
|
||||
[nota_medica.resultados.estadio_clinico]
|
||||
etiqueta = "Estadio clínico"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Estadio clínico", "Etapa clínica", "Estadio", "EC"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "E0", etiqueta = "Estadio 0", alias = ["EC 0", "Etapa 0", "In situ", "Estadio clínico 0", "Etapa clínica 0"] },
|
||||
{ valor = "EI", etiqueta = "Estadio I", alias = ["I", "IA", "IB", "EC I", "EC IA", "EC IB", "Estadio IA", "Estadio IB", "Etapa I", "Estadio clínico I", "Etapa clínica I", "Estadio clínico IA", "Estadio clínico IB"] },
|
||||
{ valor = "EIIA", etiqueta = "Estadio IIA", alias = ["IIA", "EC IIA", "Etapa IIA", "Estadio clínico IIA", "Etapa clínica IIA"] },
|
||||
{ valor = "EIIB", etiqueta = "Estadio IIB", alias = ["IIB", "EC IIB", "Etapa IIB", "Estadio clínico IIB", "Etapa clínica IIB"] },
|
||||
{ valor = "EIIIA", etiqueta = "Estadio IIIA", alias = ["IIIA", "EC IIIA", "Etapa IIIA", "Estadio clínico IIIA", "Etapa clínica IIIA"] },
|
||||
{ valor = "EIIIB", etiqueta = "Estadio IIIB", alias = ["IIIB", "EC IIIB", "Etapa IIIB", "Estadio clínico IIIB", "Etapa clínica IIIB"] },
|
||||
{ valor = "EIIIC", etiqueta = "Estadio IIIC", alias = ["IIIC", "EC IIIC", "Etapa IIIC", "Estadio clínico IIIC", "Etapa clínica IIIC"] },
|
||||
{ valor = "EIV", etiqueta = "Estadio IV", alias = ["IV", "EC IV", "Etapa IV", "Metastásico", "Estadio clínico IV", "Etapa clínica IV"] },
|
||||
]
|
||||
|
||||
[nota_medica.resultados.especialidad]
|
||||
etiqueta = "Especialidad que la escribe"
|
||||
tipo_valor = "codigo"
|
||||
|
||||
+228
-219
@@ -1,267 +1,276 @@
|
||||
# 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.
|
||||
# TEA's catalog: the studies of the screening (M-CHAT, ADOS-2, neuropediatrics note, EEG) and their results.
|
||||
# Values are Core's enums (`core/tea/enums.py`). `codigos_hospital` are the codes of `ord_tipo_estudio`: an order's
|
||||
# `estudio_id` is the study it asks for.
|
||||
|
||||
[evaluacion_psicologica]
|
||||
etiqueta = "Evaluación psicológica"
|
||||
codigos_hospital = ["EVALUACION_PSICOLOGICA_TEA"]
|
||||
[mchat]
|
||||
etiqueta = "M-CHAT-R/F"
|
||||
|
||||
[evaluacion_psicologica.resultados.instrumento_tamizaje]
|
||||
etiqueta = "Instrumento de tamizaje"
|
||||
[mchat.resultados.puntaje]
|
||||
etiqueta = "Puntaje total"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
# The ADOS-2: module, algorithm, classification, CSS and the algorithm items. An item's domain is its prefix:
|
||||
# `sa_` social affect, `rrb_` restricted and repetitive behaviour. Labels of the items without a published short name
|
||||
# wait for the hospital's manuals.
|
||||
[ados2]
|
||||
etiqueta = "Evaluación psicológica (ADOS-2)"
|
||||
codigos_hospital = ["ADOS2"]
|
||||
|
||||
[ados2.resultados.modulo]
|
||||
etiqueta = "Módulo"
|
||||
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" },
|
||||
{ valor = "TODDLER", etiqueta = "Módulo T (niños pequeños)" },
|
||||
{ valor = "MODULO_1", etiqueta = "Módulo 1" },
|
||||
{ valor = "MODULO_2", etiqueta = "Módulo 2" },
|
||||
{ valor = "MODULO_3", etiqueta = "Módulo 3" },
|
||||
]
|
||||
|
||||
[evaluacion_psicologica.resultados.edad_meses]
|
||||
etiqueta = "Edad del niño"
|
||||
tipo_valor = "numero"
|
||||
unidad = "meses"
|
||||
[ados2.resultados.algoritmo]
|
||||
etiqueta = "Algoritmo"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[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.clasificacion]
|
||||
etiqueta = "Clasificación"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NO_ESPECTRO", etiqueta = "No espectro" },
|
||||
{ valor = "ESPECTRO_AUTISTA", etiqueta = "Espectro autista" },
|
||||
{ valor = "AUTISMO", etiqueta = "Autismo" },
|
||||
{ valor = "PREOCUPACION_LEVE_MODERADA", etiqueta = "Preocupación leve a moderada" },
|
||||
{ valor = "PREOCUPACION_SEVERA", etiqueta = "Preocupación moderada a severa" },
|
||||
]
|
||||
|
||||
[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"
|
||||
[ados2.resultados.sa_a2]
|
||||
etiqueta = "Frecuencia de la vocalización espontánea dirigida a otros"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[parto.resultados.ingreso_ucin]
|
||||
etiqueta = "Ingreso a UCIN"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_a6]
|
||||
etiqueta = "Uso del cuerpo de otra persona para comunicarse"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal]
|
||||
etiqueta = "Antecedentes maternos de la gestación"
|
||||
[ados2.resultados.sa_a7]
|
||||
etiqueta = "Señalar"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.antecedente_aborto]
|
||||
etiqueta = "Antecedente de aborto"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_a8]
|
||||
etiqueta = "Gestos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.asma]
|
||||
etiqueta = "Asma"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b1]
|
||||
etiqueta = "Contacto visual inusual"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.crisis_convulsivas]
|
||||
etiqueta = "Crisis convulsivas"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b2]
|
||||
etiqueta = "Sonrisa social en respuesta"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.diabetes_gestacional]
|
||||
etiqueta = "Diabetes gestacional"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b3]
|
||||
etiqueta = "Expresiones faciales dirigidas a otros"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.embarazo_multiple]
|
||||
etiqueta = "Embarazo múltiple"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b4]
|
||||
etiqueta = "Integración de la mirada y otras conductas en las iniciaciones sociales"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.enfermedad_autoinmune]
|
||||
etiqueta = "Enfermedad autoinmune"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b5]
|
||||
etiqueta = "Placer compartido durante la interacción"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.estres_agudo]
|
||||
etiqueta = "Estrés agudo"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b6]
|
||||
etiqueta = "Respuesta al nombre"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.farmaco_riesgo_neurodesarrollo]
|
||||
etiqueta = "Fármaco de riesgo para el neurodesarrollo"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b7]
|
||||
etiqueta = "Pedir"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.hipertension_preeclampsia]
|
||||
etiqueta = "Hipertensión o preeclampsia"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b8]
|
||||
etiqueta = "Dar"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.hipertiroidismo]
|
||||
etiqueta = "Hipertiroidismo"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b9]
|
||||
etiqueta = "Mostrar"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.hipotiroidismo]
|
||||
etiqueta = "Hipotiroidismo"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b10]
|
||||
etiqueta = "Iniciación espontánea de la atención conjunta"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.hipoxia_materna]
|
||||
etiqueta = "Hipoxia materna"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b11]
|
||||
etiqueta = "Respuesta a la atención conjunta"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.incompatibilidad_rh]
|
||||
etiqueta = "Incompatibilidad Rh"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b12]
|
||||
etiqueta = "Calidad de los acercamientos sociales"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.infeccion_gestacion]
|
||||
etiqueta = "Infección en la gestación"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b13]
|
||||
etiqueta = "Reactivo B13"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.liquido_amniotico]
|
||||
etiqueta = "Alteración del líquido amniótico"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b14]
|
||||
etiqueta = "Reactivo B14"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.migrana]
|
||||
etiqueta = "Migraña"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b15]
|
||||
etiqueta = "Reactivo B15"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.proceso_proinflamatorio]
|
||||
etiqueta = "Proceso proinflamatorio"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b16b]
|
||||
etiqueta = "Reactivo B16b"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.tabaquismo_gestacion]
|
||||
etiqueta = "Tabaquismo en la gestación"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b18]
|
||||
etiqueta = "Reactivo B18"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.trastorno_neurologico]
|
||||
etiqueta = "Trastorno neurológico"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.rrb_a3]
|
||||
etiqueta = "Entonación de las vocalizaciones o verbalizaciones"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[nota_medica]
|
||||
etiqueta = "Nota médica"
|
||||
[ados2.resultados.rrb_a4]
|
||||
etiqueta = "Ecolalia inmediata"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[nota_medica.resultados.diagnostico]
|
||||
[ados2.resultados.rrb_a5]
|
||||
etiqueta = "Uso estereotipado o idiosincrásico de palabras o frases"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[ados2.resultados.rrb_d1]
|
||||
etiqueta = "Interés sensorial inusual en los materiales de juego o en las personas"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[ados2.resultados.rrb_d2]
|
||||
etiqueta = "Manierismos de manos, dedos y otros manierismos complejos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[ados2.resultados.rrb_d4]
|
||||
etiqueta = "Intereses inusualmente repetitivos o conductas estereotipadas"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[ados2.resultados.rrb_d5]
|
||||
etiqueta = "Reactivo D5"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[evaluacion_neuropediatrica]
|
||||
etiqueta = "Evaluación neuropediátrica"
|
||||
codigos_hospital = ["NEUROPEDIATRIA"]
|
||||
|
||||
[evaluacion_neuropediatrica.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.
|
||||
# The EEG: what its analysis writes. On the recording (`toma`), the sleep, channels, duration, the five quality
|
||||
# criteria and each metric's measured value; on each electrode (`parte`, `codigo_fuente` the electrode), the metric's
|
||||
# z-score there, under the same result.
|
||||
[eeg]
|
||||
etiqueta = "Electroencefalograma"
|
||||
codigos_hospital = ["EEG"]
|
||||
|
||||
[eeg.resultados.con_sueno]
|
||||
etiqueta = "Registro con sueño"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.canales]
|
||||
etiqueta = "Canales"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.duracion_min]
|
||||
etiqueta = "Duración del registro"
|
||||
tipo_valor = "numero"
|
||||
unidad = "min"
|
||||
|
||||
[eeg.resultados.calidad_amplitud]
|
||||
etiqueta = "Canales con amplitud extrema"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.calidad_alta_frecuencia]
|
||||
etiqueta = "Ruido de alta frecuencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.calidad_correlacion]
|
||||
etiqueta = "Baja correlación entre canales"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.calidad_sin_senal]
|
||||
etiqueta = "Canales planos o sin señal"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.calidad_linea]
|
||||
etiqueta = "Ruido de la línea eléctrica"
|
||||
tipo_valor = "numero"
|
||||
unidad = "dB"
|
||||
|
||||
[eeg.resultados.ritmo_posterior]
|
||||
etiqueta = "Ritmo posterior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2]
|
||||
etiqueta = "Husos de sueño N2"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3]
|
||||
etiqueta = "Husos de sueño N3"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos]
|
||||
etiqueta = "Picos paroxísticos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior]
|
||||
etiqueta = "Gradiente anteroposterior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "razón posterior/anterior"
|
||||
|
||||
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
|
||||
[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"
|
||||
|
||||
@@ -17,7 +17,6 @@ class ArtifactKind(str, Enum):
|
||||
METODO_ANALITICO = "METODO_ANALITICO"
|
||||
BALANCE_CLASES = "BALANCE_CLASES"
|
||||
CONFIANZA_SALIDA = "CONFIANZA_SALIDA"
|
||||
ONNX_CHECKPOINT = "ONNX_CHECKPOINT"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
|
||||
@@ -9,11 +9,20 @@ 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).
|
||||
|
||||
How each source writes those codes lives apart, in the database: `cat_sistema_fuente` (who sends the data) and
|
||||
`cat_mapeo` (FHIR's `ConceptMap`: a source's study code, a caption or a spelling, to our code). Those rows are edited
|
||||
from the application, never by a deploy; the TOML only seeds the missing ones. A row is never deleted: a correction
|
||||
closes it (`vigente_hasta`) and adds another.
|
||||
"""
|
||||
|
||||
from sqlalchemy import CheckConstraint
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import CheckConstraint, ForeignKeyConstraint, Index, UniqueConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
|
||||
# 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`
|
||||
@@ -24,6 +33,12 @@ TIPOS_DE_VALOR = (
|
||||
"externo", # un código de otro sistema (`sistema`, p. ej. CIE-10), sin catálogo propio
|
||||
)
|
||||
ESTADOS_DE_VALOR = ("vigente", "retirado")
|
||||
# What a source form maps to (`cat_mapeo.clase`).
|
||||
CLASES_DE_MAPEO = (
|
||||
"estudio", # a source's study or test code -> `estudio_id`
|
||||
"etiqueta", # a caption a result is printed under -> `resultado_id`
|
||||
"valor", # a spelling or code of a value -> `resultado_id` and `valor_id`
|
||||
)
|
||||
|
||||
|
||||
class CatEstudioBase(SQLModel):
|
||||
@@ -66,3 +81,61 @@ def estado_de_valor_conocido() -> CheckConstraint:
|
||||
return CheckConstraint(
|
||||
"estado IN (" + ", ".join(f"'{e}'" for e in ESTADOS_DE_VALOR) + ")", name="ck_cat_valor_estado"
|
||||
)
|
||||
|
||||
|
||||
class CatSistemaFuenteBase(SQLModel):
|
||||
"""Who sends the data: a lab, the record's header, a radiology system. A provider change is a new row."""
|
||||
|
||||
sistema_fuente_id: str = Field(primary_key=True, max_length=64)
|
||||
etiqueta: str
|
||||
fuente_tabla: str | None = Field(default=None, max_length=64) # its staging table; None: any
|
||||
vigente_desde: date # first document date it applies to
|
||||
vigente_hasta: date | None = None # last one; None while current
|
||||
|
||||
|
||||
class CatMapeoBase(SQLModel):
|
||||
"""How a source system writes one of our codes (FHIR `ConceptMap`, one element), while it's in force."""
|
||||
|
||||
mapeo_id: int | None = Field(default=None, primary_key=True)
|
||||
sistema_fuente_id: str = Field(foreign_key="cat_sistema_fuente.sistema_fuente_id", max_length=64)
|
||||
clase: str = Field(max_length=16) # one of CLASES_DE_MAPEO
|
||||
forma: str = Field(max_length=255) # as the source writes it
|
||||
forma_normalizada: str = Field(max_length=255) # uppercase, without accents, single spaces: what is compared
|
||||
estudio_id: str | None = Field(default=None, foreign_key="cat_estudio.estudio_id", max_length=64)
|
||||
resultado_id: str | None = Field(default=None, foreign_key="cat_resultado.resultado_id", max_length=128)
|
||||
valor_id: str | None = Field(default=None, max_length=64)
|
||||
vigente_desde: date
|
||||
vigente_hasta: date | None = None
|
||||
registrado_por: str = Field(max_length=64) # "catalogo" for a row seeded from the TOML
|
||||
registrado_en: datetime = Field(sa_type=FechaHoraUTC)
|
||||
motivo: str | None = None
|
||||
|
||||
|
||||
def vigencia_ordenada(tabla: str) -> CheckConstraint:
|
||||
"""`vigente_hasta`, if any, isn't before `vigente_desde`."""
|
||||
return CheckConstraint("vigente_hasta IS NULL OR vigente_hasta >= vigente_desde", name=f"ck_{tabla}_vigencia")
|
||||
|
||||
|
||||
def reglas_de_mapeo() -> tuple:
|
||||
"""`cat_mapeo`'s constraints: a known class with the target it needs, a value that exists, one row per form and
|
||||
start date. Overlapping validities with different targets are checked by whoever writes and by dbt's tests:
|
||||
no portable constraint expresses them."""
|
||||
clases = ", ".join(f"'{c}'" for c in CLASES_DE_MAPEO)
|
||||
return (
|
||||
CheckConstraint(f"clase IN ({clases})", name="ck_cat_mapeo_clase"),
|
||||
CheckConstraint(
|
||||
"(clase = 'estudio' AND estudio_id IS NOT NULL AND resultado_id IS NULL AND valor_id IS NULL)"
|
||||
" OR (clase = 'etiqueta' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NULL)"
|
||||
" OR (clase = 'valor' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NOT NULL)",
|
||||
name="ck_cat_mapeo_destino",
|
||||
),
|
||||
vigencia_ordenada("cat_mapeo"),
|
||||
ForeignKeyConstraint(
|
||||
["resultado_id", "valor_id"], ["cat_valor.resultado_id", "cat_valor.valor_id"], name="fk_cat_mapeo_valor"
|
||||
),
|
||||
UniqueConstraint(
|
||||
"sistema_fuente_id", "clase", "resultado_id", "estudio_id", "forma_normalizada", "vigente_desde",
|
||||
name="uq_cat_mapeo",
|
||||
),
|
||||
Index("ix_cat_mapeo_busqueda", "sistema_fuente_id", "resultado_id", "forma_normalizada"),
|
||||
)
|
||||
|
||||
@@ -130,7 +130,7 @@ def evaluacion_unica() -> UniqueConstraint:
|
||||
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
|
||||
Las declara cada proyecto (`webapi.orchestration.tables.<proyecto>.COHORTES`); el ciclo las lee
|
||||
y Persistance las escribe.
|
||||
"""
|
||||
|
||||
|
||||
+31
-297
@@ -1,327 +1,61 @@
|
||||
"""Vocabularios controlados del proyecto TEA.
|
||||
"""Controlled vocabularies of TEA's staging (spec/tablas_TEA.md).
|
||||
|
||||
Capa Core: sin importaciones de infraestructura. Seguro de importar
|
||||
desde cualquier módulo de src/.
|
||||
|
||||
Generado desde spec/tablas_TEA.md. No editar a mano.
|
||||
Core layer: no infrastructure imports.
|
||||
"""
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Parentesco(str, Enum):
|
||||
"""pac_parentesco in table pacientes."""
|
||||
HIJO = "HIJO"
|
||||
HIJA = "HIJA"
|
||||
HIJASTRO = "HIJASTRO"
|
||||
TUTELADO = "TUTELADO"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class SexoBiologico(str, Enum):
|
||||
"""pac_sexo in table pacientes."""
|
||||
F = "F"
|
||||
M = "M"
|
||||
I = "I"
|
||||
|
||||
|
||||
class Especialidad(str, Enum):
|
||||
"""ord_especialidad in table ordenes_estudio."""
|
||||
NEUROLOGIA_PEDIATRICA = "NEUROLOGIA_PEDIATRICA"
|
||||
PEDIATRIA = "PEDIATRIA"
|
||||
PSICOLOGIA = "PSICOLOGIA"
|
||||
PSIQUIATRIA_INFANTIL = "PSIQUIATRIA_INFANTIL"
|
||||
AUDIOLOGIA = "AUDIOLOGIA"
|
||||
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
|
||||
ENFERMERIA = "ENFERMERIA"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class TipoEstudio(str, Enum):
|
||||
"""ord_tipo_estudio in table ordenes_estudio."""
|
||||
ELECTROENCEFALOGRAMA = "ELECTROENCEFALOGRAMA"
|
||||
POTENCIALES_EVOCADOS_AUDITIVOS = "POTENCIALES_EVOCADOS_AUDITIVOS"
|
||||
EVALUACION_PSICOLOGICA_TEA = "EVALUACION_PSICOLOGICA_TEA"
|
||||
OTRO = "OTRO"
|
||||
ADOS2 = "ADOS2"
|
||||
NEUROPEDIATRIA = "NEUROPEDIATRIA"
|
||||
EEG = "EEG"
|
||||
|
||||
|
||||
# How the hospital writes each study, normalized (upper case, without accents) before it is looked up.
|
||||
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",
|
||||
"ADOS-2": "ADOS2",
|
||||
"ADOS 2": "ADOS2",
|
||||
"EVALUACION PSICOLOGICA": "ADOS2",
|
||||
"EVALUACION_PSICOLOGICA_TEA": "ADOS2",
|
||||
"NEUROLOGIA PEDIATRICA": "NEUROPEDIATRIA",
|
||||
"NEUROLOGIA_PEDIATRICA": "NEUROPEDIATRIA",
|
||||
"EVALUACION NEUROPEDIATRICA": "NEUROPEDIATRIA",
|
||||
"ELECTROENCEFALOGRAMA": "EEG",
|
||||
}
|
||||
|
||||
|
||||
class EstatusEstudio(str, Enum):
|
||||
"""ord_estatus in table ordenes_estudio."""
|
||||
SOLICITADO = "SOLICITADO"
|
||||
EN_PROCESO = "EN_PROCESO"
|
||||
REALIZADO = "REALIZADO"
|
||||
RESULTADO_DISPONIBLE = "RESULTADO_DISPONIBLE"
|
||||
CANCELADO = "CANCELADO"
|
||||
NO_ACUDIO = "NO_ACUDIO"
|
||||
|
||||
|
||||
class VentanaMadurativa(str, Enum):
|
||||
"""ord_ventana_madurativa in table ordenes_estudio."""
|
||||
V1_16_23 = "V1_16_23"
|
||||
V2_24_30 = "V2_24_30"
|
||||
V3_31_36 = "V3_31_36"
|
||||
FUERA_DE_RANGO = "FUERA_DE_RANGO"
|
||||
|
||||
|
||||
class TipoNota(str, Enum):
|
||||
"""nm_tipo_nota in table nota_medica."""
|
||||
PRIMERA_VEZ = "PRIMERA_VEZ"
|
||||
TAMIZAJE = "TAMIZAJE"
|
||||
INTERPRETACION_EEG = "INTERPRETACION_EEG"
|
||||
TRATAMIENTO = "TRATAMIENTO"
|
||||
SEGUIMIENTO = "SEGUIMIENTO"
|
||||
INTERCONSULTA = "INTERCONSULTA"
|
||||
URGENCIA = "URGENCIA"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class Pronostico(str, Enum):
|
||||
"""nm_pronostico in table nota_medica."""
|
||||
BUENO = "BUENO"
|
||||
RESERVADO = "RESERVADO"
|
||||
MALO = "MALO"
|
||||
NO_ESPECIFICADO = "NO_ESPECIFICADO"
|
||||
|
||||
|
||||
class InstrumentoTamizaje(str, Enum):
|
||||
"""psi_instrumento_tamizaje in table evaluacion_psicologica."""
|
||||
M_CHAT_R = "M_CHAT_R"
|
||||
M_CHAT_RF = "M_CHAT_RF"
|
||||
OTRO = "OTRO"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class NivelRiesgoTamizaje(str, Enum):
|
||||
"""psi_tamizaje_riesgo in table evaluacion_psicologica."""
|
||||
BAJO = "BAJO"
|
||||
MEDIO = "MEDIO"
|
||||
ALTO = "ALTO"
|
||||
NO_APLICA = "NO_APLICA"
|
||||
|
||||
|
||||
class ModuloAdos2(str, Enum):
|
||||
"""psi_ados2_modulo in table evaluacion_psicologica."""
|
||||
"""ado_modulo in table ados2."""
|
||||
TODDLER = "TODDLER"
|
||||
MODULO_1 = "MODULO_1"
|
||||
MODULO_2 = "MODULO_2"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
MODULO_3 = "MODULO_3"
|
||||
|
||||
|
||||
class ClasificacionAdos2(str, Enum):
|
||||
"""psi_ados2_clasificacion in table evaluacion_psicologica."""
|
||||
NO_TEA = "NO_TEA"
|
||||
"""ado_clasificacion in table ados2."""
|
||||
NO_ESPECTRO = "NO_ESPECTRO"
|
||||
ESPECTRO_AUTISTA = "ESPECTRO_AUTISTA"
|
||||
AUTISMO = "AUTISMO"
|
||||
PREOCUPACION_LEVE_MODERADA = "PREOCUPACION_LEVE_MODERADA"
|
||||
PREOCUPACION_SEVERA = "PREOCUPACION_SEVERA"
|
||||
|
||||
|
||||
class GradoHipoacusia(str, Enum):
|
||||
"""pea_grado_hipoacusia in table potenciales_evocados_auditivos."""
|
||||
NORMAL = "NORMAL"
|
||||
LEVE = "LEVE"
|
||||
MODERADA = "MODERADA"
|
||||
SEVERA = "SEVERA"
|
||||
PROFUNDA = "PROFUNDA"
|
||||
NO_CONCLUYENTE = "NO_CONCLUYENTE"
|
||||
CLASIFICACION_ADOS2_ALIAS: dict[str, str] = {"NO_TEA": "NO_ESPECTRO", "NO ESPECTRO": "NO_ESPECTRO"}
|
||||
|
||||
|
||||
class ClasificacionEeg(str, Enum):
|
||||
"""eeg_clasificacion in table eeg_estudio."""
|
||||
SIN_REFERENCIA_AURICULAR = "SIN_REFERENCIA_AURICULAR"
|
||||
class MetricaEeg(str, Enum):
|
||||
"""met_codigo in table eeg_metrica."""
|
||||
RITMO_POSTERIOR = "RITMO_POSTERIOR"
|
||||
HUSOS_SUENO_N2 = "HUSOS_SUENO_N2"
|
||||
HUSOS_SUENO_N3 = "HUSOS_SUENO_N3"
|
||||
PICOS_PAROXISTICOS = "PICOS_PAROXISTICOS"
|
||||
GRADIENTE_ANTEROPOSTERIOR = "GRADIENTE_ANTEROPOSTERIOR"
|
||||
|
||||
|
||||
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"
|
||||
NOTA_MEDICA = "NOTA_MEDICA"
|
||||
AMBAS = "AMBAS"
|
||||
NINGUNA = "NINGUNA"
|
||||
|
||||
|
||||
class EstadoRegistroEeg(str, Enum):
|
||||
"""eeg_estado_registro in table eeg_estudio."""
|
||||
VIGILIA = "VIGILIA"
|
||||
SUENO_ESPONTANEO = "SUENO_ESPONTANEO"
|
||||
SUENO_INDUCIDO = "SUENO_INDUCIDO"
|
||||
MIXTO = "MIXTO"
|
||||
NO_ESPECIFICADO = "NO_ESPECIFICADO"
|
||||
|
||||
|
||||
class CalidadTecnicaEeg(str, Enum):
|
||||
"""eeg_calidad_tecnica in table eeg_estudio."""
|
||||
SATISFACTORIA = "SATISFACTORIA"
|
||||
LIMITADA_POR_ARTEFACTO = "LIMITADA_POR_ARTEFACTO"
|
||||
LIMITADA_POR_COLABORACION = "LIMITADA_POR_COLABORACION"
|
||||
NO_VALORABLE = "NO_VALORABLE"
|
||||
NO_ESPECIFICADA = "NO_ESPECIFICADA"
|
||||
|
||||
|
||||
class Simetria(str, Enum):
|
||||
"""eeg_simetria in table eeg_estudio."""
|
||||
SIMETRICO = "SIMETRICO"
|
||||
ASIMETRICO_IZQUIERDO = "ASIMETRICO_IZQUIERDO"
|
||||
ASIMETRICO_DERECHO = "ASIMETRICO_DERECHO"
|
||||
NO_ESPECIFICADA = "NO_ESPECIFICADA"
|
||||
|
||||
|
||||
class TipoGrafoelemento(str, Enum):
|
||||
"""eeg_tipo_grafoelemento in table eeg_estudio."""
|
||||
NINGUNO = "NINGUNO"
|
||||
ESPIGA = "ESPIGA"
|
||||
ONDA_AGUDA = "ONDA_AGUDA"
|
||||
COMPLEJO_ESPIGA_ONDA = "COMPLEJO_ESPIGA_ONDA"
|
||||
COMPLEJO_POLIESPIGA_ONDA = "COMPLEJO_POLIESPIGA_ONDA"
|
||||
PUNTA_ONDA_LENTA = "PUNTA_ONDA_LENTA"
|
||||
DESCARGA_RITMICA = "DESCARGA_RITMICA"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class DistribucionAnormalidad(str, Enum):
|
||||
"""eeg_distribucion_anormalidad in table eeg_estudio."""
|
||||
FOCAL = "FOCAL"
|
||||
MULTIFOCAL = "MULTIFOCAL"
|
||||
GENERALIZADA = "GENERALIZADA"
|
||||
LATERALIZADA = "LATERALIZADA"
|
||||
NO_ESPECIFICADA = "NO_ESPECIFICADA"
|
||||
|
||||
|
||||
class Lentificacion(str, Enum):
|
||||
"""eeg_lentificacion in table eeg_estudio."""
|
||||
NINGUNA = "NINGUNA"
|
||||
FOCAL = "FOCAL"
|
||||
GENERALIZADA = "GENERALIZADA"
|
||||
INTERMITENTE = "INTERMITENTE"
|
||||
|
||||
|
||||
class RespuestaFotoestimulacion(str, Enum):
|
||||
"""eeg_respuesta_fotoestimulacion in table eeg_estudio."""
|
||||
NORMAL = "NORMAL"
|
||||
RESPUESTA_FOTOPAROXISTICA = "RESPUESTA_FOTOPAROXISTICA"
|
||||
SIN_RESPUESTA = "SIN_RESPUESTA"
|
||||
NO_PRACTICADA = "NO_PRACTICADA"
|
||||
|
||||
|
||||
class ConclusionEeg(str, Enum):
|
||||
"""eeg_conclusion_categoria in table eeg_estudio."""
|
||||
NORMAL_PARA_LA_EDAD = "NORMAL_PARA_LA_EDAD"
|
||||
NORMAL_CON_VARIANTES = "NORMAL_CON_VARIANTES"
|
||||
ANORMAL_EPILEPTIFORME = "ANORMAL_EPILEPTIFORME"
|
||||
ANORMAL_NO_EPILEPTIFORME = "ANORMAL_NO_EPILEPTIFORME"
|
||||
ANORMAL_MIXTO = "ANORMAL_MIXTO"
|
||||
NO_CONCLUYENTE = "NO_CONCLUYENTE"
|
||||
|
||||
|
||||
class FuenteAntecedenteMaterno(str, Enum):
|
||||
"""amg_fuente_antecedente in table antecedentes_maternos_gestacion."""
|
||||
EXPEDIENTE_MATERNO = "EXPEDIENTE_MATERNO"
|
||||
INTERROGATORIO_NM11 = "INTERROGATORIO_NM11"
|
||||
AMBAS = "AMBAS"
|
||||
NO_LOCALIZADO = "NO_LOCALIZADO"
|
||||
|
||||
|
||||
class CategoriaPesoMaterno(str, Enum):
|
||||
"""amg_categoria_peso_materno in table antecedentes_maternos_gestacion."""
|
||||
BAJO_PESO = "BAJO_PESO"
|
||||
NORMAL = "NORMAL"
|
||||
SOBREPESO = "SOBREPESO"
|
||||
OBESIDAD_I = "OBESIDAD_I"
|
||||
OBESIDAD_II = "OBESIDAD_II"
|
||||
OBESIDAD_III = "OBESIDAD_III"
|
||||
NO_REGISTRADA = "NO_REGISTRADA"
|
||||
|
||||
|
||||
class TipoEmbarazo(str, Enum):
|
||||
"""amg_embarazo_multiple in table antecedentes_maternos_gestacion."""
|
||||
UNICO = "UNICO"
|
||||
GEMELAR = "GEMELAR"
|
||||
TRIPLE_O_MAS = "TRIPLE_O_MAS"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class TrastornoHipertensivoGestacion(str, Enum):
|
||||
"""amg_hipertension_preeclampsia in table antecedentes_maternos_gestacion."""
|
||||
NINGUNO = "NINGUNO"
|
||||
HIPERTENSION_GESTACIONAL = "HIPERTENSION_GESTACIONAL"
|
||||
PREECLAMPSIA = "PREECLAMPSIA"
|
||||
ECLAMPSIA = "ECLAMPSIA"
|
||||
SINDROME_HELLP = "SINDROME_HELLP"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class VolumenLiquidoAmniotico(str, Enum):
|
||||
"""amg_liquido_amniotico in table antecedentes_maternos_gestacion."""
|
||||
NORMAL = "NORMAL"
|
||||
OLIGOHIDRAMNIOS = "OLIGOHIDRAMNIOS"
|
||||
POLIHIDRAMNIOS = "POLIHIDRAMNIOS"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class FuenteAntecedenteNeonatal(str, Enum):
|
||||
"""pnn_fuente_antecedente in table parto_neonatal."""
|
||||
NOTA_RECIEN_NACIDO = "NOTA_RECIEN_NACIDO"
|
||||
NOTA_RESOLUCION_OBSTETRICA = "NOTA_RESOLUCION_OBSTETRICA"
|
||||
INTERROGATORIO_NM11 = "INTERROGATORIO_NM11"
|
||||
AMBAS = "AMBAS"
|
||||
NO_LOCALIZADA = "NO_LOCALIZADA"
|
||||
|
||||
|
||||
class TipoParto(str, Enum):
|
||||
"""pnn_tipo_parto in table parto_neonatal."""
|
||||
VAGINAL_ESPONTANEO = "VAGINAL_ESPONTANEO"
|
||||
VAGINAL_INSTRUMENTADO = "VAGINAL_INSTRUMENTADO"
|
||||
CESAREA_ELECTIVA = "CESAREA_ELECTIVA"
|
||||
CESAREA_URGENCIA = "CESAREA_URGENCIA"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class ComplicacionIntraparto(str, Enum):
|
||||
"""pnn_complicacion_tipo in table parto_neonatal."""
|
||||
NINGUNA = "NINGUNA"
|
||||
HIPOXIA = "HIPOXIA"
|
||||
ISQUEMIA = "ISQUEMIA"
|
||||
TRAUMA_OBSTETRICO = "TRAUMA_OBSTETRICO"
|
||||
CIRCULAR_DE_CORDON = "CIRCULAR_DE_CORDON"
|
||||
SUFRIMIENTO_FETAL_AGUDO = "SUFRIMIENTO_FETAL_AGUDO"
|
||||
OTRA = "OTRA"
|
||||
|
||||
|
||||
class ClasificacionEdadGestacional(str, Enum):
|
||||
"""pnn_clasificacion_eg in table parto_neonatal."""
|
||||
PRETERMINO_EXTREMO = "PRETERMINO_EXTREMO"
|
||||
MUY_PRETERMINO = "MUY_PRETERMINO"
|
||||
PRETERMINO_TARDIO = "PRETERMINO_TARDIO"
|
||||
TERMINO = "TERMINO"
|
||||
POSTERMINO = "POSTERMINO"
|
||||
NO_DETERMINADA = "NO_DETERMINADA"
|
||||
|
||||
|
||||
class TamanoParaEdadGestacional(str, Enum):
|
||||
"""pnn_tamano_para_eg in table parto_neonatal."""
|
||||
PEQUENO = "PEQUENO"
|
||||
ADECUADO = "ADECUADO"
|
||||
GRANDE = "GRANDE"
|
||||
NO_DETERMINADO = "NO_DETERMINADO"
|
||||
# The electrodes of the 10-20 system an electrode value can name (mel_electrodo).
|
||||
ELECTRODOS_10_20 = (
|
||||
"Fp1", "Fp2", "F7", "F3", "Fz", "F4", "F8", "T3", "C3", "Cz", "C4", "T4",
|
||||
"T5", "P3", "Pz", "P4", "T6", "O1", "O2",
|
||||
)
|
||||
|
||||
@@ -19,10 +19,14 @@ from core.indicadores.cohortes import (
|
||||
)
|
||||
from core.indicadores.catalogos import (
|
||||
CatEstudioBase,
|
||||
CatMapeoBase,
|
||||
CatResultadoBase,
|
||||
CatSistemaFuenteBase,
|
||||
CatValorBase,
|
||||
estado_de_valor_conocido,
|
||||
reglas_de_mapeo,
|
||||
tipo_de_valor_conocido,
|
||||
vigencia_ordenada,
|
||||
)
|
||||
from core.indicadores.plata import (
|
||||
ObservacionClinicaBase,
|
||||
@@ -162,6 +166,16 @@ class CatValor(TeaModel, CatValorBase, table=True):
|
||||
__table_args__ = (estado_de_valor_conocido(),)
|
||||
|
||||
|
||||
class CatSistemaFuente(TeaModel, CatSistemaFuenteBase, table=True):
|
||||
__tablename__ = "cat_sistema_fuente"
|
||||
__table_args__ = (vigencia_ordenada("cat_sistema_fuente"),)
|
||||
|
||||
|
||||
class CatMapeo(TeaModel, CatMapeoBase, table=True):
|
||||
__tablename__ = "cat_mapeo"
|
||||
__table_args__ = reglas_de_mapeo()
|
||||
|
||||
|
||||
# --- La plata de dos tablas (F5, ADR-MD-007) ---
|
||||
|
||||
|
||||
|
||||
+134
-338
@@ -1,18 +1,52 @@
|
||||
"""TEA staging tables (data dictionary: spec/tablas_TEA.md).
|
||||
|
||||
Permissive storage: every domain field is optional so a load never rejects a
|
||||
row; booleans are INTEGER and enums TEXT. Coercion and validation happen in
|
||||
the import schemas (WebApi/webapi/imports/schemas/tea).
|
||||
One table per kind of study: the M-CHAT, the ADOS-2, the neuropediatrics note and the EEG, with the patients and
|
||||
the orders. The EEG's quality criteria, channels, duration, sleep, metrics and electrode values are written by the
|
||||
EEG analysis from the stored EDF.
|
||||
|
||||
Permissive storage: every domain field is optional so a load never rejects a row; booleans are INTEGER and enums
|
||||
TEXT. Coercion and validation happen in the import schemas (WebApi/webapi/imports/schemas/tea).
|
||||
"""
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
|
||||
from core.tea.base import TeaModel
|
||||
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
|
||||
from core.tea.base import TeaModel
|
||||
|
||||
# The ADOS-2 items with an algorithm score: social affect (SA) and restricted and repetitive behaviour (RRB).
|
||||
ADOS2_ITEMS = (
|
||||
"sa_a2", "sa_a6", "sa_a7", "sa_a8", "sa_b1", "sa_b2", "sa_b3", "sa_b4", "sa_b5", "sa_b6", "sa_b7", "sa_b8",
|
||||
"sa_b9", "sa_b10", "sa_b11", "sa_b12", "sa_b13", "sa_b14", "sa_b15", "sa_b16b", "sa_b18",
|
||||
"rrb_a3", "rrb_a4", "rrb_a5", "rrb_d1", "rrb_d2", "rrb_d4", "rrb_d5",
|
||||
)
|
||||
|
||||
|
||||
def _uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def _id() -> Field:
|
||||
return Field(default_factory=_uuid, sa_column=sa.Column(sa.String(36), primary_key=True))
|
||||
|
||||
|
||||
def _text() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
|
||||
|
||||
def _int() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
|
||||
|
||||
def _float() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
|
||||
|
||||
def _date() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
|
||||
|
||||
class Pacientes(TeaModel, table=True):
|
||||
@@ -22,366 +56,128 @@ class Pacientes(TeaModel, table=True):
|
||||
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))
|
||||
pac_parentesco: 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))
|
||||
pac_sexo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_codigo_postal_vigente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_dependencia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pac_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pac_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_id_hospital: Optional[str] = _text()
|
||||
pac_fecha_nacimiento: Optional[date] = _date()
|
||||
|
||||
|
||||
class OrdenesEstudio(TeaModel, table=True):
|
||||
__tablename__ = "ordenes_estudio"
|
||||
|
||||
ord_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
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))
|
||||
# Bounded and indexed, unlike TEA's other unenforced Text references: it
|
||||
# is the natural key the import layer upserts/merges orders on.
|
||||
ord_id: Optional[str] = _id()
|
||||
ord_pac_id: Optional[int] = _int()
|
||||
# Bounded and indexed: the natural key the import layer 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))
|
||||
ord_diagnostico_asignado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_cie_asignado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_dias_vigencia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
ord_fecha_vencimiento: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
ord_tipo_estudio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_estatus: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_fecha_realizacion: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
ord_fecha_resultado: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
ord_dias_espera: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
ord_proveedor: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
ord_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
ord_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
ord_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_tipo_estudio: Optional[str] = _text() # TipoEstudio: ADOS2, NEUROPEDIATRIA, EEG
|
||||
ord_fecha: Optional[date] = _date()
|
||||
ord_pdf_blob: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob)) # the study's report, as PDF
|
||||
|
||||
|
||||
class NotaMedica(TeaModel, table=True):
|
||||
__tablename__ = "nota_medica"
|
||||
class Mchat(TeaModel, table=True):
|
||||
__tablename__ = "mchat"
|
||||
|
||||
nm_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
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))
|
||||
nm_fecha: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
nm_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_medico_tratante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_motivo_consulta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_interrogatorio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_regresion_referida: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_antecedente_familiar_tea: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_perimetro_cefalico: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_diagnostico_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_cie_codigo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_cie_descripcion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_tratamiento_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_receta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_plan_estudios: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_pronostico: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_masa_corporal: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_talla: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_imc_visita: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_frecuencia_cardiaca: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_frecuencia_respiratoria: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_presion_arterial_sistolica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_presion_arterial_diastolica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_temperatura: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
nm_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
nm_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
mch_id: Optional[str] = _id()
|
||||
mch_pac_id: Optional[int] = _int()
|
||||
mch_ord_id: Optional[str] = _text()
|
||||
mch_fecha: Optional[date] = _date()
|
||||
mch_puntaje: Optional[int] = _int() # 0 to 20
|
||||
|
||||
|
||||
class EvaluacionPsicologica(TeaModel, table=True):
|
||||
__tablename__ = "evaluacion_psicologica"
|
||||
class Ados2(TeaModel, table=True):
|
||||
__tablename__ = "ados2"
|
||||
|
||||
psi_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
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[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))
|
||||
psi_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_instrumento_tamizaje: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_tamizaje_puntaje: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_tamizaje_riesgo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_ados2_modulo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
# ADOS-2 item columns (data dictionary, annex B); the valid range and which
|
||||
# items apply depend on psi_ados2_modulo.
|
||||
psi_ados2_sa_a2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_a6: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_a7: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_a8: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b1: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b3: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b6: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b7: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b8: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b9: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b10: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b11: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b12: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b13: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b14: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b15: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b16b: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b18: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_a3: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_a4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_a5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_d1: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_d2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_d4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_d5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_total: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_css: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_css_sa: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_css_rrb: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_clasificacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_rgd: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_cociente_desarrollo: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
psi_css_umbral_aplicado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_caso_confirmado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_cars_total: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
psi_otros_instrumentos: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_regresion_desarrollo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_diagnostico_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
psi_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
psi_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
ado_id: Optional[str] = _id()
|
||||
ado_pac_id: Optional[int] = _int()
|
||||
ado_ord_id: Optional[str] = _text()
|
||||
ado_fecha: Optional[date] = _date()
|
||||
ado_modulo: Optional[str] = _text()
|
||||
# Within a module the algorithm depends on the child's language level (item A1).
|
||||
ado_algoritmo: Optional[str] = _text()
|
||||
ado_css: Optional[int] = _int() # 1 to 10
|
||||
ado_clasificacion: Optional[str] = _text()
|
||||
# Item scores, 0 to 3. The domain subtotals and the total are sums of their algorithm scores.
|
||||
ado_sa_a2: Optional[int] = _int()
|
||||
ado_sa_a6: Optional[int] = _int()
|
||||
ado_sa_a7: Optional[int] = _int()
|
||||
ado_sa_a8: Optional[int] = _int()
|
||||
ado_sa_b1: Optional[int] = _int()
|
||||
ado_sa_b2: Optional[int] = _int()
|
||||
ado_sa_b3: Optional[int] = _int()
|
||||
ado_sa_b4: Optional[int] = _int()
|
||||
ado_sa_b5: Optional[int] = _int()
|
||||
ado_sa_b6: Optional[int] = _int()
|
||||
ado_sa_b7: Optional[int] = _int()
|
||||
ado_sa_b8: Optional[int] = _int()
|
||||
ado_sa_b9: Optional[int] = _int()
|
||||
ado_sa_b10: Optional[int] = _int()
|
||||
ado_sa_b11: Optional[int] = _int()
|
||||
ado_sa_b12: Optional[int] = _int()
|
||||
ado_sa_b13: Optional[int] = _int()
|
||||
ado_sa_b14: Optional[int] = _int()
|
||||
ado_sa_b15: Optional[int] = _int()
|
||||
ado_sa_b16b: Optional[int] = _int()
|
||||
ado_sa_b18: Optional[int] = _int()
|
||||
ado_rrb_a3: Optional[int] = _int()
|
||||
ado_rrb_a4: Optional[int] = _int()
|
||||
ado_rrb_a5: Optional[int] = _int()
|
||||
ado_rrb_d1: Optional[int] = _int()
|
||||
ado_rrb_d2: Optional[int] = _int()
|
||||
ado_rrb_d4: Optional[int] = _int()
|
||||
ado_rrb_d5: Optional[int] = _int()
|
||||
|
||||
|
||||
class PotencialesEvocadosAuditivos(TeaModel, table=True):
|
||||
__tablename__ = "potenciales_evocados_auditivos"
|
||||
class EvaluacionNeuropediatrica(TeaModel, table=True):
|
||||
__tablename__ = "evaluacion_neuropediatrica"
|
||||
|
||||
pea_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
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[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))
|
||||
pea_umbral_oi: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pea_latencia_v_od: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_latencia_v_oi: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_interpico_i_v_od: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_interpico_i_v_oi: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_grado_hipoacusia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_conclusion_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_flag_diferencial_auditivo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pea_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pea_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
neu_id: Optional[str] = _id()
|
||||
neu_pac_id: Optional[int] = _int()
|
||||
neu_ord_id: Optional[str] = _text()
|
||||
neu_fecha: Optional[date] = _date()
|
||||
neu_cie_codigo: Optional[str] = _text()
|
||||
|
||||
|
||||
class EegEstudio(TeaModel, table=True):
|
||||
__tablename__ = "eeg_estudio"
|
||||
class Eeg(TeaModel, table=True):
|
||||
__tablename__ = "eeg"
|
||||
|
||||
eeg_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
eeg_ord_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_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))
|
||||
eeg_dias_respuesta: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_medico_interpreta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_estado_registro: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
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[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))
|
||||
eeg_ritmo_base_amplitud: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_simetria: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_anormalidad_presente: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_actividad_epileptiforme: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_tipo_grafoelemento: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_distribucion_anormalidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_localizacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_activacion_sueno: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_lentificacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_crisis_registradas: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
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))
|
||||
# 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: Optional[str] = _id()
|
||||
eeg_pac_id: Optional[int] = _int()
|
||||
eeg_ord_id: Optional[str] = _text()
|
||||
# Bounded and indexed: the natural key several sources (a report, the EDF itself) land in the same row by.
|
||||
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))
|
||||
eeg_fecha_estudio: Optional[date] = _date()
|
||||
# Written by the EEG analysis.
|
||||
eeg_con_sueno: Optional[int] = _int()
|
||||
eeg_canales: Optional[int] = _int()
|
||||
eeg_duracion_min: Optional[float] = _float()
|
||||
# Quality criteria: channels flagged by each one, and the line noise. An EEG is bad when any criterion is.
|
||||
eeg_canales_amplitud: Optional[int] = _int()
|
||||
eeg_canales_alta_frecuencia: Optional[int] = _int()
|
||||
eeg_canales_correlacion: Optional[int] = _int()
|
||||
eeg_canales_sin_senal: Optional[int] = _int()
|
||||
eeg_ruido_linea_db: Optional[float] = _float()
|
||||
eeg_estudio: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob)) # the EDF
|
||||
|
||||
|
||||
class EegSegmento(TeaModel, table=True):
|
||||
__tablename__ = "eeg_segmento"
|
||||
class EegMetrica(TeaModel, table=True):
|
||||
"""One metric the EEG analysis measured on an EEG. A null value is a metric that can't be evaluated."""
|
||||
|
||||
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))
|
||||
__tablename__ = "eeg_metrica"
|
||||
|
||||
met_id: Optional[str] = _id()
|
||||
met_eeg_id: Optional[str] = _text()
|
||||
met_codigo: Optional[str] = _text() # MetricaEeg
|
||||
met_valor: Optional[float] = _float()
|
||||
|
||||
|
||||
class InstrumentoAplicado(TeaModel, table=True):
|
||||
__tablename__ = "instrumento_aplicado"
|
||||
class EegMetricaElectrodo(TeaModel, table=True):
|
||||
"""A metric's value at one electrode of the 10-20 system."""
|
||||
|
||||
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))
|
||||
__tablename__ = "eeg_metrica_electrodo"
|
||||
|
||||
|
||||
class AntecedentesMaternosGestacion(TeaModel, table=True):
|
||||
__tablename__ = "antecedentes_maternos_gestacion"
|
||||
|
||||
amg_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
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))
|
||||
amg_imc_pregestacional: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
amg_categoria_peso_materno: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_tabaquismo_gestacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_acido_folico_preconcepcional: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_intervalo_intergenesico_meses: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_antecedente_aborto: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_embarazo_multiple: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_infeccion_gestacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_infeccion_tipo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_infeccion_hospitalizacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_diabetes_gestacional: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_hipertension_preeclampsia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_hipotiroidismo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_hipertiroidismo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_incompatibilidad_rh: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_crisis_convulsivas: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_proceso_proinflamatorio: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_enfermedad_autoinmune: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_migrana: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_asma: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_hipoxia_materna: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_estres_agudo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_trastorno_neurologico: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_liquido_amniotico: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_medicamentos_gestacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
amg_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
amg_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
amg_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
|
||||
|
||||
class PartoNeonatal(TeaModel, table=True):
|
||||
__tablename__ = "parto_neonatal"
|
||||
|
||||
pnn_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
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))
|
||||
pnn_complicacion_tipo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_peso_nacer_g: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_talla_nacer_cm: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_perimetro_cefalico_nacer_cm: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_edad_gestacional_sem: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_clasificacion_eg: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_tamano_para_eg: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_peso_nacer_zscore: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_apgar_1min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_apgar_5min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_ingreso_ucin: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_dias_ucin: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_encefalopatia_hipoxico_isquemica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_hipotermia_nacer: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_hiperbilirrubinemia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_fototerapia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_hipoglucemia_neonatal: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_anoxia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_sindrome_congenito: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_sindrome_congenito_desc: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_flag_riesgo_neonatal: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pnn_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pnn_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
mel_id: Optional[str] = _id()
|
||||
mel_met_id: Optional[str] = _text()
|
||||
mel_electrodo: Optional[str] = _text()
|
||||
mel_valor: Optional[float] = _float()
|
||||
|
||||
+59
-479
@@ -1,8 +1,12 @@
|
||||
# Diccionario de datos y reglas de validación — Proyecto TEA
|
||||
|
||||
Este documento describe la base de datos del proyecto. Para cada tabla se listan sus
|
||||
variables, el tipo de dato, la unidad (cuando aplica) y la validación que debe
|
||||
cumplir cada una.
|
||||
Este documento describe el staging del proyecto: una tabla por tipo de estudio (M-CHAT, ADOS-2, nota de
|
||||
neuropediatría y EEG), más los pacientes y las órdenes. Para cada tabla se listan sus variables, el tipo de dato,
|
||||
la unidad (cuando aplica) y la validación que cumple cada una al importarse. El almacenamiento es permisivo: todo
|
||||
campo es opcional y la validación ocurre en los esquemas de importación (`WebApi/webapi/imports/schemas/tea`).
|
||||
|
||||
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG a partir del EDF guardado: calidad,
|
||||
canales, duración, sueño, métricas y valores por electrodo.
|
||||
|
||||
---
|
||||
|
||||
@@ -12,27 +16,7 @@ cumplir cada una.
|
||||
|---|---|---|---|---|
|
||||
| `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`. | — |
|
||||
| `pac_fecha_nacimiento` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `pac_sexo` | TEXT | — | Catálogo cerrado `SexoBiologico`: `F, M, I`. | — |
|
||||
| `pac_codigo_postal_vigente` | TEXT | — | Debe quedar en 5 dígitos numéricos exactos (se completa con ceros a la izquierda si llega con menos). | — |
|
||||
| `pac_dependencia` | TEXT | — | — | — |
|
||||
| `pac_created_at` | DATETIME | — | — | — |
|
||||
| `pac_updated_at` | DATETIME | — | — | — |
|
||||
| `pac_fuente_sistema` | TEXT | — | — | — |
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -42,502 +26,98 @@ datos reales en ninguna base de TEA todavía.
|
||||
|---|---|---|---|---|
|
||||
| `ord_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `ord_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `ord_nota_medica_id` | TEXT | — | — | → `nota_medica.nm_id` |
|
||||
| `ord_id_hospital` | VARCHAR(64), indexado | — | Llave natural para `on_conflict=upsert`/`merge` al importar órdenes de varias fuentes. | — |
|
||||
| `ord_id_hospital` | VARCHAR(64), indexado | — | Llave natural para unir órdenes de varias fuentes al importar. | — |
|
||||
| `ord_tipo_estudio` | TEXT | — | Catálogo `TipoEstudio`: `ADOS2, NEUROPEDIATRIA, EEG`. | — |
|
||||
| `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`. | — |
|
||||
| `ord_diagnostico_asignado` | TEXT | — | — | — |
|
||||
| `ord_cie_asignado` | TEXT | — | Formato CIE: una letra mayúscula, dos dígitos, y opcionalmente un punto con uno o dos dígitos más (ejemplo: `A09.1`). | — |
|
||||
| `ord_dias_vigencia` | INTEGER | días | Entre 1 y 365. | — |
|
||||
| `ord_fecha_vencimiento` | DATE | — | Ver validación cruzada. | — |
|
||||
| `ord_proveedor` | TEXT | — | — | — |
|
||||
| `ord_tipo_estudio` | TEXT | — | Catálogo `TipoEstudio`: `ELECTROENCEFALOGRAMA, POTENCIALES_EVOCADOS_AUDITIVOS, EVALUACION_PSICOLOGICA_TEA, OTRO`. | — |
|
||||
| `ord_estatus` | TEXT | — | Catálogo `EstatusEstudio`: `SOLICITADO, EN_PROCESO, REALIZADO, RESULTADO_DISPONIBLE, CANCELADO, NO_ACUDIO`. | — |
|
||||
| `ord_fecha_realizacion` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
|
||||
| `ord_fecha_resultado` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
|
||||
| `ord_dias_espera` | INTEGER | días | Entre 0 y 180. | — |
|
||||
| `ord_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
| `ord_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`: `V1_16_23, V2_24_30, V3_31_36, FUERA_DE_RANGO`. Ver validación cruzada. | — |
|
||||
| `ord_pdf_ruta` | TEXT | — | — | — |
|
||||
| `ord_observaciones` | TEXT | — | — | — |
|
||||
| `ord_created_at` | DATETIME | — | — | — |
|
||||
| `ord_updated_at` | DATETIME | — | — | — |
|
||||
| `ord_fuente_sistema` | TEXT | — | — | — |
|
||||
|
||||
**Validaciones cruzadas de `ordenes_estudio`:**
|
||||
- `ord_fecha_vencimiento` debe ser igual a `ord_fecha + ord_dias_vigencia` días, cuando ambos valores existen.
|
||||
- `ord_fecha_realizacion` no puede ser anterior a `ord_fecha`.
|
||||
- `ord_fecha_resultado` no puede ser anterior a `ord_fecha_realizacion`.
|
||||
- `ord_ventana_madurativa` debe corresponder a `ord_edad_meses` según la tabla de ventanas (Anexo A).
|
||||
| `ord_pdf_blob` | BLOB (LONGBLOB en MySQL/MariaDB) | — | Informe del estudio en PDF, si la fuente lo trae. | — |
|
||||
|
||||
---
|
||||
|
||||
## 3. Tabla `nota_medica`
|
||||
## 3. Tabla `mchat`
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `nm_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `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`). | — |
|
||||
| `nm_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `nm_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
| `nm_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`. Ver validación cruzada. | — |
|
||||
| `nm_medico_tratante` | TEXT | — | — | — |
|
||||
| `nm_motivo_consulta` | TEXT | — | — | — |
|
||||
| `nm_interrogatorio` | TEXT | — | — | — |
|
||||
| `nm_regresion_referida` | BOOL | — | — | — |
|
||||
| `nm_antecedente_familiar_tea` | BOOL | — | — | — |
|
||||
| `nm_perimetro_cefalico` | FLOAT | cm | Entre 38.0 y 58.0. | — |
|
||||
| `nm_diagnostico_texto` | TEXT | — | — | — |
|
||||
| `nm_cie_codigo` | TEXT | — | Formato CIE: una letra mayúscula, dos dígitos, punto opcional con uno o dos dígitos más. | — |
|
||||
| `nm_cie_descripcion` | TEXT | — | — | — |
|
||||
| `nm_tratamiento_texto` | TEXT | — | — | — |
|
||||
| `nm_receta` | TEXT | — | — | — |
|
||||
| `nm_plan_estudios` | TEXT | — | — | — |
|
||||
| `nm_pronostico` | TEXT | — | Catálogo `Pronostico`: `BUENO, RESERVADO, MALO, NO_ESPECIFICADO`. | — |
|
||||
| `nm_observaciones` | TEXT | — | — | — |
|
||||
| `nm_masa_corporal` | FLOAT | kg | Entre 2.0 y 40.0. | — |
|
||||
| `nm_talla` | FLOAT | m | Entre 0.4 y 1.4. | — |
|
||||
| `nm_imc_visita` | FLOAT | kg/m² | Entre 5.0 y 40.0. Ver validación cruzada con peso y talla. | — |
|
||||
| `nm_frecuencia_cardiaca` | INTEGER | lpm | Entre 50 y 230. | — |
|
||||
| `nm_frecuencia_respiratoria` | INTEGER | rpm | Entre 10 y 80. | — |
|
||||
| `nm_presion_arterial_sistolica` | INTEGER | mmHg | Entre 45 y 160. Ver validación cruzada. | — |
|
||||
| `nm_presion_arterial_diastolica` | INTEGER | mmHg | Entre 25 y 110. Ver validación cruzada. | — |
|
||||
| `nm_temperatura` | FLOAT | °C | Entre 32.0 y 43.0. | — |
|
||||
| `nm_pdf_ruta` | TEXT | — | — | — |
|
||||
| `nm_created_at` | DATETIME | — | — | — |
|
||||
| `nm_updated_at` | DATETIME | — | — | — |
|
||||
| `nm_fuente_sistema` | TEXT | — | — | — |
|
||||
|
||||
**Validaciones cruzadas de `nota_medica`:**
|
||||
- La presión sistólica debe ser mayor que la diastólica.
|
||||
- `nm_imc_visita` debe ser aproximadamente igual a `nm_masa_corporal / nm_talla²` (tolerancia de 0.5).
|
||||
- `nm_ventana_madurativa` debe corresponder a `nm_edad_meses` (Anexo A).
|
||||
| `mch_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `mch_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `mch_ord_id` | TEXT | — | Casi siempre nulo: el M-CHAT rara vez tiene orden. | → `ordenes_estudio.ord_id` |
|
||||
| `mch_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `mch_puntaje` | INTEGER | puntos | Entre 0 y 20. | — |
|
||||
|
||||
---
|
||||
|
||||
## 4. Tabla `evaluacion_psicologica`
|
||||
## 4. Tabla `ados2`
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `psi_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `psi_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_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. | — |
|
||||
| `psi_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`. Ver validación cruzada. | — |
|
||||
| `psi_instrumento_tamizaje` | TEXT | — | Catálogo `InstrumentoTamizaje`: `M_CHAT_R, M_CHAT_RF, OTRO, NO_REGISTRADO`. | — |
|
||||
| `psi_tamizaje_puntaje` | INTEGER | — | Entre 0 y 20. | — |
|
||||
| `psi_tamizaje_riesgo` | TEXT | — | Catálogo `NivelRiesgoTamizaje`: `BAJO, MEDIO, ALTO, NO_APLICA`. | — |
|
||||
| `psi_ados2_modulo` | TEXT | — | Catálogo `ModuloAdos2`: `TODDLER, MODULO_1, MODULO_2, NO_REGISTRADO`. Define qué ítems del ADOS-2 aplican (Anexo B). | — |
|
||||
| `psi_ados2_sa` | INTEGER | — | Entre 0 y 30. Ver validación cruzada. | — |
|
||||
| `psi_ados2_rrb` | INTEGER | — | Entre 0 y 20. Ver validación cruzada. | — |
|
||||
| `psi_ados2_total` | INTEGER | — | Entre 0 y 50. Debe ser igual a `psi_ados2_sa + psi_ados2_rrb`. | — |
|
||||
| `psi_ados2_css` | INTEGER | — | Entre 1 y 10. | — |
|
||||
| `psi_ados2_css_sa` | INTEGER | — | Entre 1 y 10. | — |
|
||||
| `psi_ados2_css_rrb` | INTEGER | — | Entre 1 y 10. | — |
|
||||
| `psi_ados2_clasificacion` | TEXT | — | Catálogo `ClasificacionAdos2`: `NO_TEA, ESPECTRO_AUTISTA, AUTISMO, PREOCUPACION_LEVE_MODERADA, PREOCUPACION_SEVERA`. | — |
|
||||
| `psi_rgd` | BOOL | — | Ver validación cruzada (retraso global del desarrollo). | — |
|
||||
| `psi_cociente_desarrollo` | FLOAT | — | Entre 20.0 y 160.0. | — |
|
||||
| `psi_css_umbral_aplicado` | INTEGER | — | Entre 1 y 10. Ver validación cruzada. | — |
|
||||
| `psi_caso_confirmado` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `psi_cars_total` | FLOAT | — | Entre 15.0 y 60.0. Solo válido a partir de los 24 meses (ver validación cruzada). | — |
|
||||
| `psi_otros_instrumentos` | TEXT | — | — | — |
|
||||
| `psi_regresion_desarrollo` | BOOL | — | — | — |
|
||||
| `psi_diagnostico_texto` | TEXT | — | — | — |
|
||||
| `psi_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `psi_nlp_version` | TEXT | — | — | — |
|
||||
| `psi_created_at` | DATETIME | — | — | — |
|
||||
| `psi_updated_at` | DATETIME | — | — | — |
|
||||
| `ado_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `ado_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `ado_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `ado_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `ado_modulo` | TEXT | — | Catálogo `ModuloAdos2`: `TODDLER, MODULO_1, MODULO_2, MODULO_3`. | — |
|
||||
| `ado_algoritmo` | TEXT | — | El algoritmo del módulo, que depende del nivel de lenguaje (reactivo A1). | — |
|
||||
| `ado_css` | INTEGER | puntos | Entre 1 y 10. | — |
|
||||
| `ado_clasificacion` | TEXT | — | Catálogo `ClasificacionAdos2`: `NO_ESPECTRO, ESPECTRO_AUTISTA, AUTISMO, PREOCUPACION_LEVE_MODERADA, PREOCUPACION_SEVERA`. | — |
|
||||
| `ado_sa_a2` … `ado_sa_b18` (21) | INTEGER | puntos | Entre 0 y 3. Reactivos de afecto social. | — |
|
||||
| `ado_rrb_a3` … `ado_rrb_d5` (7) | INTEGER | puntos | Entre 0 y 3. Reactivos de comportamiento restringido y repetitivo. | — |
|
||||
|
||||
**Columnas de ítem del ADOS-2** (mismo tipo y patrón de validación que los puntajes enteros de arriba):
|
||||
|
||||
| Variable | Tipo | Unidad | Validación |
|
||||
|---|---|---|---|
|
||||
| `psi_ados2_sa_a2`, `psi_ados2_sa_a6`, `psi_ados2_sa_a7`, `psi_ados2_sa_a8`, `psi_ados2_sa_b1` … `psi_ados2_sa_b16b`, `psi_ados2_sa_b18` | INTEGER | — | Rango permitido según el módulo (Anexo B); fuera de rango se rechaza. |
|
||||
| `psi_ados2_rrb_a3`, `psi_ados2_rrb_a4`, `psi_ados2_rrb_a5`, `psi_ados2_rrb_d1`, `psi_ados2_rrb_d2`, `psi_ados2_rrb_d4`, `psi_ados2_rrb_d5` | INTEGER | — | Rango permitido según el módulo (Anexo B); fuera de rango se rechaza. |
|
||||
|
||||
El detalle exacto de rango por código y por módulo, la validación de completitud y
|
||||
la validación de pertenencia a módulo están en el **Anexo B**.
|
||||
|
||||
**Validaciones cruzadas de `evaluacion_psicologica`:**
|
||||
- `psi_ados2_total` debe ser igual a `psi_ados2_sa + psi_ados2_rrb`.
|
||||
- `psi_css_umbral_aplicado` debe ser 6 si `psi_rgd` es verdadero, y 5 si es falso.
|
||||
- `psi_caso_confirmado` debe ser igual a `psi_ados2_css >= psi_css_umbral_aplicado`.
|
||||
- `psi_cars_total` solo es válido si la ventana madurativa no es `V1_16_23` (la escala CARS aplica desde los 24 meses).
|
||||
- `psi_ventana_madurativa` debe corresponder a `psi_edad_meses` (Anexo A).
|
||||
- `psi_rgd` debe ser verdadero cuando `psi_cociente_desarrollo` es menor o igual a 75.0, y falso en caso contrario.
|
||||
|
||||
Las validaciones cruzadas propias del Anexo B (completitud y pertenencia a módulo) se
|
||||
suman a esta lista.
|
||||
Los subtotales por dominio y el total no se guardan: son sumas de los puntajes de algoritmo de los reactivos.
|
||||
|
||||
---
|
||||
|
||||
## 5. Tabla `potenciales_evocados_auditivos`
|
||||
## 5. Tabla `evaluacion_neuropediatrica`
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `pea_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `pea_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_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). | — |
|
||||
| `pea_umbral_oi` | INTEGER | dB | Entre 0 y 120 (oído izquierdo). | — |
|
||||
| `pea_latencia_v_od` | FLOAT | ms | Entre 3.5 y 12.0. | — |
|
||||
| `pea_latencia_v_oi` | FLOAT | ms | Entre 3.5 y 12.0. | — |
|
||||
| `pea_interpico_i_v_od` | FLOAT | ms | Entre 2.0 y 8.0. | — |
|
||||
| `pea_interpico_i_v_oi` | FLOAT | ms | Entre 2.0 y 8.0. | — |
|
||||
| `pea_grado_hipoacusia` | TEXT | — | Catálogo `GradoHipoacusia`: `NORMAL, LEVE, MODERADA, SEVERA, PROFUNDA, NO_CONCLUYENTE`. | — |
|
||||
| `pea_conclusion_texto` | TEXT | — | — | — |
|
||||
| `pea_flag_diferencial_auditivo` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pea_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `pea_created_at` | DATETIME | — | — | — |
|
||||
| `pea_updated_at` | DATETIME | — | — | — |
|
||||
|
||||
**Validación cruzada de `potenciales_evocados_auditivos`:**
|
||||
- Si `pea_grado_hipoacusia` es `MODERADA`, `SEVERA` o `PROFUNDA`, entonces `pea_flag_diferencial_auditivo` debe ser verdadero.
|
||||
| `neu_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `neu_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `neu_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `neu_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `neu_cie_codigo` | TEXT | — | Formato CIE-10: una letra, dos dígitos y opcionalmente un punto con uno o dos dígitos (`F84.0`). | — |
|
||||
|
||||
---
|
||||
|
||||
## 6. Tabla `eeg_estudio`
|
||||
## 6. Tabla `eeg`
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `eeg_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `eeg_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_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_archivo` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `eeg_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
| `eeg_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `eeg_id_registro_laboratorio` | VARCHAR(64), indexado | — | Llave natural: el reporte y el EDF del mismo estudio caen en la misma fila. | — |
|
||||
| `eeg_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `eeg_fecha_reporte` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
|
||||
| `eeg_dias_respuesta` | INTEGER | días | Entre 0 y 60. Ver validación cruzada. | — |
|
||||
| `eeg_medico_interpreta` | TEXT | — | — | — |
|
||||
| `eeg_estado_registro` | TEXT | — | Catálogo `EstadoRegistroEeg`: `VIGILIA, SUENO_ESPONTANEO, SUENO_INDUCIDO, MIXTO, NO_ESPECIFICADO`. | — |
|
||||
| `eeg_privacion_sueno` | BOOL | — | — | — |
|
||||
| `eeg_sedacion` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_sedacion_farmaco` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `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. | — |
|
||||
| `eeg_ritmo_base_amplitud` | INTEGER | µV | Entre 5 y 300. | — |
|
||||
| `eeg_simetria` | TEXT | — | Catálogo `Simetria`: `SIMETRICO, ASIMETRICO_IZQUIERDO, ASIMETRICO_DERECHO, NO_ESPECIFICADA`. | — |
|
||||
| `eeg_anormalidad_presente` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_actividad_epileptiforme` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_tipo_grafoelemento` | TEXT | — | Catálogo `TipoGrafoelemento`: `NINGUNO, ESPIGA, ONDA_AGUDA, COMPLEJO_ESPIGA_ONDA, COMPLEJO_POLIESPIGA_ONDA, PUNTA_ONDA_LENTA, DESCARGA_RITMICA, OTRO`. Ver validación cruzada. | — |
|
||||
| `eeg_distribucion_anormalidad` | TEXT | — | Catálogo `DistribucionAnormalidad`: `FOCAL, MULTIFOCAL, GENERALIZADA, LATERALIZADA, NO_ESPECIFICADA`. | — |
|
||||
| `eeg_localizacion` | TEXT | — | — | — |
|
||||
| `eeg_activacion_sueno` | BOOL | — | — | — |
|
||||
| `eeg_lentificacion` | TEXT | — | Catálogo `Lentificacion`: `NINGUNA, FOCAL, GENERALIZADA, INTERMITENTE`. | — |
|
||||
| `eeg_crisis_registradas` | BOOL | — | — | — |
|
||||
| `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` | 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 | — | — | — |
|
||||
| `eeg_con_sueno` | INTEGER | — | 0 o 1. **(análisis del EEG)** | — |
|
||||
| `eeg_canales` | INTEGER | canales | Entre 1 y 256. **(análisis del EEG)** | — |
|
||||
| `eeg_duracion_min` | FLOAT | minutos | Mayor que 0. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_amplitud` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_alta_frecuencia` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_correlacion` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_sin_senal` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_estudio` | BLOB (LONGBLOB en MySQL) | — | El archivo EDF. | — |
|
||||
|
||||
**Validaciones cruzadas de `eeg_estudio`:**
|
||||
- `eeg_fecha_reporte` no puede ser anterior a `eeg_fecha_estudio`.
|
||||
- `eeg_dias_respuesta` debe ser igual a la diferencia en días entre `eeg_fecha_reporte` y `eeg_fecha_estudio`.
|
||||
- Si `eeg_actividad_epileptiforme` es falso, `eeg_tipo_grafoelemento` debe quedar vacío o en `NINGUNO`.
|
||||
- Si `eeg_actividad_epileptiforme` es verdadero, `eeg_anormalidad_presente` debe ser verdadero.
|
||||
- Si `eeg_sedacion` es falso, `eeg_sedacion_farmaco` debe quedar vacío.
|
||||
- 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.
|
||||
Un EEG es malo cuando cualquiera de sus criterios de calidad está fuera de su umbral; uno malo no tiene resultado y
|
||||
sus alteraciones no cuentan.
|
||||
|
||||
---
|
||||
|
||||
## 7. Tabla `antecedentes_maternos_gestacion`
|
||||
## 7. Tabla `eeg_metrica` **(análisis del EEG)**
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `amg_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `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 | — | — | — |
|
||||
| `amg_imc_pregestacional` | FLOAT | kg/m² | Entre 12.0 y 70.0. Ver validación cruzada. | — |
|
||||
| `amg_categoria_peso_materno` | TEXT | — | Catálogo `CategoriaPesoMaterno`: `BAJO_PESO, NORMAL, SOBREPESO, OBESIDAD_I, OBESIDAD_II, OBESIDAD_III, NO_REGISTRADA`. Ver validación cruzada. | — |
|
||||
| `amg_tabaquismo_gestacion` | BOOL | — | — | — |
|
||||
| `amg_acido_folico_preconcepcional` | BOOL | — | — | — |
|
||||
| `amg_intervalo_intergenesico_meses` | INTEGER | meses | Entre 0 y 360. | — |
|
||||
| `amg_antecedente_aborto` | BOOL | — | — | — |
|
||||
| `amg_embarazo_multiple` | TEXT | — | Catálogo `TipoEmbarazo`: `UNICO, GEMELAR, TRIPLE_O_MAS, NO_REGISTRADO`. | — |
|
||||
| `amg_infeccion_gestacion` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `amg_infeccion_tipo` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `amg_infeccion_hospitalizacion` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `amg_diabetes_gestacional` | BOOL | — | — | — |
|
||||
| `amg_hipertension_preeclampsia` | TEXT | — | Catálogo `TrastornoHipertensivoGestacion`: `NINGUNO, HIPERTENSION_GESTACIONAL, PREECLAMPSIA, ECLAMPSIA, SINDROME_HELLP, NO_REGISTRADO`. | — |
|
||||
| `amg_hipotiroidismo` | BOOL | — | — | — |
|
||||
| `amg_hipertiroidismo` | BOOL | — | — | — |
|
||||
| `amg_incompatibilidad_rh` | BOOL | — | — | — |
|
||||
| `amg_crisis_convulsivas` | BOOL | — | — | — |
|
||||
| `amg_proceso_proinflamatorio` | BOOL | — | — | — |
|
||||
| `amg_enfermedad_autoinmune` | BOOL | — | — | — |
|
||||
| `amg_migrana` | BOOL | — | — | — |
|
||||
| `amg_asma` | BOOL | — | — | — |
|
||||
| `amg_hipoxia_materna` | BOOL | — | — | — |
|
||||
| `amg_estres_agudo` | BOOL | — | — | — |
|
||||
| `amg_trastorno_neurologico` | BOOL | — | — | — |
|
||||
| `amg_liquido_amniotico` | TEXT | — | Catálogo `VolumenLiquidoAmniotico`: `NORMAL, OLIGOHIDRAMNIOS, POLIHIDRAMNIOS, NO_REGISTRADO`. | — |
|
||||
| `amg_medicamentos_gestacion` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `amg_farmaco_riesgo_neurodesarrollo` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `amg_observaciones` | TEXT | — | — | — |
|
||||
| `amg_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `amg_nlp_version` | TEXT | — | — | — |
|
||||
| `amg_created_at` | DATETIME | — | — | — |
|
||||
| `amg_updated_at` | DATETIME | — | — | — |
|
||||
| `amg_fuente_sistema` | TEXT | — | — | — |
|
||||
| `met_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `met_eeg_id` | TEXT | — | — | → `eeg.eeg_id` |
|
||||
| `met_codigo` | TEXT | — | Catálogo `MetricaEeg`: `RITMO_POSTERIOR, HUSOS_SUENO_N2, HUSOS_SUENO_N3, PICOS_PAROXISTICOS, GRADIENTE_ANTEROPOSTERIOR`. | — |
|
||||
| `met_valor` | FLOAT | la de la métrica | Nulo: la métrica no se puede evaluar (por ejemplo, husos sin registro de sueño). | — |
|
||||
|
||||
**Validaciones cruzadas de `antecedentes_maternos_gestacion`:**
|
||||
- Si `amg_fuente_antecedente` es `EXPEDIENTE_MATERNO` o `AMBAS`, `amg_id_madre_seudonimo` debe estar presente.
|
||||
- `amg_categoria_peso_materno` debe corresponder al valor de `amg_imc_pregestacional` (Anexo A).
|
||||
- Si `amg_infeccion_gestacion` es falso, `amg_infeccion_tipo` debe quedar vacío y `amg_infeccion_hospitalizacion` debe ser falso o vacío.
|
||||
- Si `amg_farmaco_riesgo_neurodesarrollo` es verdadero, `amg_medicamentos_gestacion` no puede quedar vacío.
|
||||
Solo se guarda el valor medido: el puntaje z y el estado salen de los rangos de referencia por grupo de edad.
|
||||
|
||||
---
|
||||
|
||||
## 8. Tabla `parto_neonatal`
|
||||
## 8. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `pnn_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `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. | — |
|
||||
| `pnn_complicacion_tipo` | TEXT | — | Catálogo `ComplicacionIntraparto`: `NINGUNA, HIPOXIA, ISQUEMIA, TRAUMA_OBSTETRICO, CIRCULAR_DE_CORDON, SUFRIMIENTO_FETAL_AGUDO, OTRA`. Ver validación cruzada. | — |
|
||||
| `pnn_peso_nacer_g` | INTEGER | g | Entre 400 y 6000. | — |
|
||||
| `pnn_talla_nacer_cm` | FLOAT | cm | Entre 25.0 y 60.0. | — |
|
||||
| `pnn_perimetro_cefalico_nacer_cm` | FLOAT | cm | Entre 25.0 y 42.0. | — |
|
||||
| `pnn_edad_gestacional_sem` | FLOAT | semanas | Entre 22.0 y 43.0. | — |
|
||||
| `pnn_clasificacion_eg` | TEXT | — | Catálogo `ClasificacionEdadGestacional`: `PRETERMINO_EXTREMO, MUY_PRETERMINO, PRETERMINO_TARDIO, TERMINO, POSTERMINO, NO_DETERMINADA`. Ver validación cruzada. | — |
|
||||
| `pnn_tamano_para_eg` | TEXT | — | Catálogo `TamanoParaEdadGestacional`: `PEQUENO, ADECUADO, GRANDE, NO_DETERMINADO`. | — |
|
||||
| `pnn_peso_nacer_zscore` | FLOAT | — | Entre -5.0 y 5.0. | — |
|
||||
| `pnn_apgar_1min` | INTEGER | — | Entre 0 y 10. Ver validación cruzada. | — |
|
||||
| `pnn_apgar_5min` | INTEGER | — | Entre 0 y 10. Ver validación cruzada. | — |
|
||||
| `pnn_ingreso_ucin` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_dias_ucin` | INTEGER | días | Entre 0 y 365. Ver validación cruzada. | — |
|
||||
| `pnn_encefalopatia_hipoxico_isquemica` | BOOL | — | — | — |
|
||||
| `pnn_hipotermia_nacer` | BOOL | — | — | — |
|
||||
| `pnn_hiperbilirrubinemia` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_fototerapia` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_hipoglucemia_neonatal` | BOOL | — | — | — |
|
||||
| `pnn_anoxia` | BOOL | — | — | — |
|
||||
| `pnn_sindrome_congenito` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_sindrome_congenito_desc` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `pnn_flag_riesgo_neonatal` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_observaciones` | TEXT | — | — | — |
|
||||
| `pnn_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `pnn_nlp_version` | TEXT | — | — | — |
|
||||
| `pnn_created_at` | DATETIME | — | — | — |
|
||||
| `pnn_updated_at` | DATETIME | — | — | — |
|
||||
| `pnn_fuente_sistema` | TEXT | — | — | — |
|
||||
|
||||
**Validaciones cruzadas de `parto_neonatal`:**
|
||||
- `pnn_clasificacion_eg` debe corresponder a `pnn_edad_gestacional_sem` (Anexo A).
|
||||
- `pnn_apgar_5min` no puede ser menor que `pnn_apgar_1min`.
|
||||
- Si `pnn_dias_ucin` es mayor que 0, `pnn_ingreso_ucin` debe ser verdadero.
|
||||
- Si `pnn_fototerapia` es verdadero, `pnn_hiperbilirrubinemia` debe ser verdadero.
|
||||
- Si `pnn_complicaciones_intraparto` es falso, `pnn_complicacion_tipo` debe quedar vacío o en `NINGUNA`.
|
||||
- Si `pnn_sindrome_congenito` es falso, `pnn_sindrome_congenito_desc` debe quedar vacío.
|
||||
- `pnn_flag_riesgo_neonatal` debe ser verdadero si se cumple al menos una de estas cuatro condiciones: `pnn_apgar_5min < 7`, `pnn_ingreso_ucin` verdadero, `pnn_encefalopatia_hipoxico_isquemica` verdadero, o `pnn_anoxia` verdadero. Si no se cumple ninguna, debe ser falso.
|
||||
|
||||
---
|
||||
|
||||
## 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`):
|
||||
|
||||
| Edad en meses | Ventana |
|
||||
|---|---|
|
||||
| 16.0 a 23.9 | `V1_16_23` |
|
||||
| 24.0 a 30.9 | `V2_24_30` |
|
||||
| 31.0 a 36.0 | `V3_31_36` |
|
||||
| Cualquier otro valor | `FUERA_DE_RANGO` |
|
||||
|
||||
**Categoría de peso materno según IMC pregestacional** (usada en `antecedentes_maternos_gestacion`, clasificación estándar de adultos de la OMS):
|
||||
|
||||
| IMC (kg/m²) | Categoría |
|
||||
|---|---|
|
||||
| Menor a 18.5 | `BAJO_PESO` |
|
||||
| 18.5 a 24.9 | `NORMAL` |
|
||||
| 25.0 a 29.9 | `SOBREPESO` |
|
||||
| 30.0 a 34.9 | `OBESIDAD_I` |
|
||||
| 35.0 a 39.9 | `OBESIDAD_II` |
|
||||
| 40.0 o más | `OBESIDAD_III` |
|
||||
|
||||
**Clasificación por edad gestacional al nacer** (usada en `parto_neonatal`):
|
||||
|
||||
| Semanas de gestación | Clasificación |
|
||||
|---|---|
|
||||
| Menos de 28.0 | `PRETERMINO_EXTREMO` |
|
||||
| 28.0 a 31.9 | `MUY_PRETERMINO` |
|
||||
| 32.0 a 36.9 | `PRETERMINO_TARDIO` |
|
||||
| 37.0 a 41.9 | `TERMINO` |
|
||||
| 42.0 o más | `POSTERMINO` |
|
||||
|
||||
---
|
||||
|
||||
## Anexo B — Validación de los códigos del ADOS-2 (`evaluacion_psicologica`)
|
||||
|
||||
El campo `psi_ados2_modulo` fija qué módulo del ADOS-2 se aplicó al paciente. Cada
|
||||
módulo usa un subconjunto distinto de códigos, dentro de los dos dominios que ya
|
||||
existen como columnas agregadas: `SA` (Interacción social recíproca / comunicación) y
|
||||
`RRB` (Conductas restringidas y repetitivas). Equivalencia entre el catálogo
|
||||
`ModuloAdos2` y los módulos del manual: `TODDLER` = Módulo T, `MODULO_1` = Módulo 1,
|
||||
`MODULO_2` = Módulo 2.
|
||||
|
||||
### B.1 Rango válido de cada código, por módulo
|
||||
|
||||
| Código | Dominio | Módulo T | Módulo 1 | Módulo 2 |
|
||||
|---|---|---|---|---|
|
||||
| a2 | SA | 0–3 | 0–3 | — |
|
||||
| a6 | SA | — | — | 0–3 |
|
||||
| a7 | SA | 0–3 | 0–3 | 0–3, 8 |
|
||||
| a8 | SA | 0–3, 8 | 0–2, 8 | — |
|
||||
| b1 | SA | 0–3 | 0, 2 | 0, 2 |
|
||||
| b2 | SA | — | — | 0–2 |
|
||||
| b3 | SA | — | 0–2 | 0–3 |
|
||||
| b4 | SA | 0–3 | 0–3 | — |
|
||||
| b5 | SA | 0–3 | 0–3 | 0–2 |
|
||||
| b6 | SA | 0–3 | — | 0–2 |
|
||||
| b7 | SA | 0–3 | — | — |
|
||||
| b8 | SA | 0–3 | — | 0–3 |
|
||||
| b9 | SA | 0–3 | 0–2 | — |
|
||||
| b10 | SA | — | 0–2 | — |
|
||||
| b11 | SA | — | 0–3 | 0–3 |
|
||||
| b12 | SA | 0–3 | 0–3 | 0–3 |
|
||||
| b13 | SA | 0–3 | — | — |
|
||||
| b14 | SA | 0–3 | — | — |
|
||||
| b15 | SA | 0–3 | — | — |
|
||||
| b16b | SA | 0–3, 7, 8 | — | — |
|
||||
| b18 | SA | 0–3 | — | — |
|
||||
| a3 | RRB | 0–3, 8 | 0–2, 8 | — |
|
||||
| a4 | RRB | — | — | 0–3 |
|
||||
| a5 | RRB | — | 0–3, 8 | — |
|
||||
| d1 | RRB | 0–3 | 0–3 | 0–3 |
|
||||
| d2 | RRB | 0–3 | 0–3 | 0–3 |
|
||||
| d4 | RRB | — | 0–3 | 0–3 |
|
||||
| d5 | RRB | 0–3 | — | — |
|
||||
|
||||
Nota de lectura: "0–3, 8" significa que, además de los valores enteros 0 a 3, el
|
||||
manual permite el código adicional 8 en ese ítem y módulo. Una celda con "—" quiere
|
||||
decir que ese código no existe para ese módulo (ver regla de pertenencia, B.3).
|
||||
|
||||
**Validación de rango por código:** si la columna correspondiente al código no está
|
||||
vacía, su valor debe ser un entero dentro del conjunto permitido para el módulo
|
||||
indicado en `psi_ados2_modulo`. Cualquier valor fuera del conjunto (incluido un
|
||||
entero "razonable" pero no listado, como un 4 donde el máximo es 3) se rechaza.
|
||||
|
||||
### B.2 Validación de completitud del módulo
|
||||
|
||||
Todos los códigos que pertenecen al módulo indicado en `psi_ados2_modulo` (columna
|
||||
correspondiente en la tabla de B.1) deben tener un valor, es decir, no pueden quedar
|
||||
vacíos. Si al menos uno de los códigos propios del módulo está vacío, el renglón se
|
||||
considera incompleto y se rechaza.
|
||||
|
||||
Ejemplo: si `psi_ados2_modulo = MODULO_1`, deben estar llenas las columnas
|
||||
`psi_ados2_sa_a2, sa_a7, sa_a8, sa_b1, sa_b3, sa_b4, sa_b5, sa_b9, sa_b10, sa_b11,
|
||||
sa_b12, rrb_a3, rrb_a5, rrb_d1, rrb_d2, rrb_d4`.
|
||||
|
||||
### B.3 Validación de pertenencia a módulo
|
||||
|
||||
Los códigos que **no** pertenecen al módulo indicado (celda "—" en B.1 para ese
|
||||
módulo) deben quedar vacíos. Si alguno de esos códigos trae un valor, el renglón se
|
||||
rechaza, porque ese código no corresponde a la versión de la prueba aplicada.
|
||||
|
||||
Ejemplo: si `psi_ados2_modulo = TODDLER`, las columnas `psi_ados2_sa_b2,
|
||||
sa_b3, sa_b10, sa_b11, rrb_a4, rrb_a5, rrb_d4` (propias de otros módulos) deben
|
||||
quedar vacías.
|
||||
|
||||
---
|
||||
|
||||
## Anexo C — Llaves foráneas (resumen)
|
||||
|
||||
| Columna | Tabla y columna referenciada |
|
||||
|---|---|
|
||||
| `ordenes_estudio.ord_pac_id` | `pacientes.pac_id` |
|
||||
| `ordenes_estudio.ord_nota_medica_id` | `nota_medica.nm_id` |
|
||||
| `nota_medica.nm_pac_id` | `pacientes.pac_id` |
|
||||
| `nota_medica.nm_nota_previa_id` | `nota_medica.nm_id` (autorreferencia) |
|
||||
| `evaluacion_psicologica.psi_ord_id` | `ordenes_estudio.ord_id` |
|
||||
| `evaluacion_psicologica.psi_pac_id` | `pacientes.pac_id` |
|
||||
| `potenciales_evocados_auditivos.pea_ord_id` | `ordenes_estudio.ord_id` |
|
||||
| `potenciales_evocados_auditivos.pea_pac_id` | `pacientes.pac_id` |
|
||||
| `eeg_estudio.eeg_ord_id` | `ordenes_estudio.ord_id` |
|
||||
| `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` |
|
||||
| `mel_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `mel_met_id` | TEXT | — | — | → `eeg_metrica.met_id` |
|
||||
| `mel_electrodo` | TEXT | — | Un electrodo del sistema 10-20 (`Fp1` … `O2`). | — |
|
||||
| `mel_valor` | FLOAT | puntaje z | — | — |
|
||||
|
||||
@@ -23,6 +23,8 @@ INDICADORES_KIT_CDM = {
|
||||
"cat_estudio",
|
||||
"cat_resultado",
|
||||
"cat_valor",
|
||||
"cat_sistema_fuente",
|
||||
"cat_mapeo",
|
||||
"procedimiento",
|
||||
"observacion_clinica",
|
||||
"cat_measure",
|
||||
@@ -75,14 +77,12 @@ def test_tea_tables_registered():
|
||||
# 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",
|
||||
"mchat",
|
||||
"ados2",
|
||||
"evaluacion_neuropediatrica",
|
||||
"eeg",
|
||||
"eeg_metrica",
|
||||
"eeg_metrica_electrodo",
|
||||
# indicadores_kit CDM, built from staging by the webapi.orquestacion graph.
|
||||
*INDICADORES_KIT_CDM,
|
||||
}
|
||||
@@ -103,3 +103,15 @@ def test_domains_do_not_share_metadata():
|
||||
assert CaCuModel.metadata is not GovernanceModel.metadata
|
||||
assert CaMaModel.metadata is not GovernanceModel.metadata
|
||||
assert TeaModel.metadata is not GovernanceModel.metadata
|
||||
|
||||
|
||||
def test_cat_mapeo_keeps_its_rules_in_the_schema():
|
||||
"""Pins down: a mapping row needs a known class with the target that class needs, a value of the catalog, and
|
||||
one row per form and start date; `cat_sistema_fuente` keeps its dates in order. Fails if a constraint is
|
||||
dropped from `reglas_de_mapeo` or `vigencia_ordenada`, which every engine relies on."""
|
||||
from core.cama.indicadores.models import CatMapeo, CatSistemaFuente
|
||||
|
||||
names = {c.name for c in CatMapeo.__table__.constraints}
|
||||
assert {"ck_cat_mapeo_clase", "ck_cat_mapeo_destino", "ck_cat_mapeo_vigencia", "fk_cat_mapeo_valor",
|
||||
"uq_cat_mapeo"} <= names
|
||||
assert "ck_cat_sistema_fuente_vigencia" in {c.name for c in CatSistemaFuente.__table__.constraints}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# Extraction
|
||||
|
||||
Reads clinical documents (PDF with or without a text layer, images, plain text) and EEG files, and turns the
|
||||
documents into records of the fields an import target has (VAR-01..03, VARM-01..04a). It has no dependency on the
|
||||
rest of the platform: WebApi gives it the fields to look for and stores what it finds.
|
||||
|
||||
## From pages to values
|
||||
|
||||
| Step | Module | What it does |
|
||||
|---|---|---|
|
||||
| Reading | `readers/` | Text layer with word positions (`pdfplumber`), Tesseract OCR on pages without one, embedded images located. |
|
||||
| Records | `segmentation.py`, `records.py` | Pages split into records (by patient key, by page count, whole document) and records of the same key merged; the most confident value wins and confident disagreements are kept as conflicts. |
|
||||
| Letterhead | `template.py` | Margin lines that repeat across different patients' documents are the issuer's, and fill nothing. |
|
||||
| Candidates | `nlp/extractors.py` | Every reading of every field, each with how it was found (`ExtractedValue.features`): `LabeledValueExtractor` (caption and value, in columns too), `PatternExtractor` (values with a known shape), `FreeTextMentionExtractor` (catalog terms in prose), `MeasurementExtractor` (a number with its unit after its concept). |
|
||||
| Context | `nlp/context.py` | Whether the report affirms, denies, supposes, quotes from history or from the clinical request each mention (ConText and NegEx), and which section it sits in. |
|
||||
| Choice | `nlp/ranking.py` | One value per field: the most confident (`HeuristicRanker`) or a ranker learned from corrections (`LearnedRanker`). |
|
||||
| Measurement | `nlp/evaluation.py` | Precision, recall and F1 per field against an answer key. |
|
||||
|
||||
Everything a field is looked for with lives in `nlp/vocabulary.py`: captions (`LABELS`), catalog terms as reports
|
||||
write them (`CLINICAL_TERMS`), the concepts a generic answer must follow (`ANCHORS`), severity orders (`SEVERITY`),
|
||||
what a denied mention means for a presence field (`NEGATED_VALUES`), units (`UNITS`), what each kind of report is
|
||||
about (`SUBJECTS`), section headings and trigger phrases. A report format with a caption or a term the extractor
|
||||
doesn't know is fixed there, without code changes.
|
||||
|
||||
## What the rules do
|
||||
|
||||
- **Assertions.** A mention preceded, within its clause, by a negation ("sin", "negativo para"), a hypothetical
|
||||
("en caso de", "un resultado"), a historical ("antecedente de") or an uncertainty trigger ("probable") is qualified
|
||||
accordingly. A form answer after it (`Carcinoma invasor: NO`) denies it, and a caption whose answer is elsewhere
|
||||
asserts nothing. Negated mentions fill nothing, except a presence field's `negated_value` ("sin actividad
|
||||
epileptiforme" is 0). Hypothetical ones fill nothing without a trained ranker.
|
||||
- **Sections.** A heading alone on its line opens a section until the next one: clinical data (what was suspected,
|
||||
presumed), history, description, result, and reference text (interpretation guides, reference intervals,
|
||||
methods), whose mentions describe no patient. A caption with its content on the same line qualifies only that line.
|
||||
- **Generic answers.** "POSITIVO", "NO", "NORMAL" in prose only count after their concept (`ANCHORS` or the field's
|
||||
captions), so a form's other positives don't fill the HPV result.
|
||||
- **Severity.** When a report affirms several values of an ordered field (one per specimen, one per breast), the most
|
||||
severe is the finding.
|
||||
- **Subject.** A record whose pages name another kind of study (`SUBJECTS` of the other targets) and not the
|
||||
target's fills nothing, and is flagged in the review. A record that names no study at all is not judged.
|
||||
- **OCR look-alikes.** On OCR pages, captions and terms also match with commonly confused characters collapsed
|
||||
(`ocr_fold`: `l`/`I`/`!`, `0`/`O` inside words...), at a slightly lower confidence.
|
||||
|
||||
## The learned ranker
|
||||
|
||||
`LearnedRanker` is a logistic regression over the candidates' features: method, assertion, section, label score,
|
||||
how many candidates agree, whether the document is on topic, crossed with the field and the method. It never sees
|
||||
the document's words, so its weights can be read and shared. It learns online with AdaGrad and L2, one batch at a
|
||||
time.
|
||||
|
||||
- It starts from the rules. Its score is blended with the heuristic's, and trusted fully after `TRUST_EXAMPLES`
|
||||
examples. Until then, what the rules rule out (hypothetical mentions, off-topic documents) stays out.
|
||||
- Each domain's ranker is versioned in the model registry as `<domain>-extraccion` (`models.io.extraction_ranker`),
|
||||
with its five routine records like any model. Extraction uses the version in production, otherwise the latest.
|
||||
- It learns in line: when an import whose documents a person corrected is written, the corrected records become
|
||||
examples (WebApi, `review_learning.py`) and a new DEV version is registered in the background.
|
||||
- It can also learn from an answer key: `python -m webapi.nlp train --documents <folder> --key <key.json>`, which
|
||||
first estimates, leaving each document out in turn, how it does on documents it hasn't seen.
|
||||
|
||||
## Measuring it (VAR-04, VARM-05)
|
||||
|
||||
`python -m webapi.nlp evaluate --documents <folder> --key <key.json>` prints precision, recall and F1 per field and
|
||||
overall, and which document and field each error is in (`--with-values` adds the values). The key gives, per
|
||||
document and target, the right value of each field checked, with `null` for a field that must stay empty. Measure
|
||||
on documents the vocabulary was not adjusted on: the score on the documents used to adjust it says how well it fits
|
||||
them, not how it generalizes.
|
||||
|
||||
## References
|
||||
|
||||
- Chapman WW et al. A simple algorithm for identifying negated findings and diseases in discharge summaries.
|
||||
J Biomed Inform 2001;34(5):301-310 (NegEx).
|
||||
- Harkema H et al. ConText: an algorithm for determining negation, experiencer, and temporal status from clinical
|
||||
reports. J Biomed Inform 2009;42(5):839-851.
|
||||
- Duchi J, Hazan E, Singer Y. Adaptive subgradient methods for online learning and stochastic optimization.
|
||||
J Mach Learn Res 2011;12:2121-2159 (AdaGrad).
|
||||
- Nayar R, Wilbur DC (eds.). The Bethesda System for Reporting Cervical Cytology, 3rd ed. Springer, 2015.
|
||||
- Darragh TM et al. The Lower Anogenital Squamous Terminology Standardization Project for HPV-associated lesions
|
||||
(LAST). Arch Pathol Lab Med 2012;136(10):1266-1297.
|
||||
- American College of Radiology. ACR BI-RADS Atlas, 5th ed., 2013.
|
||||
- Hirsch LJ et al. American Clinical Neurophysiology Society's Standardized Critical Care EEG Terminology: 2021
|
||||
version. J Clin Neurophysiol 2021;38(1):1-29.
|
||||
- Smith R. An overview of the Tesseract OCR engine. ICDAR 2007.
|
||||
@@ -26,11 +26,43 @@ class BBox:
|
||||
return [round(self.x0, 4), round(self.y0, 4), round(self.x1, 4), round(self.y1, 4)]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Word:
|
||||
"""One word of a line with its horizontal extent on the page (0..1)."""
|
||||
|
||||
text: str
|
||||
x0: float
|
||||
x1: float
|
||||
|
||||
@property
|
||||
def center(self) -> float:
|
||||
return (self.x0 + self.x1) / 2
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Line:
|
||||
"""`words`, when the reader knows them, are the line's words in order;
|
||||
`text` is then exactly their texts joined by single spaces, so a
|
||||
character offset in `text` maps to a position on the page."""
|
||||
|
||||
text: str
|
||||
bbox: BBox
|
||||
confidence: float = 1.0
|
||||
words: tuple[Word, ...] = ()
|
||||
|
||||
def x_at(self, offset: int) -> float | None:
|
||||
"""Left edge of the word holding character `offset` of `text`."""
|
||||
position = 0
|
||||
for word in self.words:
|
||||
end = position + len(word.text)
|
||||
if offset < end + 1:
|
||||
return word.x0
|
||||
position = end + 1
|
||||
return None
|
||||
|
||||
def text_between(self, x0: float, x1: float) -> str:
|
||||
"""The words whose center falls in `[x0, x1)`: one column's share of a line."""
|
||||
return " ".join(word.text for word in self.words if x0 <= word.center < x1)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from extraction.nlp.discovery import DiscoveredField, discover_captions
|
||||
from extraction.nlp.extractors import (
|
||||
DEFAULT_EXTRACTORS,
|
||||
FieldExtractor,
|
||||
@@ -11,6 +12,7 @@ from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_EXTRACTORS",
|
||||
"DiscoveredField",
|
||||
"Evidence",
|
||||
"ExtractedValue",
|
||||
"FieldExtractor",
|
||||
@@ -21,4 +23,5 @@ __all__ = [
|
||||
"PatternExtractor",
|
||||
"RecordExtractor",
|
||||
"SegmentLine",
|
||||
"discover_captions",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""What a report says about a mention: whether it affirms it, denies it, only
|
||||
supposes it, or quotes it from somewhere else; and which section of the report
|
||||
it sits in.
|
||||
|
||||
The approach is ConText (Harkema et al., 2009, J Biomed Inform 42:839), the
|
||||
extension of NegEx (Chapman et al., 2001, J Biomed Inform 34:301) to
|
||||
hypothetical, historical and uncertain mentions: trigger phrases before a
|
||||
mention, within its clause, qualify it, and a clause ends at a terminator.
|
||||
Two additions fit how forms and lab reports are laid out:
|
||||
|
||||
- form-style answers after the mention (`Carcinoma invasor: NO`);
|
||||
- sections. A heading such as "Datos clínicos" or "Valores de referencia"
|
||||
qualifies everything under it until the next heading: what the requesting
|
||||
physician suspected is not the study's result, and an interpretation guide
|
||||
printed on every report describes no patient.
|
||||
|
||||
Triggers and headings live in `extraction.nlp.vocabulary`.
|
||||
"""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from functools import lru_cache
|
||||
from typing import Sequence
|
||||
|
||||
from extraction.nlp.text import fold
|
||||
|
||||
|
||||
class Assertion(str, Enum):
|
||||
AFIRMADO = "afirmado"
|
||||
NEGADO = "negado"
|
||||
INCIERTO = "incierto"
|
||||
HIPOTETICO = "hipotetico"
|
||||
HISTORICO = "historico"
|
||||
PRESUNTIVO = "presuntivo"
|
||||
|
||||
|
||||
class Section(str, Enum):
|
||||
GENERAL = "general"
|
||||
CLINICA = "clinica"
|
||||
DESCRIPCION = "descripcion"
|
||||
RESULTADO = "resultado"
|
||||
ANTECEDENTES = "antecedentes"
|
||||
REFERENCIA = "referencia"
|
||||
|
||||
|
||||
# Sections whose content is about the patient's study as such.
|
||||
REPORTING_SECTIONS = frozenset({Section.GENERAL, Section.DESCRIPCION, Section.RESULTADO})
|
||||
|
||||
# How far back, in characters, a trigger reaches within a clause.
|
||||
TRIGGER_WINDOW = 60
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Context:
|
||||
assertion: Assertion
|
||||
section: Section
|
||||
trigger: str | None = None
|
||||
|
||||
|
||||
def _alternatives(terms) -> str:
|
||||
folded = sorted({" ".join(re.findall(r"[A-Z0-9]+", fold(t))) for t in terms if t.strip()}, key=len, reverse=True)
|
||||
return "|".join(r"[\s.\-]+".join(re.escape(w) for w in term.split()) for term in folded)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _compiled():
|
||||
from extraction.nlp.vocabulary import (
|
||||
CLAUSE_TERMINATORS,
|
||||
POST_AFFIRMATIONS,
|
||||
POST_NEGATIONS,
|
||||
PRE_TRIGGERS,
|
||||
PSEUDO_TRIGGERS,
|
||||
SECTION_HEADINGS,
|
||||
)
|
||||
|
||||
pre = {
|
||||
assertion: re.compile(rf"(?<![A-Z0-9])({_alternatives(terms)})(?![A-Z0-9])")
|
||||
for assertion, terms in PRE_TRIGGERS.items()
|
||||
}
|
||||
pseudo = re.compile(rf"(?<![A-Z0-9])({_alternatives(PSEUDO_TRIGGERS)})(?![A-Z0-9])")
|
||||
terminator = re.compile(rf"[.;:]|(?<![A-Z0-9])({_alternatives(CLAUSE_TERMINATORS)})(?![A-Z0-9])")
|
||||
post_negation = re.compile(rf"^[\s.:=\-]*({_alternatives(POST_NEGATIONS)})(?![A-Z0-9])")
|
||||
post_affirmation = re.compile(rf"^[\s.:=\-]*({_alternatives(POST_AFFIRMATIONS)})(?![A-Z0-9])")
|
||||
headings = [
|
||||
(section, re.compile(rf"^\s*(?:(?:\d{{1,3}}|[A-Z])\s*[.)][.\-]*\s*)?({_alternatives(terms)})(?![A-Z0-9])(?P<rest>.*)$"))
|
||||
for section, terms in SECTION_HEADINGS.items()
|
||||
]
|
||||
return pre, pseudo, terminator, post_negation, post_affirmation, headings
|
||||
|
||||
|
||||
def _heading(folded_line: str) -> tuple[Section, bool] | None:
|
||||
"""The section a line's leading heading names, and whether the heading
|
||||
stands alone (nothing but punctuation after it)."""
|
||||
*_, headings = _compiled()
|
||||
best: tuple[int, Section, bool] | None = None
|
||||
for section, pattern in headings:
|
||||
match = pattern.match(folded_line)
|
||||
if not match:
|
||||
continue
|
||||
rest = match.group("rest")
|
||||
if rest.strip() and not re.match(r"^\s*[:.\-]", rest):
|
||||
continue
|
||||
length = len(match.group(1))
|
||||
if best is None or length > best[0]:
|
||||
best = (length, section, not re.sub(r"[\s:.\-]", "", rest))
|
||||
return (best[1], best[2]) if best else None
|
||||
|
||||
|
||||
def heading_section(folded_line: str) -> Section | None:
|
||||
"""The section a line's leading heading names: the heading alone, or
|
||||
a caption followed by its content (`Metodología: PCR`)."""
|
||||
found = _heading(folded_line)
|
||||
return found[0] if found else None
|
||||
|
||||
|
||||
def caption_section(folded_line: str, start: int) -> Section | None:
|
||||
"""The section a caption earlier on the same line names (`... Diagnóstico
|
||||
clínico: LIAG`), for a mention after it."""
|
||||
before = folded_line[:start]
|
||||
colon = before.rfind(":")
|
||||
if colon < 0:
|
||||
return None
|
||||
caption_start = max(before.rfind(".", 0, colon), before.rfind(";", 0, colon), -1) + 1
|
||||
return heading_section(before[caption_start : colon + 1])
|
||||
|
||||
|
||||
def sections(folded_lines: Sequence[str]) -> list[Section]:
|
||||
"""The section of each line: the last heading standing alone at or above
|
||||
it. A caption with its content on the same line (`Metodología: PCR`)
|
||||
qualifies only that line."""
|
||||
current = Section.GENERAL
|
||||
found = []
|
||||
for line in folded_lines:
|
||||
heading = _heading(line)
|
||||
if heading is None:
|
||||
found.append(current)
|
||||
elif heading[1]:
|
||||
current = heading[0]
|
||||
found.append(current)
|
||||
else:
|
||||
found.append(heading[0])
|
||||
return found
|
||||
|
||||
|
||||
def assess(folded_line: str, start: int, end: int, section: Section = Section.GENERAL) -> Context:
|
||||
"""The assertion of the mention at `folded_line[start:end]`."""
|
||||
pre, pseudo, terminator, post_negation, post_affirmation, _ = _compiled()
|
||||
named = caption_section(folded_line, start)
|
||||
if named is not None:
|
||||
section = named
|
||||
clause_start = max((m.end() for m in terminator.finditer(folded_line, max(0, start - TRIGGER_WINDOW), start)), default=max(0, start - TRIGGER_WINDOW))
|
||||
window = folded_line[clause_start:start]
|
||||
for blocked in pseudo.finditer(window):
|
||||
window = window[: blocked.start()] + " " * (blocked.end() - blocked.start()) + window[blocked.end() :]
|
||||
for assertion in (Assertion.NEGADO, Assertion.HIPOTETICO, Assertion.HISTORICO, Assertion.INCIERTO):
|
||||
pattern = pre.get(assertion)
|
||||
found = pattern.search(window) if pattern else None
|
||||
if found:
|
||||
return Context(assertion, section, found.group(1))
|
||||
after = folded_line[end : end + 30]
|
||||
if re.match(r"^\s*:", after) and not post_affirmation.match(after):
|
||||
# A caption asking about it (`Carcinoma invasor:`), answered elsewhere.
|
||||
negated = post_negation.match(after)
|
||||
return Context(Assertion.NEGADO if negated else Assertion.HIPOTETICO, section, negated.group(1) if negated else "rubro")
|
||||
negated = post_negation.match(after)
|
||||
if negated and not post_affirmation.match(after):
|
||||
return Context(Assertion.NEGADO, section, negated.group(1))
|
||||
if section is Section.REFERENCIA:
|
||||
return Context(Assertion.HIPOTETICO, section, "seccion")
|
||||
if section is Section.ANTECEDENTES:
|
||||
return Context(Assertion.HISTORICO, section, "seccion")
|
||||
if section is Section.CLINICA:
|
||||
return Context(Assertion.PRESUNTIVO, section, "seccion")
|
||||
return Context(Assertion.AFIRMADO, section)
|
||||
|
||||
|
||||
# How much a mention's assertion leaves of the confidence of a value read from it.
|
||||
ASSERTION_WEIGHT = {
|
||||
Assertion.AFIRMADO: 1.0,
|
||||
Assertion.INCIERTO: 0.75,
|
||||
Assertion.PRESUNTIVO: 0.35,
|
||||
Assertion.HISTORICO: 0.35,
|
||||
Assertion.HIPOTETICO: 0.15,
|
||||
Assertion.NEGADO: 0.0,
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Captions a document carries that no registered `FieldSpec` claims.
|
||||
|
||||
`LabeledValueExtractor` only looks for the labels a caller already knows
|
||||
about. A source whose documents carry fields outside today's vocabulary
|
||||
(another report layout, a free-form note) still has captions in the
|
||||
`"Campo: valor"` shape; this module finds them so a caller can use them as
|
||||
values of their own, or decide whether each matches something in a catalog
|
||||
closely enough to reuse, or is new (see
|
||||
`webapi.imports.schemas.catalog_matching`).
|
||||
|
||||
Captions are found wherever a form puts them: alone on their line, several
|
||||
on one line, after an item number, or heading a column whose value sits on
|
||||
the line below. Each one found becomes a temporary `FieldSpec`, so its value
|
||||
is read by the same extractor, with the same layout handling, as the known
|
||||
fields'.
|
||||
"""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
from extraction.nlp.extractors import LabelIndex, RecordExtractor, SegmentLine, cell_starts
|
||||
from extraction.nlp.fields import Evidence, FieldKind, FieldSpec
|
||||
|
||||
MAX_CAPTION_WORDS = 6
|
||||
_ITEM_NUMBER = re.compile(r"(?:^|(?<=\s))(?:\d{1,3}|[A-Za-z])\s*[.)][.\-]*(?=\s|$)")
|
||||
# Words a caption may carry between its first and last word.
|
||||
_CONNECTORS = frozenset({"de", "del", "la", "el", "los", "las", "en", "para", "por", "al", "y", "a", "que", "con", "se"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiscoveredField:
|
||||
"""One `caption: value` a known `FieldSpec` didn't already claim."""
|
||||
|
||||
caption: str
|
||||
value: str
|
||||
evidence: Evidence
|
||||
|
||||
|
||||
def discover_captions(lines: Sequence[SegmentLine], specs: Sequence[FieldSpec]) -> list[DiscoveredField]:
|
||||
"""Every caption no spec claims, with its value, in the order the
|
||||
captions first appear."""
|
||||
known = LabelIndex(lines, specs)
|
||||
captions: list[str] = []
|
||||
for line_index, line in enumerate(lines):
|
||||
for start, end, caption in find_captions(line):
|
||||
if any(hit.start < end and start < hit.end for hit in known.hits[line_index]):
|
||||
continue
|
||||
if caption.casefold() not in (seen.casefold() for seen in captions):
|
||||
captions.append(caption)
|
||||
if not captions:
|
||||
return []
|
||||
adhoc = [FieldSpec(f"caption:{caption}", FieldKind.TEXT, labels=(caption,)) for caption in captions]
|
||||
values = RecordExtractor([*specs, *adhoc]).extract(lines)
|
||||
found = []
|
||||
for caption, spec in zip(captions, adhoc):
|
||||
value = values.get(spec.name)
|
||||
if value is not None and str(value.value).strip():
|
||||
found.append(DiscoveredField(caption, str(value.value).strip(), value.evidence))
|
||||
return found
|
||||
|
||||
|
||||
def find_captions(line: SegmentLine) -> list[tuple[int, int, str]]:
|
||||
"""`(start, end, caption)` for every caption on the line, in order;
|
||||
offsets are into the line's text and `end` is past the colon."""
|
||||
text = line.text
|
||||
boundaries = sorted({0, *cell_starts(line), *(match.end() for match in _ITEM_NUMBER.finditer(text))})
|
||||
found: list[tuple[int, int, str]] = []
|
||||
previous_colon = -1
|
||||
for colon in (match.start() for match in re.finditer(r":(?=\s|$)", text)):
|
||||
start = max([b for b in boundaries if b <= colon] + [previous_colon + 1])
|
||||
words = text[start:colon].split()
|
||||
if not words:
|
||||
previous_colon = colon
|
||||
continue
|
||||
in_sentence = start == previous_colon + 1 and previous_colon >= 0 or len(words) > MAX_CAPTION_WORDS
|
||||
if in_sentence:
|
||||
words = _trailing_caption(words)
|
||||
if not words[0][:1].isupper():
|
||||
previous_colon = colon
|
||||
continue
|
||||
caption = " ".join(words).strip(" .-")
|
||||
if caption and any(ch.isalpha() for ch in caption) and len(caption) <= 60:
|
||||
found.append((text.rindex(words[0], start, colon), colon + 1, caption))
|
||||
previous_colon = colon
|
||||
return found
|
||||
|
||||
|
||||
def _trailing_caption(words: list[str]) -> list[str]:
|
||||
"""The caption at the end of a run of words that also holds the value
|
||||
before it: the last word, plus words joined to it by connectors or
|
||||
abbreviations (`Fecha de nacimiento`, `Fech. solicitud`) and the
|
||||
capitalized words of a title-case caption (`Motivo Principal`)."""
|
||||
caption = [words[-1]]
|
||||
position = len(words) - 2
|
||||
while position >= 0 and len(caption) < MAX_CAPTION_WORDS:
|
||||
word = words[position]
|
||||
if word.casefold() in _CONNECTORS and position > 0:
|
||||
caption[:0] = [words[position - 1], word]
|
||||
position -= 2
|
||||
elif word.endswith(".") and len(word) <= 6 and word[0].isalpha():
|
||||
caption.insert(0, word)
|
||||
position -= 1
|
||||
elif _title_case(word) and _title_case(caption[0]):
|
||||
caption.insert(0, word)
|
||||
position -= 1
|
||||
else:
|
||||
break
|
||||
return caption
|
||||
|
||||
|
||||
def _title_case(word: str) -> bool:
|
||||
return len(word) > 1 and word[0].isupper() and word[1:].islower()
|
||||
@@ -0,0 +1,112 @@
|
||||
"""How well extraction does against an answer key (VAR-04, VARM-05).
|
||||
|
||||
An answer key maps each document to the right value of each field it was
|
||||
checked for; `None` means the field must stay empty, and a field left out
|
||||
of a document's answers is not scored for it. Per field, a value equal to
|
||||
the key is a true positive, a value where the key has another or none is a
|
||||
false positive, and a key value not extracted (or extracted wrong) is a
|
||||
false negative: a wrong value counts as both, as is usual for slot filling.
|
||||
"""
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Mapping
|
||||
|
||||
from extraction.nlp.ranking import same_value
|
||||
|
||||
|
||||
@dataclass
|
||||
class FieldScore:
|
||||
true_positives: int = 0
|
||||
false_positives: int = 0
|
||||
false_negatives: int = 0
|
||||
true_negatives: int = 0
|
||||
|
||||
@property
|
||||
def precision(self) -> float | None:
|
||||
found = self.true_positives + self.false_positives
|
||||
return self.true_positives / found if found else None
|
||||
|
||||
@property
|
||||
def recall(self) -> float | None:
|
||||
expected = self.true_positives + self.false_negatives
|
||||
return self.true_positives / expected if expected else None
|
||||
|
||||
@property
|
||||
def f1(self) -> float | None:
|
||||
p, r = self.precision, self.recall
|
||||
if p is None or r is None or p + r == 0:
|
||||
return None
|
||||
return 2 * p * r / (p + r)
|
||||
|
||||
def add(self, extracted: Any, expected: Any) -> bool:
|
||||
"""Scores one value; returns whether it was right."""
|
||||
if expected is None:
|
||||
if extracted is None:
|
||||
self.true_negatives += 1
|
||||
return True
|
||||
self.false_positives += 1
|
||||
return False
|
||||
if extracted is not None and same_value(extracted, expected):
|
||||
self.true_positives += 1
|
||||
return True
|
||||
self.false_negatives += 1
|
||||
if extracted is not None:
|
||||
self.false_positives += 1
|
||||
return False
|
||||
|
||||
def merge(self, other: "FieldScore") -> None:
|
||||
self.true_positives += other.true_positives
|
||||
self.false_positives += other.false_positives
|
||||
self.false_negatives += other.false_negatives
|
||||
self.true_negatives += other.true_negatives
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"verdaderos_positivos": self.true_positives,
|
||||
"falsos_positivos": self.false_positives,
|
||||
"falsos_negativos": self.false_negatives,
|
||||
"verdaderos_negativos": self.true_negatives,
|
||||
"precision": _round(self.precision),
|
||||
"exhaustividad": _round(self.recall),
|
||||
"f1": _round(self.f1),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Evaluation:
|
||||
fields: dict[str, FieldScore] = field(default_factory=dict)
|
||||
# Per document and field, what was extracted where it differs from the key.
|
||||
errors: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def overall(self) -> FieldScore:
|
||||
total = FieldScore()
|
||||
for score in self.fields.values():
|
||||
total.merge(score)
|
||||
return total
|
||||
|
||||
def to_dict(self, *, with_values: bool = False) -> dict[str, Any]:
|
||||
"""`with_values` includes the wrong and expected values of each error;
|
||||
without it, only which document and field, so a report on real
|
||||
documents can be shared without what they say."""
|
||||
errors = self.errors if with_values else [{"documento": e["documento"], "campo": e["campo"]} for e in self.errors]
|
||||
return {
|
||||
"global": self.overall.to_dict(),
|
||||
"campos": {name: score.to_dict() for name, score in sorted(self.fields.items())},
|
||||
"errores": errors,
|
||||
}
|
||||
|
||||
|
||||
def evaluate(extracted: Mapping[str, Mapping[str, Any]], key: Mapping[str, Mapping[str, Any]]) -> Evaluation:
|
||||
"""`extracted` and `key`: per document, per field, a value."""
|
||||
result = Evaluation()
|
||||
for document, expected_fields in key.items():
|
||||
found = extracted.get(document, {})
|
||||
for name, expected in expected_fields.items():
|
||||
value = found.get(name)
|
||||
if not result.fields.setdefault(name, FieldScore()).add(value, expected):
|
||||
result.errors.append({"documento": document, "campo": name, "extraido": value, "esperado": expected})
|
||||
return result
|
||||
|
||||
|
||||
def _round(value: float | None) -> float | None:
|
||||
return None if value is None else round(value, 3)
|
||||
@@ -1,5 +1,7 @@
|
||||
"""Field extraction strategies. Each `FieldExtractor` proposes candidates
|
||||
for a field; `RecordExtractor` keeps the most confident one per field.
|
||||
for a field, each with the features of how it was found; `RecordExtractor`
|
||||
keeps them all and lets a `CandidateRanker` (`extraction.nlp.ranking`) pick
|
||||
one per field. Without a trained ranker, the most confident candidate wins.
|
||||
|
||||
To add a strategy (a dictionary lookup, a statistical NER model, an LLM
|
||||
call), subclass `FieldExtractor`, give it a `method` name and pass an
|
||||
@@ -15,6 +17,7 @@ from typing import Any, ClassVar, Iterable, Sequence
|
||||
from rapidfuzz import fuzz
|
||||
|
||||
from extraction.document import Line
|
||||
from extraction.nlp.context import ASSERTION_WEIGHT, Assertion, Context, Section, assess, heading_section, sections
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
|
||||
from extraction.nlp.text import (
|
||||
SEPARATOR,
|
||||
@@ -25,18 +28,32 @@ from extraction.nlp.text import (
|
||||
fold,
|
||||
is_negated,
|
||||
label_pattern,
|
||||
ocr_fold,
|
||||
)
|
||||
|
||||
FUZZY_LABEL_THRESHOLD = 0.86
|
||||
MAX_TEXT_LENGTH = 1000
|
||||
MAX_CONTINUATION_LINES = 8
|
||||
# A choice whose label stands alone may state its value a few lines down,
|
||||
# after a subheading.
|
||||
MAX_CHOICE_LOOKAHEAD = 3
|
||||
# Values in a column may start slightly left of the label heading it.
|
||||
COLUMN_MARGIN = 0.02
|
||||
|
||||
|
||||
# What an OCR look-alike match is worth next to an exact one.
|
||||
OCR_MATCH_SCORE = 0.92
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SegmentLine:
|
||||
"""`ocr`: the line was read by OCR, so look-alike characters may stand in
|
||||
for each other (`extraction.nlp.text.ocr_fold`)."""
|
||||
|
||||
document: str
|
||||
page_number: int
|
||||
line: Line
|
||||
ocr: bool = False
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
@@ -46,6 +63,10 @@ class SegmentLine:
|
||||
def folded(self) -> str:
|
||||
return fold(self.line.text)
|
||||
|
||||
@property
|
||||
def ocr_folded(self) -> str:
|
||||
return ocr_fold(self.line.text)
|
||||
|
||||
@property
|
||||
def ocr_confidence(self) -> float:
|
||||
return self.line.confidence if self.line.confidence > 0 else 0.5
|
||||
@@ -65,11 +86,42 @@ class LabelHit:
|
||||
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."""
|
||||
`Nombre: ANA Sexo: F C.P.: 64000` be split into three values.
|
||||
|
||||
Captions no field knows (`Cualquier otra cosa:`) are tracked too, as
|
||||
boundaries: they end the value before them and the text under the
|
||||
label before them, without being read themselves."""
|
||||
|
||||
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]
|
||||
self.folded = [line.folded for line in self.lines]
|
||||
self.hits: list[list[LabelHit]] = [_label_hits(line, tuple(specs)) for line in self.lines]
|
||||
self.boundaries: list[list[int]] = [
|
||||
_boundaries(folded, hits) for folded, hits in zip(self.folded, self.hits)
|
||||
]
|
||||
self.sections: list[Section] = sections([line.ocr_folded if line.ocr else line.folded for line in self.lines])
|
||||
|
||||
def context(self, line_index: int, start: int, end: int) -> Context:
|
||||
"""The assertion of the mention at `start:end` of a line."""
|
||||
line = self.lines[line_index]
|
||||
return assess(line.ocr_folded if line.ocr else line.folded, start, end, self.sections[line_index])
|
||||
|
||||
def label_context(self, line_index: int, hit: "LabelHit") -> Context:
|
||||
"""A label's value is the answer to it, so only where the label sits
|
||||
qualifies it: its section, or a caption that names one
|
||||
("Diagnóstico clínico:" is what was suspected, not found). A caption
|
||||
inside reference text (a report date in the footer under an
|
||||
interpretation guide) is still the document's own."""
|
||||
folded = self.folded[line_index]
|
||||
section = heading_section(folded[_caption_start(folded, hit.start) :]) or self.sections[line_index]
|
||||
assertion = {
|
||||
Section.CLINICA: Assertion.PRESUNTIVO,
|
||||
Section.ANTECEDENTES: Assertion.HISTORICO,
|
||||
}.get(section, Assertion.AFIRMADO)
|
||||
return Context(assertion, section)
|
||||
|
||||
def position(self, line_index: int) -> float:
|
||||
return line_index / max(1, len(self.lines) - 1)
|
||||
|
||||
def for_field(self, name: str) -> Iterable[tuple[int, LabelHit]]:
|
||||
for index, hits in enumerate(self.hits):
|
||||
@@ -78,13 +130,94 @@ class LabelIndex:
|
||||
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]
|
||||
starts = [start for start in self.boundaries[index] if start >= after]
|
||||
return min(starts) if starts else None
|
||||
|
||||
def column(self, index: int, hit: LabelHit) -> tuple[float, float] | None:
|
||||
"""Horizontal extent of the column a label heads, when its line
|
||||
carries other captions too: from the label's left edge to the next
|
||||
caption's. `None` for a label alone on its line or without word
|
||||
positions."""
|
||||
starts = self.boundaries[index]
|
||||
line = self.lines[index].line
|
||||
own = max((start for start in starts if start <= hit.start), default=None)
|
||||
if len(starts) < 2 or not line.words or own is None:
|
||||
return None
|
||||
position = starts.index(own)
|
||||
left = line.x_at(own) if position else 0.0
|
||||
right = line.x_at(starts[position + 1]) if position + 1 < len(starts) else 1.0
|
||||
if left is None or right is None or right <= left:
|
||||
return None
|
||||
return left - COLUMN_MARGIN if position else 0.0, right - COLUMN_MARGIN if position + 1 < len(starts) else 1.0
|
||||
|
||||
def label_in_column(self, index: int, column: tuple[float, float]) -> bool:
|
||||
line = self.lines[index].line
|
||||
return any(column[0] <= (line.x_at(start) or -1.0) < column[1] for start in self.boundaries[index])
|
||||
|
||||
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])
|
||||
return any(start <= offset + 2 for start in self.boundaries[index])
|
||||
|
||||
|
||||
# A caption no field knows: a few words and a colon, at the start of the
|
||||
# line or after an item number (`7.- `, `b) `).
|
||||
_ITEM_NUMBER = r"(?:\d{1,3}|[A-Z])\s*[.)][.\-]*\s*"
|
||||
_ANY_CAPTION = re.compile(rf"(?:^|(?<=\s))(?P<item>{_ITEM_NUMBER})?[A-Z][A-Z0-9./\-]*(?:\s+[A-Z0-9][A-Z0-9./\-]*){{0,5}}\s*:")
|
||||
_TRAILING_ITEM_NUMBER = re.compile(rf"(?:^|(?<=\s)){_ITEM_NUMBER}$")
|
||||
|
||||
|
||||
# An item number in the middle of a line (`... 3.- SIGUIENTE`) starts the next item.
|
||||
_INLINE_ITEM = re.compile(r"(?<=\s)(?:\d{1,3}\.-|\d{1,3}\)|[A-Z]\))(?=\s)")
|
||||
# A horizontal gap wider than this (fraction of the page) between two words
|
||||
# separates two cells of a form line.
|
||||
CELL_GAP = 0.02
|
||||
|
||||
|
||||
def cell_starts(line: SegmentLine) -> list[int]:
|
||||
"""Character offsets where a word starts after a wide horizontal gap;
|
||||
without word positions, after a run of spaces or a tab."""
|
||||
words = line.line.words
|
||||
if not words:
|
||||
return [match.end() for match in re.finditer(r"\s{2,}|\t", line.text)]
|
||||
starts, offset = [], 0
|
||||
for previous, word in zip((None, *words), words):
|
||||
if previous is not None and word.x0 - previous.x1 > CELL_GAP:
|
||||
starts.append(offset)
|
||||
offset += len(word.text) + 1
|
||||
return starts
|
||||
|
||||
|
||||
def _within_cell(line: SegmentLine, start: int, tail: str) -> str:
|
||||
"""A value ends where the next cell of the line begins, once it has
|
||||
started: the gap between a caption and its value doesn't cut it."""
|
||||
cuts = [cut for cut in cell_starts(line) if cut > start]
|
||||
if not cuts or cuts[0] >= start + len(tail):
|
||||
return tail
|
||||
return line.text[start : cuts[0]].rstrip()
|
||||
|
||||
|
||||
def _caption_start(folded: str, start: int) -> int:
|
||||
"""Where a caption begins, counting the item number printed before it."""
|
||||
item = _TRAILING_ITEM_NUMBER.search(folded[:start])
|
||||
return item.start() if item else start
|
||||
|
||||
|
||||
def _boundaries(folded: str, hits: list[LabelHit]) -> list[int]:
|
||||
starts = {hit: _caption_start(folded, hit.start) for hit in hits}
|
||||
extra: set[int] = {
|
||||
match.start() for match in _INLINE_ITEM.finditer(folded) if not any(hit.start <= match.start() < hit.end for hit in hits)
|
||||
}
|
||||
line_start = len(folded) - len(folded.lstrip())
|
||||
for match in _ANY_CAPTION.finditer(folded):
|
||||
if match.start() != line_start and not match.group("item"):
|
||||
continue
|
||||
inside = [hit for hit in hits if match.start() <= hit.start < match.end()]
|
||||
for hit in inside:
|
||||
starts[hit] = min(starts[hit], match.start())
|
||||
if not inside and not any(hit.start <= match.start() < hit.end for hit in hits):
|
||||
extra.add(match.start())
|
||||
return sorted(set(starts.values()) | extra)
|
||||
|
||||
|
||||
_AFTER_CAPTION = re.compile(r"\s*[:=#]|\s{2,}|\s*$")
|
||||
@@ -96,13 +229,57 @@ def _is_caption(folded: str, start: int, end: int) -> bool:
|
||||
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] = []
|
||||
# A caption may run on for a few words before its colon.
|
||||
_CAPTION_RUN_ON = re.compile(r"(?:\s+[A-Z]{1,15}\.?){1,4}\s*:")
|
||||
|
||||
|
||||
# Words a run-on caption may have before its label, counted from the start
|
||||
# of the line, an item number or the previous colon; more is a sentence.
|
||||
MAX_CAPTION_LEAD_WORDS = 2
|
||||
|
||||
|
||||
_CONNECTOR_BEFORE = re.compile(r"(?<![A-Z0-9])(DE|DEL|PARA|POR|EN|CON|SIN|A|AL)\s+$")
|
||||
|
||||
|
||||
def _names_something_else(folded: str, start: int) -> bool:
|
||||
"""A label right after a connector is the tail of a longer caption
|
||||
that names something else: `FECHA DE INTERPRETACION` is a date, not
|
||||
the interpretation."""
|
||||
return bool(_CONNECTOR_BEFORE.search(folded[max(0, start - 8) : start]))
|
||||
|
||||
|
||||
def _near_segment_start(folded: str, start: int) -> bool:
|
||||
segment = re.split(r":|(?:^|\s)(?:\d{1,3}|[A-Z])\s*[.)][.\-]*\s", folded[:start])[-1]
|
||||
return len(segment.split()) <= MAX_CAPTION_LEAD_WORDS
|
||||
|
||||
|
||||
def _label_hits(line: SegmentLine, specs: tuple[FieldSpec, ...]) -> list[LabelHit]:
|
||||
folded = line.folded
|
||||
canonical = line.ocr_folded if line.ocr else None
|
||||
found: 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))
|
||||
if not exact and canonical is not None:
|
||||
exact = [
|
||||
LabelHit(spec.name, m.start(), m.end(), OCR_MATCH_SCORE)
|
||||
for m in label_pattern(ocr_fold(label)).finditer(canonical)
|
||||
]
|
||||
found.extend(exact or _fuzzy_hits(canonical or folded, spec.name, ocr_fold(label) if canonical else label))
|
||||
hits: list[LabelHit] = []
|
||||
for hit in found:
|
||||
if _names_something_else(folded, hit.start):
|
||||
continue
|
||||
if _is_caption(folded, hit.start, hit.end):
|
||||
hits.append(hit)
|
||||
continue
|
||||
run_on = _CAPTION_RUN_ON.match(folded, hit.end)
|
||||
if (
|
||||
run_on
|
||||
and _near_segment_start(folded, hit.start)
|
||||
and not any(other is not hit and other.start < run_on.end() and other.end > hit.end for other in found)
|
||||
):
|
||||
hits.append(LabelHit(hit.field, hit.start, run_on.end(), hit.score))
|
||||
# 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] = []
|
||||
@@ -142,8 +319,9 @@ class Parsed:
|
||||
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."""
|
||||
def parse_value(spec: FieldSpec, text: str, *, ocr: bool = False) -> Parsed | None:
|
||||
"""Reads a value of `spec.kind` out of the text found next to a label;
|
||||
`ocr` also accepts choices written with OCR look-alikes."""
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return None
|
||||
@@ -152,6 +330,9 @@ def parse_value(spec: FieldSpec, text: str) -> Parsed | None:
|
||||
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)
|
||||
dated = find_date(text)
|
||||
if found and dated and dated[1][0] <= found[1][0] < dated[1][1]:
|
||||
return None
|
||||
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)
|
||||
@@ -161,23 +342,28 @@ def parse_value(spec: FieldSpec, text: str) -> Parsed | None:
|
||||
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))
|
||||
quality = 1.0
|
||||
if found is None and ocr:
|
||||
found = find_choice(spec, ocr_fold(text), canonical=True)
|
||||
quality = OCR_MATCH_SCORE
|
||||
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)
|
||||
return Parsed(value, text[start : start + len(surface)], quality * (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`."""
|
||||
def find_choice(spec: FieldSpec, folded: str, *, min_length: int = 1, canonical: bool = False) -> tuple[Any, str, int] | None:
|
||||
"""Leftmost, then longest, non-negated surface form of `spec` in `folded`
|
||||
(`canonical`: `folded` went through `ocr_fold`, and so do the surfaces)."""
|
||||
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):
|
||||
for match in _choice_pattern(ocr_fold(surface) if canonical else 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])):
|
||||
@@ -216,31 +402,60 @@ class LabeledValueExtractor(FieldExtractor):
|
||||
end = index.next_start(line_index, hit.end)
|
||||
tail = line.text[hit.end : end]
|
||||
tail = tail[len(SEPARATOR.match(tail).group()) :]
|
||||
tail = _within_cell(line, line.text.index(tail, hit.end) if tail else hit.end, tail)
|
||||
source_line = line
|
||||
below = False
|
||||
if not tail.strip() or (spec.multiline and spec.kind is FieldKind.TEXT):
|
||||
continuation = self._continuation(spec, index, line_index)
|
||||
continuation = self._continuation(spec, index, line_index, index.column(line_index, hit))
|
||||
if continuation is not None:
|
||||
tail, source_line = (f"{tail.strip()} {continuation[0]}".strip(), continuation[1])
|
||||
parsed = parse_value(spec, tail)
|
||||
below = True
|
||||
parsed = parse_value(spec, tail, ocr=line.ocr or source_line.ocr)
|
||||
if parsed is None:
|
||||
continue
|
||||
context = index.label_context(line_index, hit)
|
||||
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(line.text))
|
||||
confidence *= max(ASSERTION_WEIGHT[context.assertion], 0.1)
|
||||
features = {
|
||||
"assertion": context.assertion.value,
|
||||
"section": context.section.value,
|
||||
"label_score": hit.score,
|
||||
"parse_quality": parsed.quality,
|
||||
"value_below_label": below,
|
||||
"position": index.position(line_index),
|
||||
"ocr": line.ocr,
|
||||
}
|
||||
yield ExtractedValue(parsed.value, confidence, self.method, parsed.raw, source_line.evidence(line.text), features)
|
||||
|
||||
@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] = []
|
||||
def _continuation(
|
||||
spec: FieldSpec, index: LabelIndex, line_index: int, column: tuple[float, float] | None = None
|
||||
) -> tuple[str, SegmentLine] | None:
|
||||
"""The text under a label. When the label shares its line with
|
||||
other labels (a form laid out in columns, captions on one row and
|
||||
values on the next), only the words under this label's column
|
||||
count, and lines with nothing in that column are passed over."""
|
||||
limit = MAX_CONTINUATION_LINES if spec.multiline else (MAX_CHOICE_LOOKAHEAD if spec.kind is FieldKind.CHOICE else 1)
|
||||
collected: list[tuple[str, 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)
|
||||
text = candidate.text.strip()
|
||||
if column is not None and candidate.line.words:
|
||||
if index.label_in_column(following, column):
|
||||
break
|
||||
text = candidate.line.text_between(*column)
|
||||
if not text:
|
||||
continue
|
||||
collected.append((text, candidate))
|
||||
if spec.kind is FieldKind.CHOICE and parse_value(spec, text, ocr=candidate.ocr) is not None:
|
||||
break
|
||||
if not collected:
|
||||
return None
|
||||
return " ".join(line.text.strip() for line in collected), collected[0]
|
||||
return " ".join(text for text, _ in collected), collected[0][1]
|
||||
|
||||
|
||||
class PatternExtractor(FieldExtractor):
|
||||
@@ -260,64 +475,263 @@ class PatternExtractor(FieldExtractor):
|
||||
parsed = parse_value(spec, match.group())
|
||||
if parsed is None:
|
||||
continue
|
||||
context = index.context(line_index, match.start(), match.end())
|
||||
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())
|
||||
features = {
|
||||
"assertion": context.assertion.value,
|
||||
"section": context.section.value,
|
||||
"labelled_line": line_index in labelled_lines,
|
||||
"position": index.position(line_index),
|
||||
"ocr": line.ocr,
|
||||
}
|
||||
confidence = base * line.ocr_confidence * max(ASSERTION_WEIGHT[context.assertion], 0.1)
|
||||
yield ExtractedValue(parsed.value, confidence, self.method, match.group(), line.evidence(), features)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Mention:
|
||||
value: Any
|
||||
raw: str
|
||||
line_index: int
|
||||
context: Context
|
||||
anchored: bool
|
||||
generic: bool
|
||||
|
||||
@property
|
||||
def weight(self) -> float:
|
||||
return ASSERTION_WEIGHT[self.context.assertion]
|
||||
|
||||
|
||||
def _anchor_terms(spec: FieldSpec) -> tuple[str, ...]:
|
||||
return tuple(dict.fromkeys(fold(term).strip() for term in (*spec.anchors, *spec.labels) if term.strip()))
|
||||
|
||||
|
||||
@lru_cache(maxsize=2048)
|
||||
def _anchor_pattern(terms: tuple[str, ...]) -> re.Pattern | None:
|
||||
if not terms:
|
||||
return None
|
||||
body = "|".join(r"[\s.\-]+".join(re.escape(token) for token in term.split()) for term in sorted(terms, key=len, reverse=True))
|
||||
return re.compile(rf"(?<![A-Z0-9])(?:{body})(?![A-Z0-9])")
|
||||
|
||||
|
||||
# How far before a mention, on its line, its anchor may be.
|
||||
ANCHOR_REACH = 80
|
||||
|
||||
|
||||
def is_generic(surface: str) -> bool:
|
||||
from extraction.nlp.vocabulary import GENERIC_TERMS
|
||||
|
||||
return " ".join(surface.split()) in GENERIC_TERMS
|
||||
|
||||
|
||||
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,
|
||||
II...") without a label in front, each judged in its context
|
||||
(`extraction.nlp.context`): denied, hypothetical, historical or
|
||||
clinically presumed mentions count for little or nothing, a generic
|
||||
answer ("POSITIVO") only counts after its concept (`FieldSpec.anchors`),
|
||||
and a denied mention of a presence field gives its `negated_value`.
|
||||
|
||||
Every value mentioned is a candidate. The one proposed first is, for a
|
||||
field with a `severity` order, the most severe value the report
|
||||
affirms; otherwise the most repeated, ties going to the last mention,
|
||||
since reports state their conclusion at the end."""
|
||||
|
||||
method = "texto_libre"
|
||||
MIN_SURFACE_LENGTH = 4
|
||||
|
||||
def mentions(self, spec: FieldSpec, index: LabelIndex) -> list[Mention]:
|
||||
anchors = _anchor_pattern(_anchor_terms(spec))
|
||||
found: list[Mention] = []
|
||||
for line_index, line in enumerate(index.lines):
|
||||
texts = [(line.folded, False)]
|
||||
if line.ocr:
|
||||
texts.append((line.ocr_folded, True))
|
||||
seen: set[tuple[int, int]] = set()
|
||||
for text, canonical in texts:
|
||||
taken: list[tuple[int, int]] = []
|
||||
for surface in spec.surface_forms:
|
||||
if len(surface) < self.MIN_SURFACE_LENGTH:
|
||||
continue
|
||||
pattern = _choice_pattern(ocr_fold(surface) if canonical else surface)
|
||||
for match in pattern.finditer(text):
|
||||
span = (match.start(), match.end())
|
||||
# A longer surface already covers this one ("NIC III" over "NIC II").
|
||||
if span in seen or any(s <= span[0] and span[1] <= e for s, e in taken):
|
||||
continue
|
||||
taken.append(span)
|
||||
seen.add(span)
|
||||
context = index.context(line_index, *span)
|
||||
negates_itself = _negates_itself(surface)
|
||||
if negates_itself and context.assertion is Assertion.NEGADO:
|
||||
continue
|
||||
value = spec.choices[surface]
|
||||
if context.assertion is Assertion.NEGADO and not negates_itself:
|
||||
if spec.negated_value is None:
|
||||
continue
|
||||
value = spec.negated_value
|
||||
context = Context(Assertion.AFIRMADO, context.section, context.trigger)
|
||||
reach = text[max(0, span[0] - ANCHOR_REACH) : span[0]]
|
||||
anchored = bool(anchors and anchors.search(reach))
|
||||
generic = is_generic(surface)
|
||||
if generic and not anchored:
|
||||
continue
|
||||
found.append(Mention(value, line.text[span[0] : span[1]], line_index, context, anchored, generic))
|
||||
return found
|
||||
|
||||
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))
|
||||
mentions = [m for m in self.mentions(spec, index) if m.weight > 0]
|
||||
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())
|
||||
total = sum(m.weight for m in mentions)
|
||||
by_value: dict[Any, list[Mention]] = {}
|
||||
for mention in mentions:
|
||||
by_value.setdefault(mention.value, []).append(mention)
|
||||
support = {value: sum(m.weight for m in group) for value, group in by_value.items()}
|
||||
affirmed = [m for m in mentions if m.context.assertion is Assertion.AFIRMADO]
|
||||
if spec.severity and affirmed:
|
||||
winner_value = max((m.value for m in affirmed), key=lambda v: (spec.severity_rank(v), support[v]))
|
||||
else:
|
||||
top = max(support.values())
|
||||
winner_value = [m for m in mentions if support[m.value] == top][-1].value
|
||||
most_severe = max(by_value, key=spec.severity_rank) if spec.severity else None
|
||||
|
||||
def confidence_of(value: Any, best: Mention) -> float:
|
||||
share = support[value] / total
|
||||
return 0.65 * max(share, 0.5) * index.lines[best.line_index].ocr_confidence * best.weight
|
||||
|
||||
best_of = {value: max(group, key=lambda m: (m.weight, m.line_index)) for value, group in by_value.items()}
|
||||
winner_confidence = confidence_of(winner_value, best_of[winner_value])
|
||||
for value, group in by_value.items():
|
||||
best = best_of[value]
|
||||
line = index.lines[best.line_index]
|
||||
share = support[value] / total
|
||||
confidence = winner_confidence
|
||||
if value != winner_value:
|
||||
# The others stay below the winner, so ranking by confidence picks it.
|
||||
confidence = min(0.8 * confidence_of(value, best), 0.9 * winner_confidence)
|
||||
features = {
|
||||
"assertion": best.context.assertion.value,
|
||||
"section": best.context.section.value,
|
||||
"share": share,
|
||||
"mentions": len(group),
|
||||
"anchored": best.anchored,
|
||||
"generic": best.generic,
|
||||
"most_severe": spec.severity and value == most_severe,
|
||||
"last_mention": best.line_index == max(m.line_index for m in mentions),
|
||||
"position": index.position(best.line_index),
|
||||
"ocr": line.ocr,
|
||||
}
|
||||
yield ExtractedValue(value, confidence, self.method, best.raw, line.evidence(), features)
|
||||
|
||||
|
||||
class MeasurementExtractor(FieldExtractor):
|
||||
"""A number written with its unit after the field's concept, in the same
|
||||
clause ("ritmo de fondo de 8 a 9 Hz"), for fields with a `unit`. A range
|
||||
gives its midpoint."""
|
||||
|
||||
method = "medicion"
|
||||
_NUMBER = r"\d+(?:[.,]\d+)?"
|
||||
|
||||
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
|
||||
if not spec.unit or spec.kind not in (FieldKind.DECIMAL, FieldKind.INTEGER):
|
||||
return
|
||||
anchors = _anchor_pattern(_anchor_terms(spec))
|
||||
measure = re.compile(
|
||||
rf"(?<![\w.,])(?P<low>{self._NUMBER})(?:\s*(?:-|A|Y|AL)\s*(?P<high>{self._NUMBER}))?\s*(?:{spec.unit})(?![A-Z])"
|
||||
)
|
||||
for line_index, line in enumerate(index.lines):
|
||||
folded = line.folded
|
||||
for match in measure.finditer(folded):
|
||||
reach = folded[max(0, match.start() - ANCHOR_REACH) : match.start()]
|
||||
anchor = anchors.search(reach) if anchors else None
|
||||
if anchor is None:
|
||||
continue
|
||||
if re.search(r"[.;]", reach[anchor.end() :]):
|
||||
continue
|
||||
low = float(match.group("low").replace(",", "."))
|
||||
high = float(match.group("high").replace(",", ".")) if match.group("high") else low
|
||||
value: float | int = (low + high) / 2
|
||||
if spec.kind is FieldKind.INTEGER:
|
||||
value = int(round(value))
|
||||
context = index.context(line_index, match.start(), match.end())
|
||||
if context.assertion is Assertion.NEGADO:
|
||||
continue
|
||||
features = {
|
||||
"assertion": context.assertion.value,
|
||||
"section": context.section.value,
|
||||
"anchored": True,
|
||||
"range": match.group("high") is not None,
|
||||
"position": index.position(line_index),
|
||||
"ocr": line.ocr,
|
||||
}
|
||||
confidence = 0.8 * line.ocr_confidence * ASSERTION_WEIGHT[context.assertion]
|
||||
yield ExtractedValue(value, confidence, self.method, line.text[match.start() : match.end()], line.evidence(), features)
|
||||
|
||||
|
||||
DEFAULT_EXTRACTORS: tuple[FieldExtractor, ...] = (
|
||||
LabeledValueExtractor(),
|
||||
PatternExtractor(),
|
||||
FreeTextMentionExtractor(),
|
||||
MeasurementExtractor(),
|
||||
)
|
||||
|
||||
|
||||
class RecordExtractor:
|
||||
def __init__(self, specs: Sequence[FieldSpec], *, extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS):
|
||||
"""Every candidate of every field, then one per field: the ranker's pick
|
||||
(`extraction.nlp.ranking`), by default the most confident."""
|
||||
|
||||
def __init__(self, specs: Sequence[FieldSpec], *, extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS, ranker=None):
|
||||
from extraction.nlp.ranking import HeuristicRanker
|
||||
|
||||
self.specs = list(specs)
|
||||
self.extractors = list(extractors)
|
||||
self.ranker = ranker or HeuristicRanker()
|
||||
|
||||
def candidates(self, lines: Sequence[SegmentLine]) -> dict[str, list[ExtractedValue]]:
|
||||
index = LabelIndex(lines, self.specs)
|
||||
found: dict[str, list[ExtractedValue]] = {}
|
||||
for spec in self.specs:
|
||||
proposed = [candidate for extractor in self.extractors for candidate in extractor.candidates(spec, index)]
|
||||
if proposed:
|
||||
found[spec.name] = describe_candidates(proposed)
|
||||
return found
|
||||
|
||||
def choose(self, candidates: dict[str, list[ExtractedValue]]) -> dict[str, ExtractedValue]:
|
||||
specs = {spec.name: spec for spec in self.specs}
|
||||
chosen = {}
|
||||
for name, proposed in candidates.items():
|
||||
best = self.ranker.choose(specs[name], proposed)
|
||||
if best is not None:
|
||||
chosen[name] = best
|
||||
return chosen
|
||||
|
||||
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
|
||||
return self.choose(self.candidates(lines))
|
||||
|
||||
|
||||
def describe_candidates(proposed: list[ExtractedValue]) -> list[ExtractedValue]:
|
||||
"""Adds what only the set of a field's candidates tells: how each ranks
|
||||
by confidence, how many there are and how many others agree with it."""
|
||||
ordered = sorted(proposed, key=lambda c: -c.confidence)
|
||||
values = Counter(_comparable(c.value) for c in proposed)
|
||||
methods: dict[Any, set[str]] = {}
|
||||
for candidate in proposed:
|
||||
methods.setdefault(_comparable(candidate.value), set()).add(candidate.method)
|
||||
return [
|
||||
candidate.with_confidence(
|
||||
candidate.confidence,
|
||||
rank=rank,
|
||||
candidates=len(proposed),
|
||||
distinct_values=len(values),
|
||||
agreeing=values[_comparable(candidate.value)] - 1,
|
||||
agreeing_methods=len(methods[_comparable(candidate.value)]) - 1,
|
||||
)
|
||||
for rank, candidate in enumerate(ordered)
|
||||
]
|
||||
|
||||
|
||||
def _comparable(value: Any) -> Any:
|
||||
return fold(value).strip() if isinstance(value, str) else value
|
||||
|
||||
@@ -27,6 +27,13 @@ class FieldSpec:
|
||||
`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.
|
||||
|
||||
In narrative text a generic answer ("POSITIVO") only counts next to one
|
||||
of `anchors` or `labels`; `severity` orders the choice values from least
|
||||
to most severe, and the most severe one a report affirms is its finding;
|
||||
`negated_value` is what a denied mention means ("sin actividad
|
||||
epileptiforme" -> 0); `unit` is a pattern for the unit a measurement is
|
||||
written in (`HZ`).
|
||||
"""
|
||||
|
||||
name: str
|
||||
@@ -37,6 +44,10 @@ class FieldSpec:
|
||||
scan_free_text: bool = False
|
||||
multiline: bool = False
|
||||
required: bool = False
|
||||
anchors: tuple[str, ...] = ()
|
||||
severity: tuple[Any, ...] = ()
|
||||
negated_value: Any = None
|
||||
unit: str | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
folded = {fold(str(surface)).strip(): value for surface, value in self.choices.items() if str(surface).strip()}
|
||||
@@ -46,6 +57,9 @@ class FieldSpec:
|
||||
def surface_forms(self) -> list[str]:
|
||||
return sorted(self.choices, key=len, reverse=True)
|
||||
|
||||
def severity_rank(self, value: Any) -> int:
|
||||
return self.severity.index(value) if value in self.severity else -1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Evidence:
|
||||
@@ -57,11 +71,19 @@ class Evidence:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractedValue:
|
||||
"""One reading of a field. `features` describe how it was found (the
|
||||
mention's assertion and section, the label's score...), for
|
||||
`extraction.nlp.ranking`; they never hold the document's text."""
|
||||
|
||||
value: Any
|
||||
confidence: float
|
||||
method: str
|
||||
raw: str
|
||||
evidence: Evidence
|
||||
features: Mapping[str, Any] = field(default_factory=dict, compare=False, hash=False)
|
||||
|
||||
def with_confidence(self, confidence: float, **features: Any) -> "ExtractedValue":
|
||||
return ExtractedValue(self.value, confidence, self.method, self.raw, self.evidence, {**self.features, **features})
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
value = self.value.isoformat() if isinstance(self.value, date) else self.value
|
||||
@@ -74,4 +96,5 @@ class ExtractedValue:
|
||||
"page_number": self.evidence.page_number,
|
||||
"line": self.evidence.line,
|
||||
"bbox": self.evidence.bbox,
|
||||
"assertion": self.features.get("assertion"),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Choosing one reading per field among the candidates the extractors
|
||||
propose, and learning to choose better from the corrections people make.
|
||||
|
||||
`HeuristicRanker` keeps the most confident candidate. `LearnedRanker` is a
|
||||
logistic regression over how each candidate was found (its method, the
|
||||
assertion and section of its mention, the label's score, how many other
|
||||
candidates agree with it...), never over the document's words: its weights
|
||||
can be read, and it holds nothing a patient wrote or was written about.
|
||||
It learns online, one batch of reviewed records at a time (AdaGrad with L2,
|
||||
Duchi et al., 2011), so a correction made today improves tomorrow's
|
||||
extraction without retraining from scratch.
|
||||
|
||||
While it has seen few examples its score is blended with the heuristic
|
||||
one (`HeuristicRanker`, rules included), trusting it more as examples
|
||||
accumulate (`TRUST_EXAMPLES`).
|
||||
"""
|
||||
import math
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable, Mapping, Sequence
|
||||
|
||||
from extraction.nlp.fields import ExtractedValue, FieldSpec
|
||||
from extraction.nlp.text import fold
|
||||
|
||||
# Examples after which the learned score is trusted fully over the heuristic.
|
||||
TRUST_EXAMPLES = 200
|
||||
# Below this score, a field is left empty rather than filled with its best
|
||||
# guess; a trusted learned ranker leaves it empty below even odds.
|
||||
MIN_SCORE = 0.05
|
||||
LEARNED_MIN_SCORE = 0.5
|
||||
|
||||
|
||||
class CandidateRanker(ABC):
|
||||
version: str | None = None
|
||||
|
||||
@property
|
||||
def min_score(self) -> float:
|
||||
return MIN_SCORE
|
||||
|
||||
@abstractmethod
|
||||
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float: ...
|
||||
|
||||
def choose(self, spec: FieldSpec, candidates: Sequence[ExtractedValue]) -> ExtractedValue | None:
|
||||
"""The best candidate, its confidence replaced by its score."""
|
||||
scored = [(self.score(spec, candidate), candidate) for candidate in candidates]
|
||||
if not scored:
|
||||
return None
|
||||
score, best = max(scored, key=lambda pair: (pair[0], pair[1].confidence))
|
||||
if score < self.min_score:
|
||||
return None
|
||||
return best.with_confidence(score)
|
||||
|
||||
|
||||
class HeuristicRanker(CandidateRanker):
|
||||
"""The most confident candidate, except that a document about something
|
||||
else than the target, or a mention the report only supposes, fills
|
||||
nothing: those are left for a person, and for a learned ranker to weigh."""
|
||||
|
||||
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float:
|
||||
if candidate.features.get("on_topic") is False or candidate.features.get("assertion") == "hipotetico":
|
||||
return 0.0
|
||||
return candidate.confidence
|
||||
|
||||
|
||||
def features(spec: FieldSpec, candidate: ExtractedValue) -> dict[str, float]:
|
||||
"""A candidate as named features: categorical ones one-hot, numeric ones
|
||||
as they are; field and method crossed with the rest, so each field can
|
||||
weigh each kind of evidence its own way."""
|
||||
out: dict[str, float] = {"bias": 1.0, f"kind={spec.kind.value}": 1.0}
|
||||
prefixes = (f"method={candidate.method}", f"field={spec.name}", f"field={spec.name}|method={candidate.method}")
|
||||
out.update({prefix: 1.0 for prefix in prefixes})
|
||||
numeric = {"heuristic": candidate.confidence}
|
||||
categorical: dict[str, str] = {}
|
||||
for key, value in candidate.features.items():
|
||||
if isinstance(value, bool):
|
||||
numeric[key] = float(value)
|
||||
elif isinstance(value, (int, float)):
|
||||
numeric[key] = float(value)
|
||||
elif isinstance(value, str):
|
||||
categorical[key] = value
|
||||
numeric["log_candidates"] = math.log1p(numeric.pop("candidates", 0.0))
|
||||
numeric["first"] = float(numeric.pop("rank", 1.0) == 0)
|
||||
for key, value in numeric.items():
|
||||
out[key] = value
|
||||
out[f"method={candidate.method}|{key}"] = value
|
||||
for key, value in categorical.items():
|
||||
out[f"{key}={value}"] = 1.0
|
||||
out[f"method={candidate.method}|{key}={value}"] = 1.0
|
||||
out[f"field={spec.name}|{key}={value}"] = 1.0
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class LearnedRanker(CandidateRanker):
|
||||
weights: dict[str, float] = field(default_factory=dict)
|
||||
squared_gradients: dict[str, float] = field(default_factory=dict)
|
||||
examples: int = 0
|
||||
positives: int = 0
|
||||
learning_rate: float = 0.3
|
||||
l2: float = 1e-4
|
||||
version: str | None = None
|
||||
|
||||
def probability(self, x: Mapping[str, float]) -> float:
|
||||
z = sum(self.weights.get(name, 0.0) * value for name, value in x.items())
|
||||
return 1.0 / (1.0 + math.exp(-max(-30.0, min(30.0, z))))
|
||||
|
||||
@property
|
||||
def trust(self) -> float:
|
||||
return min(1.0, self.examples / TRUST_EXAMPLES)
|
||||
|
||||
@property
|
||||
def min_score(self) -> float:
|
||||
return self.trust * LEARNED_MIN_SCORE + (1.0 - self.trust) * MIN_SCORE
|
||||
|
||||
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float:
|
||||
heuristic = HeuristicRanker().score(spec, candidate)
|
||||
if heuristic == 0.0 and self.trust < 1.0:
|
||||
# What the rules rule out stays out until the ranker is fully trusted.
|
||||
return 0.0
|
||||
learned = self.probability(features(spec, candidate))
|
||||
return self.trust * learned + (1.0 - self.trust) * heuristic
|
||||
|
||||
def learn(self, examples: Iterable["Example"], *, epochs: int = 1) -> None:
|
||||
"""One pass (or `epochs`) of AdaGrad over the examples. Positives are
|
||||
weighted by how rare they are among them, so a field with many wrong
|
||||
candidates per right one still learns what right looks like."""
|
||||
batch = list(examples)
|
||||
if not batch:
|
||||
return
|
||||
positives = sum(1 for e in batch if e.label)
|
||||
negatives = len(batch) - positives
|
||||
positive_weight = min(5.0, negatives / positives) if positives else 1.0
|
||||
for _ in range(epochs):
|
||||
for example in batch:
|
||||
x = example.x
|
||||
error = self.probability(x) - (1.0 if example.label else 0.0)
|
||||
scale = positive_weight if example.label else 1.0
|
||||
for name, value in x.items():
|
||||
gradient = scale * error * value + self.l2 * self.weights.get(name, 0.0)
|
||||
accumulated = self.squared_gradients.get(name, 0.0) + gradient * gradient
|
||||
self.squared_gradients[name] = accumulated
|
||||
self.weights[name] = self.weights.get(name, 0.0) - self.learning_rate * gradient / (math.sqrt(accumulated) + 1e-8)
|
||||
self.examples += len(batch)
|
||||
self.positives += positives
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"weights": self.weights,
|
||||
"squared_gradients": self.squared_gradients,
|
||||
"examples": self.examples,
|
||||
"positives": self.positives,
|
||||
"learning_rate": self.learning_rate,
|
||||
"l2": self.l2,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any], *, version: str | None = None) -> "LearnedRanker":
|
||||
return cls(
|
||||
weights=dict(data.get("weights", {})),
|
||||
squared_gradients=dict(data.get("squared_gradients", {})),
|
||||
examples=int(data.get("examples", 0)),
|
||||
positives=int(data.get("positives", 0)),
|
||||
learning_rate=float(data.get("learning_rate", 0.3)),
|
||||
l2=float(data.get("l2", 1e-4)),
|
||||
version=version,
|
||||
)
|
||||
|
||||
def copy(self) -> "LearnedRanker":
|
||||
return LearnedRanker.from_dict(self.to_dict(), version=self.version)
|
||||
|
||||
def strongest(self, count: int = 15) -> list[tuple[str, float]]:
|
||||
return sorted(self.weights.items(), key=lambda item: -abs(item[1]))[:count]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Example:
|
||||
field: str
|
||||
x: Mapping[str, float]
|
||||
label: bool
|
||||
|
||||
|
||||
def same_value(left: Any, right: Any) -> bool:
|
||||
"""Whether an extracted value is the one a person said is right:
|
||||
dates by day, numbers by value, text without case or accents."""
|
||||
if left is None or right is None:
|
||||
return left is None and right is None
|
||||
if isinstance(left, (date, datetime)) or isinstance(right, (date, datetime)):
|
||||
return _as_date(left) is not None and _as_date(left) == _as_date(right)
|
||||
if isinstance(left, (int, float)) and not isinstance(left, bool) or isinstance(right, (int, float)) and not isinstance(right, bool):
|
||||
try:
|
||||
return abs(float(left) - float(right)) < 1e-6
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return " ".join(fold(str(left)).split()) == " ".join(fold(str(right)).split())
|
||||
|
||||
|
||||
def _as_date(value: Any) -> date | None:
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
try:
|
||||
return date.fromisoformat(str(value)[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def examples_for(
|
||||
specs: Sequence[FieldSpec], candidates: Mapping[str, Sequence[ExtractedValue]], truth: Mapping[str, Any]
|
||||
) -> list[Example]:
|
||||
"""Labelled examples from one record: every candidate of a field whose
|
||||
right value is known is right (it equals that value) or wrong. A field
|
||||
known to be empty makes all its candidates wrong; a field not in
|
||||
`truth` teaches nothing."""
|
||||
by_name = {spec.name: spec for spec in specs}
|
||||
found = []
|
||||
for name, value in truth.items():
|
||||
spec = by_name.get(name)
|
||||
if spec is None:
|
||||
continue
|
||||
for candidate in candidates.get(name, ()):
|
||||
found.append(Example(name, features(spec, candidate), value is not None and same_value(candidate.value, value)))
|
||||
return found
|
||||
@@ -22,16 +22,69 @@ def fold(text: str) -> str:
|
||||
return "".join(fold_char(ch) for ch in text)
|
||||
|
||||
|
||||
# Characters OCR confuses with each other, mapped to one representative.
|
||||
# Digits only count as letters inside a word, so `NIC 1` and `10.-` keep theirs.
|
||||
_OCR_LETTERS = {"L": "I", "!": "I", "|": "I", "J": "I"}
|
||||
_OCR_DIGITS = {"1": "I", "0": "O", "5": "S", "8": "B"}
|
||||
|
||||
|
||||
def ocr_fold(text: str) -> str:
|
||||
"""`fold`, then OCR look-alikes collapsed (`DLAGNOSTLCO`, `COND!LOMA`,
|
||||
`NAC1MIENTO`), keeping the length. Both sides of a comparison go
|
||||
through it, so a confusion matches whichever way it went."""
|
||||
folded = fold(text)
|
||||
out = []
|
||||
for i, ch in enumerate(folded):
|
||||
if ch in _OCR_LETTERS:
|
||||
ch = _OCR_LETTERS[ch]
|
||||
elif ch in _OCR_DIGITS:
|
||||
before = folded[i - 1] if i else " "
|
||||
after = folded[i + 1] if i + 1 < len(folded) else " "
|
||||
if before.isalpha() or after.isalpha():
|
||||
ch = _OCR_DIGITS[ch]
|
||||
out.append(ch)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
# Words a caption may drop without changing what it names.
|
||||
_CONNECTORS = frozenset({"DE", "DEL", "LA", "EL", "LOS", "LAS", "EN", "PARA", "POR", "AL", "Y"})
|
||||
_LABEL_SEPARATOR = r"[\s.\-_/]*"
|
||||
# A date caption may also announce the time: `FECHA/HORA DE REPORTE`, `FECHA Y HORA DE...`.
|
||||
_TIME_QUALIFIER = r"(?:(?:Y\s+)?HORA[\s.\-_/]*)?"
|
||||
# Shortest abbreviation of a caption word: `NAC.` for `NACIMIENTO`.
|
||||
MIN_ABBREVIATION = 3
|
||||
|
||||
|
||||
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."""
|
||||
variants, on word boundaries. Long words may be abbreviated with a
|
||||
period (`FECH. NAC.`), connectors between words left out
|
||||
(`FECHA NACIMIENTO`) and a date caption may name the time too
|
||||
(`FECHA/HORA DE NACIMIENTO`)."""
|
||||
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])")
|
||||
parts = []
|
||||
for position, token in enumerate(tokens):
|
||||
last = position == len(tokens) - 1
|
||||
word = _abbreviable(token) + ("" if last else _LABEL_SEPARATOR)
|
||||
optional = token in _CONNECTORS and 0 < position and not last
|
||||
parts.append(f"(?:{word})?" if optional else word)
|
||||
if token == "FECHA" and not last:
|
||||
parts.append(_TIME_QUALIFIER)
|
||||
return re.compile(rf"(?<![A-Z0-9]){''.join(parts)}\.?(?![A-Z0-9])")
|
||||
|
||||
|
||||
SEPARATOR = re.compile(r"^[\s.:\-=#•|]*")
|
||||
def _abbreviable(token: str) -> str:
|
||||
if len(token) <= MIN_ABBREVIATION + 1 or not token.isalpha():
|
||||
return re.escape(token)
|
||||
head, rest = token[:MIN_ABBREVIATION], token[MIN_ABBREVIATION:-1]
|
||||
nested = ""
|
||||
for char in reversed(rest):
|
||||
nested = f"(?:{re.escape(char)}{nested})?"
|
||||
return f"(?:{re.escape(token)}|{re.escape(head)}{nested}\\.)"
|
||||
|
||||
|
||||
SEPARATOR = re.compile(r"^[\s.:\-=#•|)]*")
|
||||
|
||||
MONTHS = {
|
||||
"ENERO": 1, "ENE": 1, "JAN": 1, "JANUARY": 1,
|
||||
|
||||
@@ -19,10 +19,10 @@ LABELS: dict[str, tuple[str, ...]] = {
|
||||
"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_calidad_especimen": ("calidad de la muestra", "calidad del espécimen", "calidad de 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_dx_lesion": ("diagnóstico",),
|
||||
"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"),
|
||||
@@ -156,7 +156,242 @@ def labels_for(column: str, description: str | None = None) -> tuple[str, ...]:
|
||||
if words and words not in labels and not words.isdigit():
|
||||
labels.append(words)
|
||||
if description:
|
||||
short = description.split("—")[0].split("(")[0].strip()
|
||||
short = _caption_from_description(description)
|
||||
if short and len(short.split()) <= 5 and short.lower() not in (label.lower() for label in labels):
|
||||
labels.append(short)
|
||||
return tuple(labels)
|
||||
|
||||
|
||||
_DESCRIPTION_CODE = re.compile(r"^\s*[A-Z]{1,4}[-.]?\d+[A-Z]?[.:)\-]*\s+")
|
||||
|
||||
|
||||
def _caption_from_description(description: str) -> str:
|
||||
"""The part of a schema description a form would print as the
|
||||
caption: without a leading item code (`A1.`) or what follows a dash,
|
||||
a parenthesis or a colon."""
|
||||
short = _DESCRIPTION_CODE.sub("", description)
|
||||
for cut in ("—", "(", ":", ";", ","):
|
||||
short = short.split(cut)[0]
|
||||
return short.strip()
|
||||
|
||||
|
||||
# What a report is about, per target table: a document that names none of
|
||||
# these is probably a different kind of report (a biopsy read as a cytology).
|
||||
SUBJECTS: dict[str, tuple[str, ...]] = {
|
||||
"citologiacervical": ("citología", "citológico", "papanicolaou", "papanicolau", "bethesda", "virus del papiloma", "vph", "hpv"),
|
||||
"biopsiacervical": ("biopsia", "histopatológico", "histopatología", "histológico", "cono cervical", "conización"),
|
||||
"mastografia": ("mastografía", "mamografía", "mastográfico", "bi-rads", "birads", "tomosíntesis"),
|
||||
"biopsiamama": ("biopsia", "histopatológico", "histopatología", "trucut", "tru-cut", "aguja gruesa", "mama"),
|
||||
"eeg_estudio": ("electroencefalograma", "electroencefalografía", "electroencefalográfico", "eeg", "video-eeg", "videoelectroencefalograma"),
|
||||
}
|
||||
|
||||
# Concepts a generic answer must be next to, in narrative text, to count for
|
||||
# a field: "POSITIVO" alone says nothing about which test was positive.
|
||||
ANCHORS: dict[str, tuple[str, ...]] = {
|
||||
"cit_vph_resultado": ("vph", "hpv", "virus del papiloma", "papiloma humano"),
|
||||
"cit_vph_genotipo_16": ("16",),
|
||||
"cit_vph_genotipo_18": ("18",),
|
||||
"cit_celulas_escamosas": ("escamosa", "escamosas", "intraepitelial", "células", "citológico", "citología"),
|
||||
"bx_cin_grado": ("biopsia", "cérvix", "cervix", "diagnóstico", "intraepitelial", "displasia"),
|
||||
"eeg_anormalidad_presente": ("eeg", "electroencefalograma", "trazo", "registro", "estudio"),
|
||||
"eeg_actividad_epileptiforme": ("epileptiforme", "epileptiformes", "paroxística", "paroxísticas"),
|
||||
"eeg_ritmo_base_frecuencia": ("ritmo de fondo", "actividad de fondo", "ritmo base", "ritmo de base", "ritmo dominante", "ritmo posterior", "actividad basal", "ritmo alfa", "frecuencia"),
|
||||
"eeg_ritmo_base_amplitud": ("amplitud", "voltaje"),
|
||||
"eeg_duracion_min": ("duración", "registro de", "tiempo de registro"),
|
||||
}
|
||||
|
||||
# Answers that mean nothing without their concept (`ANCHORS`).
|
||||
GENERIC_TERMS = frozenset(
|
||||
{"POSITIVO", "POSITIVA", "NEGATIVO", "NEGATIVA", "SI", "NO", "PRESENTE", "AUSENTE", "DETECTADO", "NO DETECTADO",
|
||||
"NORMAL", "ANORMAL", "REACTIVO", "NO REACTIVO", "INDETERMINADO", "INVALIDO", "NO CONCLUYENTE"}
|
||||
)
|
||||
|
||||
# Catalog values from least to most severe. When a report names several
|
||||
# (one per specimen, one per breast), the most severe one is the finding.
|
||||
SEVERITY: dict[str, tuple[str, ...]] = {
|
||||
"cit_celulas_escamosas": ("NORMAL", "ASC-US", "LIEBG", "ASC-H", "LIEAG", "CIS"),
|
||||
"bx_cin_grado": ("NORMAL", "LIEBG", "LIEAG", "CIS", "CARCINOMA"),
|
||||
"bx_grado_histologico": ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"),
|
||||
"mast_birads": ("1", "2", "3", "4", "4A", "4B", "4C", "5", "6"),
|
||||
"eeg_tipo_grafoelemento": ("NINGUNO", "OTRO", "DESCARGA_RITMICA", "ONDA_AGUDA", "ESPIGA", "PUNTA_ONDA_LENTA", "COMPLEJO_ESPIGA_ONDA", "COMPLEJO_POLIESPIGA_ONDA"),
|
||||
}
|
||||
|
||||
# What a denied mention means for a presence field ("sin actividad epileptiforme").
|
||||
NEGATED_VALUES: dict[str, object] = {
|
||||
"eeg_actividad_epileptiforme": 0,
|
||||
"eeg_crisis_registradas": 0,
|
||||
"eeg_tipo_grafoelemento": "NINGUNO",
|
||||
"eeg_lentificacion": "NINGUNA",
|
||||
"eeg_anormalidad_presente": 0,
|
||||
}
|
||||
|
||||
# Units a measurement is written in, as a regular expression over folded text.
|
||||
UNITS: dict[str, str] = {
|
||||
"eeg_ritmo_base_frecuencia": r"HZ|HERTZ|C\s*/\s*S|CPS|CICLOS\s+POR\s+SEGUNDO",
|
||||
"eeg_ritmo_base_amplitud": r"[µU]\s*V|MCV|MICROVOLTIOS?",
|
||||
"eeg_duracion_min": r"MIN(?:UTOS?)?\.?",
|
||||
}
|
||||
|
||||
# Report section headings (`extraction.nlp.context`). The longest match wins,
|
||||
# so "diagnóstico clínico" opens a clinical section and "diagnóstico" a result.
|
||||
SECTION_HEADINGS: dict = {}
|
||||
|
||||
# ConText trigger phrases, by the assertion they make about a mention after them.
|
||||
PRE_TRIGGERS: dict = {}
|
||||
PSEUDO_TRIGGERS: tuple[str, ...] = ()
|
||||
CLAUSE_TERMINATORS: tuple[str, ...] = ()
|
||||
POST_NEGATIONS: tuple[str, ...] = ()
|
||||
POST_AFFIRMATIONS: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def _context_vocabulary() -> None:
|
||||
from extraction.nlp.context import Assertion, Section
|
||||
|
||||
global PSEUDO_TRIGGERS, CLAUSE_TERMINATORS, POST_NEGATIONS, POST_AFFIRMATIONS
|
||||
SECTION_HEADINGS.update({
|
||||
Section.CLINICA: (
|
||||
"datos clínicos", "resumen clínico", "diagnóstico clínico", "diagnóstico de envío",
|
||||
"diagnóstico presuntivo", "diagnóstico de ingreso", "diagnóstico previo", "impresión clínica", "sospecha clínica",
|
||||
"indicación", "indicaciones", "motivo del estudio", "motivo de envío", "motivo de solicitud", "cuadro clínico",
|
||||
),
|
||||
Section.DESCRIPCION: (
|
||||
"descripción", "descripción macroscópica", "descripción microscópica", "macroscópico", "microscópico", "técnica",
|
||||
"hallazgos", "descripción del trazo", "descripción del registro", "especimen", "espécimen", "muestra",
|
||||
),
|
||||
Section.RESULTADO: (
|
||||
"diagnóstico", "diagnósticos", "diagnóstico final", "diagnóstico histopatológico", "diagnóstico patológico",
|
||||
"diagnóstico citológico", "conclusión", "conclusiones", "resultado", "resultados", "impresión diagnóstica",
|
||||
"interpretación", "dictamen",
|
||||
),
|
||||
Section.ANTECEDENTES: (
|
||||
"antecedentes", "antecedentes personales", "antecedentes patológicos", "antecedentes familiares",
|
||||
"estudios previos", "historia clínica",
|
||||
),
|
||||
Section.REFERENCIA: (
|
||||
"valores de referencia", "valor de referencia", "intervalo de referencia", "intervalos de referencia",
|
||||
"rango de referencia", "criterios de interpretación",
|
||||
"metodología", "método", "limitaciones", "aviso", "advertencia", "nota técnica", "comentario técnico",
|
||||
"aviso de privacidad",
|
||||
),
|
||||
})
|
||||
PRE_TRIGGERS.update({
|
||||
Assertion.NEGADO: (
|
||||
"no", "sin", "ni", "nunca", "niega", "negativo para", "negativa para", "negativo a", "ausencia de", "ausente",
|
||||
"descartado", "se descarta", "no se observa", "no se observan", "no hay", "libre de", "no se identifica",
|
||||
"no se identifican", "no muestra", "no presenta", "no evidencia", "sin evidencia de",
|
||||
),
|
||||
Assertion.HIPOTETICO: (
|
||||
"en caso de", "si se", "si el", "si la", "si hay", "si existe", "un resultado", "cuando", "puede", "pueden",
|
||||
"podría", "podrían", "se recomienda", "riesgo de", "para descartar", "a descartar", "descartar", "de ser",
|
||||
"en presencia de", "indica que", "se sugiere",
|
||||
),
|
||||
Assertion.HISTORICO: (
|
||||
"antecedente de", "antecedentes de", "historia de", "previo", "previa", "previamente", "tratada por",
|
||||
"tratado por", "postoperada de", "operada de", "conocida con",
|
||||
),
|
||||
Assertion.INCIERTO: (
|
||||
"probable", "probablemente", "posible", "posiblemente", "sospecha de", "sospechoso de", "sospechosa de",
|
||||
"no se descarta", "dudoso", "dudosa", "impresiona", "a considerar", "vs",
|
||||
),
|
||||
})
|
||||
PSEUDO_TRIGGERS = ("sin embargo", "no obstante", "no solo", "no sólo", "sin cambios", "no se descarta")
|
||||
CLAUSE_TERMINATORS = ("pero", "aunque", "excepto", "salvo", "sin embargo", "no obstante")
|
||||
POST_NEGATIONS = ("no", "negativo", "negativa", "ausente", "ausentes", "no se observa", "no detectado", "no detectada", "descartado", "descartada")
|
||||
POST_AFFIRMATIONS = ("si", "sí", "positivo", "positiva", "presente", "presentes", "detectado", "detectada")
|
||||
|
||||
|
||||
_context_vocabulary()
|
||||
|
||||
# EEG findings as reports state them (ACNS standardized terminology, 2021, in Spanish).
|
||||
CLINICAL_TERMS.update({
|
||||
"eeg_simetria": {
|
||||
"SIMETRICO": "SIMETRICO", "SIMETRICA": "SIMETRICO", "SIMETRICOS": "SIMETRICO", "ADECUADA SIMETRIA": "SIMETRICO",
|
||||
"ASIMETRIA IZQUIERDA": "ASIMETRICO_IZQUIERDO", "ASIMETRICO IZQUIERDO": "ASIMETRICO_IZQUIERDO",
|
||||
"ASIMETRIA DERECHA": "ASIMETRICO_DERECHO", "ASIMETRICO DERECHO": "ASIMETRICO_DERECHO",
|
||||
},
|
||||
"eeg_anormalidad_presente": {
|
||||
"EEG ANORMAL": 1, "ESTUDIO ANORMAL": 1, "TRAZO ANORMAL": 1, "REGISTRO ANORMAL": 1, "ANORMAL": 1,
|
||||
"EEG NORMAL": 0, "ESTUDIO NORMAL": 0, "TRAZO NORMAL": 0, "REGISTRO NORMAL": 0, "DENTRO DE LIMITES NORMALES": 0,
|
||||
"SIN ALTERACIONES": 0,
|
||||
},
|
||||
"eeg_actividad_epileptiforme": {
|
||||
"ACTIVIDAD EPILEPTIFORME": 1, "DESCARGAS EPILEPTIFORMES": 1, "GRAFOELEMENTOS EPILEPTIFORMES": 1,
|
||||
"ACTIVIDAD PAROXISTICA": 1, "DESCARGAS PAROXISTICAS": 1, "PUNTAS": 1, "ESPIGAS": 1, "POLIPUNTAS": 1,
|
||||
"PUNTA ONDA": 1, "ONDAS AGUDAS": 1,
|
||||
},
|
||||
"eeg_tipo_grafoelemento": {
|
||||
"ESPIGA": "ESPIGA", "ESPIGAS": "ESPIGA", "PUNTA": "ESPIGA", "PUNTAS": "ESPIGA",
|
||||
"ONDA AGUDA": "ONDA_AGUDA", "ONDAS AGUDAS": "ONDA_AGUDA",
|
||||
"COMPLEJO ESPIGA ONDA": "COMPLEJO_ESPIGA_ONDA", "COMPLEJOS ESPIGA ONDA": "COMPLEJO_ESPIGA_ONDA", "PUNTA ONDA": "COMPLEJO_ESPIGA_ONDA",
|
||||
"POLIESPIGA ONDA": "COMPLEJO_POLIESPIGA_ONDA", "POLIPUNTA ONDA": "COMPLEJO_POLIESPIGA_ONDA", "POLIPUNTAS": "COMPLEJO_POLIESPIGA_ONDA",
|
||||
"PUNTA ONDA LENTA": "PUNTA_ONDA_LENTA", "ESPIGA ONDA LENTA": "PUNTA_ONDA_LENTA",
|
||||
"DESCARGA RITMICA": "DESCARGA_RITMICA", "DESCARGAS RITMICAS": "DESCARGA_RITMICA",
|
||||
"GRAFOELEMENTOS EPILEPTIFORMES": "OTRO", "ACTIVIDAD EPILEPTIFORME": "OTRO",
|
||||
},
|
||||
"eeg_distribucion_anormalidad": {
|
||||
"FOCAL": "FOCAL", "MULTIFOCAL": "MULTIFOCAL", "GENERALIZADA": "GENERALIZADA", "GENERALIZADAS": "GENERALIZADA",
|
||||
"DIFUSA": "GENERALIZADA", "BILATERAL Y SINCRONICA": "GENERALIZADA", "LATERALIZADA": "LATERALIZADA",
|
||||
"HEMISFERICA": "LATERALIZADA",
|
||||
},
|
||||
"eeg_lentificacion": {
|
||||
"LENTIFICACION FOCAL": "FOCAL", "LENTIFICACION GENERALIZADA": "GENERALIZADA", "LENTIFICACION DIFUSA": "GENERALIZADA",
|
||||
"LENTIFICACION INTERMITENTE": "INTERMITENTE", "ACTIVIDAD LENTA INTERMITENTE": "INTERMITENTE",
|
||||
},
|
||||
"eeg_crisis_registradas": {"CRISIS ELECTROGRAFICA": 1, "CRISIS ELECTROGRAFICAS": 1, "CRISIS ELECTROCLINICA": 1, "CRISIS ELECTROCLINICAS": 1, "SE REGISTRARON CRISIS": 1},
|
||||
"eeg_respuesta_fotoestimulacion": {
|
||||
"RESPUESTA FOTOPAROXISTICA": "RESPUESTA_FOTOPAROXISTICA", "FOTOPAROXISTICA": "RESPUESTA_FOTOPAROXISTICA",
|
||||
"ARRASTRE FOTICO": "NORMAL", "RESPUESTA DE ARRASTRE": "NORMAL", "FOTOESTIMULACION SIN CAMBIOS": "SIN_RESPUESTA",
|
||||
"SIN RESPUESTA A LA FOTOESTIMULACION": "SIN_RESPUESTA", "NO SE REALIZO FOTOESTIMULACION": "NO_PRACTICADA",
|
||||
"FOTOESTIMULACION NO REALIZADA": "NO_PRACTICADA",
|
||||
},
|
||||
"eeg_conclusion_categoria": {
|
||||
"NORMAL PARA LA EDAD": "NORMAL_PARA_LA_EDAD", "EEG NORMAL": "NORMAL_PARA_LA_EDAD", "DENTRO DE LIMITES NORMALES": "NORMAL_PARA_LA_EDAD",
|
||||
"NORMAL CON VARIANTES": "NORMAL_CON_VARIANTES", "VARIANTES NORMALES": "NORMAL_CON_VARIANTES",
|
||||
"ANORMAL EPILEPTIFORME": "ANORMAL_EPILEPTIFORME", "ANORMAL POR ACTIVIDAD EPILEPTIFORME": "ANORMAL_EPILEPTIFORME",
|
||||
"ANORMAL NO EPILEPTIFORME": "ANORMAL_NO_EPILEPTIFORME", "ANORMAL POR LENTIFICACION": "ANORMAL_NO_EPILEPTIFORME",
|
||||
"NO CONCLUYENTE": "NO_CONCLUYENTE",
|
||||
},
|
||||
"eeg_calidad_tecnica": {
|
||||
"TECNICAMENTE SATISFACTORIO": "SATISFACTORIA", "ADECUADA CALIDAD TECNICA": "SATISFACTORIA",
|
||||
"LIMITADO POR ARTEFACTO": "LIMITADA_POR_ARTEFACTO", "ARTEFACTO DE MOVIMIENTO": "LIMITADA_POR_ARTEFACTO",
|
||||
"POCA COOPERACION": "LIMITADA_POR_COLABORACION", "NO VALORABLE": "NO_VALORABLE",
|
||||
},
|
||||
})
|
||||
# Narrative BI-RADS: roman numerals, "categoría", subcategories.
|
||||
CLINICAL_TERMS["mast_birads"].update({
|
||||
**{f"BIRADS {n}": n for n in ("0", "1", "2", "3", "4", "4A", "4B", "4C", "5", "6")},
|
||||
**{f"{prefix} {roman}": n for prefix in ("BI-RADS", "BIRADS", "CATEGORIA") for roman, n in (("I", "1"), ("II", "2"), ("III", "3"), ("IV", "4"), ("IVA", "4A"), ("IVB", "4B"), ("IVC", "4C"), ("V", "5"), ("VI", "6"))},
|
||||
**{f"CATEGORIA {n}": n for n in ("0", "1", "2", "3", "4", "4A", "4B", "4C", "5", "6")},
|
||||
})
|
||||
# Cytology and histology in Bethesda (2014) and LAST (2012) terms.
|
||||
CLINICAL_TERMS["cit_celulas_escamosas"].update({
|
||||
"ASC-H": "ASC-H", "ASCH": "ASC-H", "ATIPIA EN CELULAS ESCAMOSAS DE SIGNIFICADO INDETERMINADO": "ASC-US",
|
||||
"CELULAS ESCAMOSAS ATIPICAS DE SIGNIFICADO INDETERMINADO": "ASC-US",
|
||||
"CELULAS ESCAMOSAS ATIPICAS SIN PODER EXCLUIR": "ASC-H", "NO SE PUEDE DESCARTAR LESION DE ALTO GRADO": "ASC-H",
|
||||
"LIEBG": "LIEBG", "LIEAG": "LIEAG", "LIE DE BAJO GRADO": "LIEBG", "LIE DE ALTO GRADO": "LIEAG",
|
||||
"DISPLASIA LEVE": "LIEBG", "DISPLASIA MODERADA": "LIEAG", "DISPLASIA GRAVE": "LIEAG", "DISPLASIA SEVERA": "LIEAG",
|
||||
"CARCINOMA IN SITU": "CIS", "NILM": "NORMAL",
|
||||
})
|
||||
CLINICAL_TERMS["bx_cin_grado"].update({
|
||||
"NIC1": "LIEBG", "NIC2": "LIEAG", "NIC3": "LIEAG", "CIN1": "LIEBG", "CIN2": "LIEAG", "CIN3": "LIEAG",
|
||||
"LIEBG": "LIEBG", "LIEAG": "LIEAG", "LIE DE BAJO GRADO": "LIEBG", "LIE DE ALTO GRADO": "LIEAG",
|
||||
"CONDILOMA": "LIEBG", "CAMBIOS POR VPH": "LIEBG", "EFECTO CITOPATICO VIRAL": "LIEBG",
|
||||
"DISPLASIA GRAVE": "LIEAG", "ADENOCARCINOMA IN SITU": "CIS",
|
||||
})
|
||||
CLINICAL_TERMS["bx_grado_histologico"].update({
|
||||
"CARCINOMA MAMARIO INVASOR": "CARCINOMA_INVASOR", "CARCINOMA DE TIPO NO ESPECIAL": "CARCINOMA_INVASOR",
|
||||
"CARCINOMA LOBULILLAR INVASOR": "CARCINOMA_INVASOR", "CARCINOMA MUCINOSO": "CARCINOMA_INVASOR",
|
||||
"CARCINOMA INTRADUCTAL": "CARCINOMA_IN_SITU", "LESION PAPILAR BENIGNA": "BENIGNO", "PAPILOMA INTRADUCTAL": "BENIGNO",
|
||||
"ADENOSIS ESCLEROSANTE": "BENIGNO", "MASTITIS": "BENIGNO", "SIN EVIDENCIA DE MALIGNIDAD": "BENIGNO",
|
||||
})
|
||||
LABELS["cit_fecha_reporte"] = (*LABELS["cit_fecha_reporte"], "fecha de interpretación", "fecha de emisión", "fecha de liberación")
|
||||
LABELS["bx_fecha_reporte"] = (*LABELS["bx_fecha_reporte"], "fecha de emisión", "fecha de liberación")
|
||||
LABELS["bx_cin_grado"] = (*LABELS["bx_cin_grado"], "diagnóstico final", "diagnóstico patológico")
|
||||
LABELS["eeg_ritmo_base_frecuencia"] = ("ritmo de fondo", "actividad de fondo", "ritmo base", "ritmo dominante posterior", "actividad basal")
|
||||
LABELS["eeg_ritmo_base_amplitud"] = ("amplitud", "voltaje")
|
||||
LABELS["eeg_duracion_min"] = ("duración del registro", "duración", "tiempo de registro")
|
||||
FREE_TEXT_FIELDS = FREE_TEXT_FIELDS | {
|
||||
"eeg_simetria", "eeg_anormalidad_presente", "eeg_actividad_epileptiforme", "eeg_tipo_grafoelemento",
|
||||
"eeg_distribucion_anormalidad", "eeg_lentificacion", "eeg_crisis_registradas", "eeg_respuesta_fotoestimulacion",
|
||||
"eeg_conclusion_categoria", "eeg_calidad_tecnica",
|
||||
}
|
||||
|
||||
@@ -7,10 +7,13 @@ import pytesseract
|
||||
from PIL import Image
|
||||
from pytesseract import Output
|
||||
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.document import BBox, Line, Word
|
||||
from extraction.errors import ExtractionError
|
||||
|
||||
DEFAULT_LANG = os.environ.get("EXTRACTION_OCR_LANG", "spa+eng")
|
||||
# Below this mean line confidence the page is tried again at the
|
||||
# orientation Tesseract's OSD detects, for pages scanned rotated.
|
||||
REORIENT_BELOW = 0.6
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -30,6 +33,16 @@ class TesseractOcr:
|
||||
return "tesseract"
|
||||
|
||||
def read_lines(self, image: Image.Image) -> list[Line]:
|
||||
lines = self._read(image)
|
||||
if self.psm != 3 or _mean_confidence(lines) >= REORIENT_BELOW:
|
||||
return lines
|
||||
rotation = _detected_rotation(image)
|
||||
if not rotation:
|
||||
return lines
|
||||
rotated = self._read(image.rotate(-rotation, expand=True))
|
||||
return rotated if _mean_confidence(rotated) > _mean_confidence(lines) else lines
|
||||
|
||||
def _read(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:
|
||||
@@ -38,6 +51,21 @@ class TesseractOcr:
|
||||
return [_line(words, width, height) for words in group_words(data)]
|
||||
|
||||
|
||||
def _mean_confidence(lines: list[Line]) -> float:
|
||||
weights = [len(line.text) for line in lines]
|
||||
total = sum(weights)
|
||||
return sum(line.confidence * weight for line, weight in zip(lines, weights)) / total if total else 0.0
|
||||
|
||||
|
||||
def _detected_rotation(image: Image.Image) -> int:
|
||||
"""Clockwise degrees the page is turned, per Tesseract's OSD; 0 when
|
||||
OSD can't tell (too little text, no `osd` traineddata)."""
|
||||
try:
|
||||
return int(pytesseract.image_to_osd(image, output_type=Output.DICT).get("rotate", 0)) % 360
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
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]] = {}
|
||||
@@ -71,4 +99,5 @@ def _line(words: list[dict], width: int, height: int) -> Line:
|
||||
text=" ".join(w["text"] for w in words),
|
||||
bbox=BBox(x0 / width, y0 / height, x1 / width, y1 / height),
|
||||
confidence=round(confidence, 4),
|
||||
words=tuple(Word(w["text"], w["left"] / width, (w["left"] + w["width"]) / width) for w in words),
|
||||
)
|
||||
|
||||
@@ -3,15 +3,23 @@ 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
|
||||
from extraction.readers.text import TextReader
|
||||
|
||||
READERS: tuple[type[DocumentReader], ...] = (PdfReader, ImageReader)
|
||||
# Tried only once neither a signature nor the file name picked one of
|
||||
# `READERS`: a SQL column or a plain string that isn't a PDF or an image,
|
||||
# read as text as long as it decodes as one instead of being rejected.
|
||||
FALLBACK_READERS: tuple[type[DocumentReader], ...] = (TextReader,)
|
||||
|
||||
|
||||
def reader_for(name: str, raw: bytes, **options) -> DocumentReader:
|
||||
"""The reader whose signature the bytes carry; the file extension only when none does."""
|
||||
"""The reader whose signature the bytes carry, the file extension when
|
||||
none does, and `FALLBACK_READERS` by content only when neither found one."""
|
||||
head = raw[:16]
|
||||
cls = next((c for c in READERS if c.matches_content(head)), None) or next(
|
||||
(c for c in READERS if c.matches_name(name)), None
|
||||
cls = (
|
||||
next((c for c in READERS if c.matches_content(head)), None)
|
||||
or next((c for c in READERS if c.matches_name(name)), None)
|
||||
or next((c for c in FALLBACK_READERS if c.matches_content(head)), None)
|
||||
)
|
||||
if cls is None:
|
||||
raise ExtractionError(f"unsupported document format: {name!r}")
|
||||
@@ -23,14 +31,16 @@ def read_document(name: str, raw: bytes, *, ocr_mode: OcrMode = "auto") -> Docum
|
||||
|
||||
|
||||
def supported_extensions() -> list[str]:
|
||||
return sorted({extension for cls in READERS for extension in cls.extensions})
|
||||
return sorted({extension for cls in (*READERS, *FALLBACK_READERS) for extension in cls.extensions})
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FALLBACK_READERS",
|
||||
"READERS",
|
||||
"DocumentReader",
|
||||
"ImageReader",
|
||||
"PdfReader",
|
||||
"TextReader",
|
||||
"combine_pages",
|
||||
"read_document",
|
||||
"reader_for",
|
||||
|
||||
@@ -3,13 +3,17 @@ import io
|
||||
import pdfplumber
|
||||
import pypdfium2 as pdfium
|
||||
|
||||
from extraction.document import BBox, Document, EmbeddedImage, Line, Page
|
||||
from extraction.document import BBox, Document, EmbeddedImage, Line, Page, Word
|
||||
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
|
||||
# A page that is mostly one scanned image is still OCRed unless its text
|
||||
# layer has at least this much: a scanner may stamp a header or a page
|
||||
# number as text over the image that holds the content.
|
||||
MIN_TEXT_CHARS_OVER_SCAN = 200
|
||||
# Images smaller than this fraction of the page are bullets, logos or rules.
|
||||
MIN_IMAGE_AREA = 0.01
|
||||
|
||||
@@ -42,7 +46,8 @@ class PdfReader(DocumentReader):
|
||||
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:
|
||||
enough = MIN_TEXT_CHARS_OVER_SCAN if any(image.kind == "scan" for image in images) else MIN_TEXT_CHARS
|
||||
if self.ocr_mode == "never" or sum(len(line.text) for line in lines) >= enough:
|
||||
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)
|
||||
@@ -71,19 +76,43 @@ def _open(raw: bytes):
|
||||
|
||||
|
||||
def _text_layer_lines(page) -> list[Line]:
|
||||
"""Some generators fake bold by drawing each glyph several times a
|
||||
fraction of a point apart, which reads as every letter repeated;
|
||||
`dedupe_chars` collapses those before the lines are built."""
|
||||
try:
|
||||
raw_lines = page.extract_text_lines()
|
||||
raw_lines = page.dedupe_chars().extract_text_lines(return_chars=True)
|
||||
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),
|
||||
lines = []
|
||||
for line in raw_lines:
|
||||
text = line.get("text", "").strip()
|
||||
if not text:
|
||||
continue
|
||||
words = _words(text, line.get("chars") or [], width)
|
||||
lines.append(
|
||||
Line(
|
||||
text=" ".join(word.text for word in words) if words else text,
|
||||
bbox=BBox(line["x0"] / width, line["top"] / height, line["x1"] / width, line["bottom"] / height),
|
||||
words=words,
|
||||
)
|
||||
)
|
||||
for line in raw_lines
|
||||
if line.get("text", "").strip()
|
||||
]
|
||||
return lines
|
||||
|
||||
|
||||
def _words(text: str, chars: list[dict], width: float) -> tuple[Word, ...]:
|
||||
"""The line's words with their extent, pairing each word of `text`
|
||||
with its glyphs in order; empty when the two don't line up."""
|
||||
glyphs = [char for char in chars if char.get("text", "").strip()]
|
||||
words: list[Word] = []
|
||||
position = 0
|
||||
for token in text.split():
|
||||
span = glyphs[position : position + len(token)]
|
||||
if len(span) != len(token):
|
||||
return ()
|
||||
words.append(Word(token, span[0]["x0"] / width, span[-1]["x1"] / width))
|
||||
position += len(token)
|
||||
return tuple(words) if position == len(glyphs) else ()
|
||||
|
||||
|
||||
def _embedded_images(page) -> list[EmbeddedImage]:
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import io
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from extraction.document import BBox, Document, Line, Page
|
||||
from extraction.errors import ExtractionError
|
||||
from extraction.readers.base import DocumentReader
|
||||
|
||||
_LINE_HEIGHT_PX = 18
|
||||
|
||||
|
||||
class TextReader(DocumentReader):
|
||||
"""Plain text, one field's content carrying several of its own (a SQL
|
||||
column that isn't a scanned PDF, a note pasted as a string). No OCR: the
|
||||
bytes already are the text, one page, one line per newline.
|
||||
|
||||
The fallback reader, last in `extraction.readers.READERS`: it claims
|
||||
whatever a format-specific reader didn't, as long as it decodes as
|
||||
text, so a source that's neither a PDF nor an image still reaches the
|
||||
same field extraction instead of failing as an unsupported format.
|
||||
"""
|
||||
|
||||
media_type = "text/plain"
|
||||
extensions = ("txt",)
|
||||
|
||||
@classmethod
|
||||
def matches_content(cls, head: bytes) -> bool:
|
||||
"""`head` is only a short prefix (`reader_for` passes 16 bytes), so
|
||||
a multi-byte character can be cut mid-sequence; trimming up to 3
|
||||
trailing bytes covers any such cut without accepting binary data.
|
||||
Printable (plus common whitespace) is required too, so a binary
|
||||
signature that happens to be valid UTF-8 (control bytes are) isn't
|
||||
mistaken for text."""
|
||||
if b"\x00" in head:
|
||||
return False
|
||||
text = None
|
||||
for cut in range(4):
|
||||
trimmed = head[: len(head) - cut] if cut else head
|
||||
if not trimmed:
|
||||
return False
|
||||
try:
|
||||
text = trimmed.decode("utf-8")
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return text is not None and all(ch.isprintable() or ch in "\t\n\r" for ch in text)
|
||||
|
||||
def read(self, name: str, raw: bytes) -> Document:
|
||||
try:
|
||||
text = raw.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise ExtractionError(f"not valid UTF-8 text: {exc}") from exc
|
||||
rows = text.splitlines() or [""]
|
||||
lines = [
|
||||
Line(text=row, bbox=BBox(0, index / len(rows), 1, (index + 1) / len(rows)))
|
||||
for index, row in enumerate(rows)
|
||||
]
|
||||
return Document(name=name, media_type=self.media_type, pages=[Page(number=1, lines=lines, source="text")], raw=raw)
|
||||
|
||||
def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes:
|
||||
if page_number != 1:
|
||||
raise ExtractionError(f"page {page_number} out of range (1..1)")
|
||||
rows = raw.decode("utf-8", errors="replace").splitlines() or [""]
|
||||
image = Image.new("RGB", (900, max(1, len(rows)) * _LINE_HEIGHT_PX + 20), "white")
|
||||
draw = ImageDraw.Draw(image)
|
||||
for index, row in enumerate(rows):
|
||||
draw.text((10, 10 + index * _LINE_HEIGHT_PX), row, fill="black")
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
@@ -1,17 +1,31 @@
|
||||
"""From documents to records: segment, extract every field per segment,
|
||||
then merge the partial records that belong to the same patient."""
|
||||
import re
|
||||
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.nlp.discovery import DiscoveredField, discover_captions
|
||||
from extraction.nlp.extractors import DEFAULT_EXTRACTORS, FieldExtractor, RecordExtractor, parse_value
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
|
||||
from extraction.nlp.text import ocr_fold
|
||||
from extraction.segmentation import AutoSegmenter, Segment, Segmenter, normalize_key
|
||||
from extraction.template import in_margin, normalized, template_lines
|
||||
|
||||
# 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
|
||||
|
||||
# A field sourced straight from a database column, not read off the page.
|
||||
# Above every built-in extractor's ceiling (0.95, `LabeledValueExtractor`'s
|
||||
# own), so it always wins a disagreement with a text-derived reading.
|
||||
SOURCE_FIELD_METHOD = "columna_fuente"
|
||||
SOURCE_FIELD_CONFIDENCE = 1.0
|
||||
|
||||
# What is left of a value's confidence when its document names another kind
|
||||
# of study (`foreign`) and not the target's (`subject`).
|
||||
OFF_TOPIC_FACTOR = 0.5
|
||||
|
||||
|
||||
@dataclass
|
||||
class SegmentRef:
|
||||
@@ -33,6 +47,20 @@ class ExtractedRecord:
|
||||
images: list[tuple[str, EmbeddedImage]] = field(default_factory=list)
|
||||
key: str | None = None
|
||||
conflicts: list[FieldConflict] = field(default_factory=list)
|
||||
# Captions no known `FieldSpec` claimed (`discover_captions`): what a
|
||||
# source outside today's vocabulary carries, for a caller to match
|
||||
# against a catalog or register as new (catalog_matching, in WebApi).
|
||||
discovered: list[DiscoveredField] = field(default_factory=list)
|
||||
# Every reading proposed per field, the chosen one included, for review
|
||||
# and for learning from corrections (`extraction.nlp.ranking`).
|
||||
candidates: dict[str, list[ExtractedValue]] = field(default_factory=dict)
|
||||
# Whether the record's pages are about what the target is: `True` when
|
||||
# they name it, `False` when they only name another kind of study,
|
||||
# `None` when they name neither or no subject was given.
|
||||
on_topic: bool | None = None
|
||||
# Values held back because their segment was off topic, restored if the
|
||||
# record it merges into turns out to be on topic.
|
||||
withheld: dict[str, ExtractedValue] = field(default_factory=dict)
|
||||
|
||||
def row(self) -> dict[str, Any]:
|
||||
return {name: extracted.value for name, extracted in self.values.items()}
|
||||
@@ -63,6 +91,11 @@ class RecordMerger:
|
||||
by_key[record.key] = target
|
||||
merged.append(target)
|
||||
self._absorb(target, record)
|
||||
for record in merged:
|
||||
if record.on_topic:
|
||||
for name, value in record.withheld.items():
|
||||
record.values.setdefault(name, value)
|
||||
record.withheld = {}
|
||||
return merged
|
||||
|
||||
@staticmethod
|
||||
@@ -70,6 +103,14 @@ class RecordMerger:
|
||||
target.sources.extend(record.sources)
|
||||
target.images.extend(record.images)
|
||||
target.conflicts.extend(record.conflicts)
|
||||
target.discovered.extend(record.discovered)
|
||||
for name, proposed in record.candidates.items():
|
||||
target.candidates.setdefault(name, []).extend(proposed)
|
||||
if record.on_topic is not None and target.on_topic is not True:
|
||||
target.on_topic = record.on_topic
|
||||
for name, value in record.withheld.items():
|
||||
if name not in target.withheld or value.confidence > target.withheld[name].confidence:
|
||||
target.withheld[name] = value
|
||||
for name, incoming in record.values.items():
|
||||
current = target.values.get(name)
|
||||
if current is None:
|
||||
@@ -90,7 +131,12 @@ class DocumentExtractor:
|
||||
|
||||
`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.
|
||||
the merge across pages and documents. `subject` names what the target
|
||||
is about and `foreign` what other targets are (`vocabulary.SUBJECTS`):
|
||||
a segment that names only a foreign subject is another kind of report,
|
||||
and fills nothing unless the record it merges into names the target's.
|
||||
`ranker` picks each field's value among its candidates
|
||||
(`extraction.nlp.ranking`).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -101,28 +147,133 @@ class DocumentExtractor:
|
||||
segmenter: Segmenter | None = None,
|
||||
extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS,
|
||||
merger: RecordMerger | None = RecordMerger(),
|
||||
subject: Sequence[str] = (),
|
||||
foreign: Sequence[str] = (),
|
||||
ranker=None,
|
||||
):
|
||||
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.fields = RecordExtractor(self.specs, extractors=extractors, ranker=ranker)
|
||||
self.merger = merger
|
||||
self.subject = _subject_pattern(subject)
|
||||
self.foreign = _subject_pattern(foreign)
|
||||
|
||||
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)]
|
||||
def extract(
|
||||
self,
|
||||
documents: Sequence[Document],
|
||||
*,
|
||||
source_fields: dict[str, dict[str, Any]] | None = None,
|
||||
record_keys: dict[str, str] | None = None,
|
||||
) -> list[ExtractedRecord]:
|
||||
"""`source_fields` carries, per document name, field values read
|
||||
straight from a structured column rather than the page (a SQL
|
||||
source's own patient or study id, say); they override whatever
|
||||
the text parses to for that field, on every segment of that
|
||||
document, including the key field itself.
|
||||
|
||||
`record_keys` names, per document, the record it belongs to (a
|
||||
study or order id from the source): documents sharing one merge
|
||||
into a single record, and documents that don't stay apart even
|
||||
when they share the key field."""
|
||||
segments = self.segments(documents)
|
||||
|
||||
def extract(segment: Segment, template: set[str] = frozenset()) -> ExtractedRecord:
|
||||
name = segment.document.name
|
||||
return self.extract_segment(segment, (source_fields or {}).get(name), (record_keys or {}).get(name), template=template)
|
||||
|
||||
records = [extract(segment) for segment in segments]
|
||||
# A second pass without the template lines the first one revealed:
|
||||
# an issuer's letterhead must not fill any patient's fields.
|
||||
template = template_lines((self._owner(record), segment.lines_only()) for segment, record in zip(segments, records))
|
||||
if template:
|
||||
records = [
|
||||
extract(segment, template) if any(normalized(line) in template for line in segment.lines_only()) else record
|
||||
for segment, record in zip(segments, records)
|
||||
]
|
||||
return self.merger.merge(records) if self.merger else records
|
||||
|
||||
def extract_segment(self, segment: Segment) -> ExtractedRecord:
|
||||
values = self.fields.extract(segment.lines())
|
||||
def _on_topic(self, lines) -> bool | None:
|
||||
texts = [line.ocr_folded for line in lines]
|
||||
if self.subject is not None and any(self.subject.search(text) for text in texts):
|
||||
return True
|
||||
if self.foreign is not None and any(self.foreign.search(text) for text in texts):
|
||||
return False
|
||||
return None
|
||||
|
||||
def _owner(self, record: ExtractedRecord) -> str | None:
|
||||
"""Whose document a record is: its key field's value, when known."""
|
||||
if self.key_spec is None or self.key_spec.name not in record.values:
|
||||
return None
|
||||
return normalize_key(record.values[self.key_spec.name].value)
|
||||
|
||||
def extract_segment(
|
||||
self,
|
||||
segment: Segment,
|
||||
source_fields: dict[str, Any] | None = None,
|
||||
record_key: str | None = None,
|
||||
*,
|
||||
template: set[str] = frozenset(),
|
||||
) -> ExtractedRecord:
|
||||
"""`template`: normalized texts of margin lines to read nothing from
|
||||
(`extraction.template`)."""
|
||||
lines = [line for line in segment.lines() if not (template and in_margin(line.line) and normalized(line.line) in template)]
|
||||
candidates = self.fields.candidates(lines)
|
||||
on_topic = self._on_topic(lines)
|
||||
if on_topic is not None:
|
||||
factor = 1.0 if on_topic else OFF_TOPIC_FACTOR
|
||||
candidates = {
|
||||
name: [c.with_confidence(c.confidence * factor, on_topic=on_topic) for c in proposed]
|
||||
for name, proposed in candidates.items()
|
||||
}
|
||||
values = self.fields.choose(candidates)
|
||||
withheld = {}
|
||||
if on_topic is False:
|
||||
unchecked = {name: [c.with_confidence(c.confidence, on_topic=None) for c in proposed] for name, proposed in candidates.items()}
|
||||
withheld = {name: value for name, value in self.fields.choose(unchecked).items() if name not in values}
|
||||
specs = {spec.name: spec for spec in self.specs}
|
||||
for name, raw_value in (source_fields or {}).items():
|
||||
if raw_value is None:
|
||||
continue
|
||||
values[name] = ExtractedValue(
|
||||
value=_source_value(specs.get(name), raw_value),
|
||||
confidence=SOURCE_FIELD_CONFIDENCE,
|
||||
method=SOURCE_FIELD_METHOD,
|
||||
raw=str(raw_value),
|
||||
evidence=Evidence(document=segment.document.name, page_number=segment.page_numbers[0] if segment.page_numbers else 0, line=f"columna {name}"),
|
||||
)
|
||||
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)
|
||||
if record_key is not None:
|
||||
key = normalize_key(str(record_key))
|
||||
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,
|
||||
discovered=discover_captions(lines, self.specs),
|
||||
candidates=candidates,
|
||||
on_topic=on_topic,
|
||||
withheld=withheld,
|
||||
)
|
||||
|
||||
|
||||
def _subject_pattern(terms: Sequence[str]) -> re.Pattern | None:
|
||||
stems = sorted({" ".join(re.findall(r"[A-Z0-9]+", ocr_fold(term))) for term in terms if term.strip()}, key=len, reverse=True)
|
||||
if not stems:
|
||||
return None
|
||||
body = "|".join(r"[\s.\-]*".join(re.escape(word) for word in stem.split()) for stem in stems)
|
||||
return re.compile(rf"(?<![A-Z0-9])(?:{body})")
|
||||
|
||||
|
||||
def _source_value(spec: FieldSpec | None, raw_value: Any) -> Any:
|
||||
"""A column's value typed like the field it fills, so a source's
|
||||
`datetime` or date string becomes a date and a number stays one."""
|
||||
if spec is None or spec.kind in (FieldKind.TEXT, FieldKind.IDENTIFIER):
|
||||
return str(raw_value)
|
||||
parsed = parse_value(spec, str(raw_value))
|
||||
return parsed.value if parsed is not None else str(raw_value)
|
||||
|
||||
@@ -8,7 +8,7 @@ from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import ClassVar
|
||||
|
||||
from extraction.document import Document, EmbeddedImage
|
||||
from extraction.document import Document, EmbeddedImage, Line
|
||||
from extraction.nlp.extractors import LabeledValueExtractor, LabelIndex, PatternExtractor, SegmentLine
|
||||
from extraction.nlp.fields import FieldSpec
|
||||
|
||||
@@ -23,11 +23,14 @@ class Segment:
|
||||
|
||||
def lines(self) -> list[SegmentLine]:
|
||||
return [
|
||||
SegmentLine(self.document.name, number, line)
|
||||
SegmentLine(self.document.name, number, line, self.document.page(number).source == "ocr")
|
||||
for number in self.page_numbers
|
||||
for line in self.document.page(number).lines
|
||||
]
|
||||
|
||||
def lines_only(self) -> list[Line]:
|
||||
return [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]
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Lines that belong to a document's template, not to its record.
|
||||
|
||||
A letterhead or a footer carries the issuer's own name, address, phone
|
||||
and postal code, printed the same on every document it issues. Read as
|
||||
fields, they would give every patient the issuer's address. A line counts
|
||||
as template when it sits in the page's top or bottom margin and repeats,
|
||||
give or take OCR noise, on the documents of at least two different
|
||||
patients; a header that repeats only across one patient's own pages or
|
||||
studies (her name, her file number) is hers and stays.
|
||||
"""
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from typing import Hashable, Iterable
|
||||
|
||||
from rapidfuzz import fuzz
|
||||
from rapidfuzz.process import cdist
|
||||
|
||||
from extraction.document import Line
|
||||
from extraction.nlp.text import fold
|
||||
|
||||
# Fraction of the page from the top and from the bottom treated as margins.
|
||||
HEADER_BAND = 0.16
|
||||
FOOTER_BAND = 0.12
|
||||
# Two margin lines are the same line when their digits are identical and
|
||||
# their normalized texts this similar (0..100): OCR rarely reads the same
|
||||
# letterhead twice identically, but a line whose numbers differ (an id, a
|
||||
# date) is a different line.
|
||||
SAME_LINE_SCORE = 94
|
||||
MIN_LINE_LENGTH = 8
|
||||
# Above this many distinct margin lines, only exact repeats are compared.
|
||||
MAX_FUZZY_LINES = 4000
|
||||
|
||||
|
||||
def in_margin(line: Line) -> bool:
|
||||
return line.bbox.y0 < HEADER_BAND or line.bbox.y1 > 1 - FOOTER_BAND
|
||||
|
||||
|
||||
def normalized(line: Line) -> str:
|
||||
return re.sub(r"[^A-Z0-9]", "", fold(line.text))
|
||||
|
||||
|
||||
def template_lines(lines_by_owner: Iterable[tuple[Hashable, Iterable[Line]]]) -> set[str]:
|
||||
"""The normalized texts of margin lines shared by two or more owners
|
||||
(patients). `lines_by_owner` pairs an owner with the lines of one of
|
||||
their documents or segments; owners that are `None` are skipped, since
|
||||
a line can't be told apart from its owner's data without knowing who
|
||||
the owner is."""
|
||||
owners: dict[str, set[Hashable]] = defaultdict(set)
|
||||
for owner, lines in lines_by_owner:
|
||||
if owner is None:
|
||||
continue
|
||||
for line in lines:
|
||||
text = normalized(line)
|
||||
if in_margin(line) and len(text) >= MIN_LINE_LENGTH:
|
||||
owners[text].add(owner)
|
||||
texts = list(owners)
|
||||
groups = _similar_groups(texts) if len(texts) <= MAX_FUZZY_LINES else [[i] for i in range(len(texts))]
|
||||
shared: set[str] = set()
|
||||
for group in groups:
|
||||
members = [texts[i] for i in group]
|
||||
if len(set().union(*(owners[text] for text in members))) >= 2:
|
||||
shared.update(members)
|
||||
return shared
|
||||
|
||||
|
||||
def _similar_groups(texts: list[str]) -> list[list[int]]:
|
||||
"""Indices of `texts` grouped by similarity (connected components),
|
||||
only ever joining texts with the same digits."""
|
||||
by_digits: dict[str, list[int]] = defaultdict(list)
|
||||
for i, text in enumerate(texts):
|
||||
by_digits[re.sub(r"\D", "", text)].append(i)
|
||||
groups: list[list[int]] = []
|
||||
for indices in by_digits.values():
|
||||
groups.extend([[indices[i] for i in group] for group in _components([texts[i] for i in indices])])
|
||||
return groups
|
||||
|
||||
|
||||
def _components(texts: list[str]) -> list[list[int]]:
|
||||
if len(texts) == 1:
|
||||
return [[0]]
|
||||
scores = cdist(texts, texts, scorer=fuzz.ratio, score_cutoff=SAME_LINE_SCORE, workers=-1)
|
||||
parent = list(range(len(texts)))
|
||||
|
||||
def root(i: int) -> int:
|
||||
while parent[i] != i:
|
||||
parent[i] = parent[parent[i]]
|
||||
i = parent[i]
|
||||
return i
|
||||
|
||||
for i, j in zip(*scores.nonzero()):
|
||||
if i < j:
|
||||
parent[root(i)] = root(j)
|
||||
components: dict[int, list[int]] = defaultdict(list)
|
||||
for i in range(len(texts)):
|
||||
components[root(i)].append(i)
|
||||
return list(components.values())
|
||||
@@ -6,8 +6,18 @@ 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)."""
|
||||
def text_pdf(
|
||||
pages: list[list[str | list[tuple[int, str]]]],
|
||||
*,
|
||||
image_on_page: int | None = None,
|
||||
overprint: int = 1,
|
||||
background_page: bytes | None = None,
|
||||
) -> bytes:
|
||||
"""One list of lines per page, typed (real text layer). A line may be
|
||||
a list of `(x, text)` cells, for layouts in columns. `overprint` draws
|
||||
every line that many times a fraction of a point apart, the way some
|
||||
generators fake bold. `background_page` (PNG or JPEG bytes) is drawn
|
||||
under the text over the whole page, like a scan with a stamped header."""
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
@@ -15,9 +25,14 @@ def text_pdf(pages: list[list[str]], *, image_on_page: int | None = None) -> byt
|
||||
buffer = io.BytesIO()
|
||||
pdf = canvas.Canvas(buffer, pagesize=letter)
|
||||
for number, lines in enumerate(pages, start=1):
|
||||
if background_page is not None:
|
||||
pdf.drawImage(ImageReader(io.BytesIO(background_page)), 0, 0, width=letter[0], height=letter[1])
|
||||
y = 740
|
||||
for line in lines:
|
||||
pdf.drawString(60, y, line)
|
||||
cells = [(60, line)] if isinstance(line, str) else line
|
||||
for x, text in cells:
|
||||
for copy in range(overprint):
|
||||
pdf.drawString(x + 0.25 * copy, y, text)
|
||||
y -= 20
|
||||
if image_on_page == number:
|
||||
picture = Image.new("RGB", (200, 150), (180, 60, 60))
|
||||
@@ -27,23 +42,28 @@ def text_pdf(pages: list[list[str]], *, image_on_page: int | None = None) -> byt
|
||||
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"))
|
||||
def scanned_pdf(pages: list[list[str]], *, rotate: int = 0) -> bytes:
|
||||
"""Same as `text_pdf` but every page is a picture of text — no text
|
||||
layer. `rotate` turns each picture that many degrees counterclockwise,
|
||||
like a sheet scanned sideways or upside down."""
|
||||
images = [page_image(lines).rotate(rotate, expand=True) for lines in pages]
|
||||
buffer = io.BytesIO()
|
||||
images[0].save(buffer, format="PDF", save_all=True, append_images=images[1:], resolution=150)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def page_image(lines: list[str]) -> Image.Image:
|
||||
"""A letter-size page at 150 dpi with the lines written on it."""
|
||||
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
|
||||
return image.convert("RGB")
|
||||
|
||||
|
||||
def _font(size: int):
|
||||
for path in ("/System/Library/Fonts/Supplemental/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"):
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""What a report says about a mention (`extraction.nlp.context`): denied,
|
||||
supposed, quoted from the clinical request or from history, asked as a
|
||||
form's caption, or affirmed; and which section of the report it sits in.
|
||||
|
||||
Fixtures: none; every line is written inline and folded with `fold`.
|
||||
"""
|
||||
from extraction.nlp.context import Assertion, Section, assess, heading_section, sections
|
||||
from extraction.nlp.text import fold
|
||||
|
||||
|
||||
def _assess(text: str, mention: str, section: Section = Section.GENERAL):
|
||||
folded = fold(text)
|
||||
start = folded.index(fold(mention))
|
||||
return assess(folded, start, start + len(mention), section)
|
||||
|
||||
|
||||
def test_a_trigger_before_the_mention_denies_it():
|
||||
"""Fails if pre-mention negation triggers ("sin evidencia de") stop applying."""
|
||||
assert _assess("Sin evidencia de displasia en los cortes examinados", "displasia").assertion is Assertion.NEGADO
|
||||
|
||||
|
||||
def test_a_form_answer_after_the_mention_denies_or_affirms_it():
|
||||
"""`Término: NO` denies, `Término: SI` affirms. Fails if post-mention
|
||||
answers stop being read, which would turn a form's "NO" into a finding."""
|
||||
assert _assess("Carcinoma invasor: NO", "Carcinoma invasor").assertion is Assertion.NEGADO
|
||||
assert _assess("Displasia: SI", "Displasia").assertion is Assertion.AFIRMADO
|
||||
|
||||
|
||||
def test_a_caption_with_its_answer_elsewhere_is_not_a_finding():
|
||||
"""A form row that only asks ("Carcinoma invasor:") with the answer in
|
||||
another cell says nothing yet. Fails if a caption is read as an
|
||||
affirmed mention."""
|
||||
context = _assess("Carcinoma invasor: Otro rubro:", "Carcinoma invasor")
|
||||
assert context.assertion is Assertion.HIPOTETICO
|
||||
|
||||
|
||||
def test_explanatory_text_is_hypothetical():
|
||||
"""Fails if conditional wording ("en caso de") stops marking a mention
|
||||
as hypothetical, so a printed recommendation would read as a result."""
|
||||
context = _assess("En caso de lesión de alto grado se sugiere colposcopía", "lesión de alto grado")
|
||||
assert context.assertion is Assertion.HIPOTETICO
|
||||
|
||||
|
||||
def test_a_terminator_ends_the_trigger_reach():
|
||||
"""A negation in a previous sentence does not reach the next one.
|
||||
Fails if clauses stop ending at a period."""
|
||||
assert _assess("No se tomó biopsia. Displasia moderada.", "Displasia moderada").assertion is Assertion.AFIRMADO
|
||||
|
||||
|
||||
def test_a_pseudo_trigger_does_not_negate():
|
||||
""""sin embargo" contains "sin" but negates nothing. Fails if pseudo
|
||||
triggers stop being masked."""
|
||||
assert _assess("Muestra escasa, sin embargo displasia leve evidente", "displasia leve").assertion is Assertion.AFIRMADO
|
||||
|
||||
|
||||
def test_a_caption_naming_a_clinical_section_makes_its_content_presumed():
|
||||
""""Diagnóstico de envío:" is what the requesting physician suspected.
|
||||
Fails if inline section captions stop qualifying what follows them."""
|
||||
context = _assess("Edad: 40. Diagnóstico de envío: NIC III.", "NIC III")
|
||||
assert (context.assertion, context.section) == (Assertion.PRESUNTIVO, Section.CLINICA)
|
||||
|
||||
|
||||
def test_standalone_headings_open_sections_and_captions_only_their_line():
|
||||
"""A heading alone on its line qualifies the lines under it; a caption
|
||||
followed by its content only its own line. Fails if a one-line caption
|
||||
("Método: PCR") swallows the rest of the report."""
|
||||
lines = [fold(t) for t in ("Método: PCR en tiempo real", "VPH: POSITIVO", "Valores de referencia", "Un positivo indica infección")]
|
||||
assert sections(lines) == [Section.REFERENCIA, Section.GENERAL, Section.REFERENCIA, Section.REFERENCIA]
|
||||
|
||||
|
||||
def test_the_longest_heading_names_the_section():
|
||||
""""Diagnóstico clínico" is clinical, "Diagnóstico" a result. Fails if
|
||||
the shorter heading wins."""
|
||||
assert heading_section(fold("Diagnóstico clínico:")) is Section.CLINICA
|
||||
assert heading_section(fold("Diagnóstico:")) is Section.RESULTADO
|
||||
|
||||
|
||||
def test_mentions_in_reference_text_are_hypothetical():
|
||||
"""Fails if a reference section stops qualifying its mentions."""
|
||||
assert _assess("Positivo indica ADN viral", "Positivo", Section.REFERENCIA).assertion is Assertion.HIPOTETICO
|
||||
@@ -0,0 +1,49 @@
|
||||
"""`discover_captions`: fails if it stops finding fields a source carries
|
||||
that no registered `FieldSpec` names, or starts re-reporting a field the
|
||||
specs already cover as if it were new."""
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.nlp import FieldKind, FieldSpec, SegmentLine, discover_captions
|
||||
|
||||
EXPEDIENTE = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
|
||||
|
||||
def lines(*texts: str) -> list[SegmentLine]:
|
||||
return [SegmentLine("doc.pdf", 1, Line(text, BBox(0, i / 10, 1, (i + 1) / 10))) for i, text in enumerate(texts)]
|
||||
|
||||
|
||||
def test_a_caption_outside_the_known_specs_is_discovered():
|
||||
found = discover_captions(lines("Tipo de muestra: Base líquida"), [EXPEDIENTE])
|
||||
assert [(f.caption, f.value) for f in found] == [("Tipo de muestra", "Base líquida")]
|
||||
|
||||
|
||||
def test_a_line_a_known_label_already_claims_is_not_rediscovered():
|
||||
found = discover_captions(lines("Expediente: EXP-0001"), [EXPEDIENTE])
|
||||
assert found == []
|
||||
|
||||
|
||||
def test_a_line_without_the_caption_shape_is_ignored():
|
||||
found = discover_captions(lines("Resultado negativo para lesión intraepitelial"), [EXPEDIENTE])
|
||||
assert found == []
|
||||
|
||||
|
||||
def test_several_undiscovered_captions_come_back_in_line_order():
|
||||
found = discover_captions(lines("Instrumento: ADOS-2", "Módulo: 3", "Expediente: EXP-0001"), [EXPEDIENTE])
|
||||
assert [(f.caption, f.value) for f in found] == [("Instrumento", "ADOS-2"), ("Módulo", "3")]
|
||||
|
||||
|
||||
def test_several_captions_on_one_line_are_each_discovered():
|
||||
"""`Nombre: ANA Edad: 52 Sexo: F` holds three captions, and an
|
||||
abbreviation or connector belongs to the caption it starts. Fails if
|
||||
`find_captions` reads one caption per line again, or cuts
|
||||
`Fecha de alta` down to its last word."""
|
||||
found = discover_captions(lines("Nombre: ANA RUIZ Edad: 52 Grupo: B", "Ingreso: 01/02/2020 Fecha de alta: 03/04/2020"), [EXPEDIENTE])
|
||||
assert [(f.caption, f.value) for f in found] == [
|
||||
("Nombre", "ANA RUIZ"), ("Edad", "52"), ("Grupo", "B"), ("Ingreso", "01/02/2020"), ("Fecha de alta", "03/04/2020")
|
||||
]
|
||||
|
||||
|
||||
def test_a_numbered_caption_is_discovered_without_its_number():
|
||||
"""`4.- Motivo de envío: control` yields the caption `Motivo de envío`.
|
||||
Fails if item numbers stop delimiting captions."""
|
||||
found = discover_captions(lines("4.- Motivo de envío: control anual"), [EXPEDIENTE])
|
||||
assert [(f.caption, f.value) for f in found] == [("Motivo de envío", "control anual")]
|
||||
@@ -4,7 +4,7 @@ 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 ImageReader, PdfReader, combine_pages, reader_for
|
||||
from extraction.readers import ImageReader, PdfReader, TextReader, combine_pages, reader_for
|
||||
|
||||
EXPEDIENTE = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
NACIMIENTO = FieldSpec("pac_fecha_nacimiento", FieldKind.DATE, labels=("fecha de nacimiento",))
|
||||
@@ -97,6 +97,21 @@ def test_unknown_format_is_rejected():
|
||||
reader_for("notes.docx", b"PK\x03\x04")
|
||||
|
||||
|
||||
def test_plain_text_is_read_as_a_one_page_document():
|
||||
"""Fails if a source whose field bundle is a plain string (not a PDF or
|
||||
an image) stops being readable, falling back to ExtractionError."""
|
||||
document = read_document("fila_42", "Expediente: EXP-0099\nInstrumento: ADOS-2".encode("utf-8"))
|
||||
assert isinstance(reader_for("fila_42", document.raw), TextReader)
|
||||
assert document.page_count == 1
|
||||
assert [line.text for line in document.pages[0].lines] == ["Expediente: EXP-0099", "Instrumento: ADOS-2"]
|
||||
|
||||
|
||||
def test_plain_text_fallback_does_not_steal_a_known_signature_or_extension():
|
||||
"""Fails if `TextReader` starts winning over a real PDF/image match."""
|
||||
assert isinstance(reader_for("reporte.pdf", b"????"), PdfReader)
|
||||
assert isinstance(reader_for("f.png", b"\x89PNG\r\n\x1a\n" + b"\x00" * 8), ImageReader)
|
||||
|
||||
|
||||
def test_combine_pages_from_several_pdfs():
|
||||
from extraction.readers import combine_pages
|
||||
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Reading documents whose layout is not one caption and value per line:
|
||||
forms laid out in columns, captions the vocabulary doesn't know, item
|
||||
numbers, abbreviated captions, overprinted text, pages that are mostly
|
||||
a scanned image, and letterheads that repeat across patients. Also how
|
||||
values handed over by a structured source key and group records.
|
||||
|
||||
Fixtures: none; every document is built inline with `text_pdf` or
|
||||
`scanned_pdf` from `extraction.testing`, and field specs are declared at
|
||||
module level below.
|
||||
"""
|
||||
import io
|
||||
from datetime import date
|
||||
|
||||
from extraction import DocumentExtractor, FieldKind, FieldSpec, read_document
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.nlp import RecordExtractor, SegmentLine
|
||||
from extraction.nlp.vocabulary import labels_for
|
||||
from extraction.testing import page_image, scanned_pdf, text_pdf
|
||||
|
||||
KEY = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
CALIDAD = FieldSpec("cit_calidad_especimen", FieldKind.TEXT, labels=("calidad de la muestra",))
|
||||
RESULTADO = FieldSpec(
|
||||
"cit_vph_resultado",
|
||||
FieldKind.CHOICE,
|
||||
labels=("resultado",),
|
||||
choices={"POSITIVO": "POSITIVO", "NEGATIVO": "NEGATIVO"},
|
||||
)
|
||||
REPORTE = FieldSpec("cit_fecha_reporte", FieldKind.DATE, labels=("fecha de reporte",))
|
||||
ORDEN = FieldSpec("ord_numero_hospital", FieldKind.INTEGER, labels=("orden",))
|
||||
NOTAS = FieldSpec("cit_observaciones", FieldKind.TEXT, labels=("observaciones",), multiline=True)
|
||||
SPECS = [KEY, CALIDAD, RESULTADO, REPORTE, ORDEN, NOTAS]
|
||||
|
||||
|
||||
def extract(raw: bytes) -> dict:
|
||||
[record] = DocumentExtractor(SPECS, key_field="pac_id_hospital", merger=None).extract([read_document("d.pdf", raw)])
|
||||
return record.row()
|
||||
|
||||
|
||||
def lines(*texts: str) -> list[SegmentLine]:
|
||||
return [SegmentLine("d.pdf", 1, Line(text, BBox(0, i / 40, 1, (i + 1) / 40))) for i, text in enumerate(texts)]
|
||||
|
||||
|
||||
def test_captions_in_columns_take_the_value_under_each():
|
||||
"""Two captions on one row with their values on the next row, each in
|
||||
its own column. Fails if a caption takes the whole next line instead
|
||||
of the words under it (`LabelIndex.column`)."""
|
||||
raw = text_pdf(
|
||||
[[
|
||||
"Expediente: A-1",
|
||||
[(60, "Calidad de la muestra:"), (320, "Resultado:")],
|
||||
[(60, "ADECUADA"), (320, "NEGATIVO")],
|
||||
]]
|
||||
)
|
||||
row = extract(raw)
|
||||
assert row["cit_calidad_especimen"] == "ADECUADA"
|
||||
assert row["cit_vph_resultado"] == "NEGATIVO"
|
||||
|
||||
|
||||
def test_item_numbers_belong_to_the_next_caption():
|
||||
"""`1.- Calidad de la muestra: 2.- Resultado:` must not read `2.-` as
|
||||
the first caption's value. Fails if item numbers stop being folded
|
||||
into the caption they precede (`_caption_start`)."""
|
||||
raw = text_pdf(
|
||||
[[
|
||||
"Expediente: A-2",
|
||||
[(60, "1.- Calidad de la muestra:"), (320, "2.- Resultado:")],
|
||||
[(60, "ADECUADA"), (320, "POSITIVO")],
|
||||
]]
|
||||
)
|
||||
row = extract(raw)
|
||||
assert row["cit_calidad_especimen"] == "ADECUADA"
|
||||
assert row["cit_vph_resultado"] == "POSITIVO"
|
||||
|
||||
|
||||
def test_an_unknown_caption_ends_the_value_before_it():
|
||||
"""A caption no field knows still marks where the previous value ends,
|
||||
both on the same line and on the lines below. Fails if only known
|
||||
labels bound a value (`_boundaries`)."""
|
||||
found = RecordExtractor([NOTAS]).extract(
|
||||
lines("Observaciones: sin cambios", "en el control", "Responsable de la toma: Persona X")
|
||||
)
|
||||
assert found["cit_observaciones"].value == "sin cambios en el control"
|
||||
|
||||
|
||||
def test_abbreviated_captions_and_left_out_connectors_match():
|
||||
"""`Fech. reporte` names the same field as `fecha de reporte`. Fails
|
||||
if `label_pattern` stops accepting abbreviations ending in a period or
|
||||
stops treating connector words as optional."""
|
||||
found = RecordExtractor([REPORTE]).extract(lines("Fech. reporte: 03/04/2025"))
|
||||
assert found["cit_fecha_reporte"].value == date(2025, 4, 3)
|
||||
|
||||
|
||||
def test_a_caption_may_run_on_before_its_colon():
|
||||
"""`Resultado obtenido en la prueba: POSITIVO` still reads the value
|
||||
after the colon. Fails if a known label followed by a few more words
|
||||
and a colon is no longer taken as a caption."""
|
||||
found = RecordExtractor([RESULTADO]).extract(lines("Resultado obtenido en la prueba: POSITIVO"))
|
||||
assert found["cit_vph_resultado"].value == "POSITIVO"
|
||||
|
||||
|
||||
def test_an_integer_field_does_not_read_a_date():
|
||||
"""`Orden: 12/03/2025` holds a date, not order number 12. Fails if
|
||||
`parse_value` reads the day of a date as an integer."""
|
||||
found = RecordExtractor([ORDEN]).extract(lines("Orden: 12/03/2025"))
|
||||
assert "ord_numero_hospital" not in found
|
||||
|
||||
|
||||
def test_schema_descriptions_become_captions_without_item_codes():
|
||||
"""A description such as `B7 Calidad de la toma: notas` yields the
|
||||
caption `Calidad de la toma`. Fails if `labels_for` keeps the leading
|
||||
item code or the explanation after the colon."""
|
||||
assert "Calidad de la toma" in labels_for("cit_calidad_especimen", "B7 Calidad de la toma: notas")
|
||||
|
||||
|
||||
def test_overprinted_text_is_read_once():
|
||||
"""Text drawn several times a fraction of a point apart (fake bold)
|
||||
reads as one copy. Fails if the PDF reader stops deduplicating
|
||||
glyphs (`dedupe_chars`)."""
|
||||
document = read_document("b.pdf", text_pdf([["Expediente: A-3", "Resultado: POSITIVO"]], overprint=3))
|
||||
assert "Resultado: POSITIVO" in document.pages[0].text
|
||||
|
||||
|
||||
def test_a_scan_under_a_thin_text_layer_is_ocred():
|
||||
"""A page that is a full-page image with only a short stamped text
|
||||
layer is OCRed, so the content in the image is read. Fails if a few
|
||||
characters of text layer are enough to skip OCR on a scanned page."""
|
||||
picture = io.BytesIO()
|
||||
page_image(["Expediente: A-4", "Resultado: NEGATIVO"]).save(picture, format="PNG")
|
||||
raw = text_pdf([["Hoja 1"]], background_page=picture.getvalue())
|
||||
document = read_document("h.pdf", raw)
|
||||
assert document.pages[0].source == "ocr"
|
||||
assert "NEGATIVO" in document.pages[0].text
|
||||
|
||||
|
||||
def test_a_page_scanned_upside_down_is_read_after_turning_it():
|
||||
"""OCR retries at the orientation Tesseract detects when the first
|
||||
reading is poor. Fails if `TesseractOcr.read_lines` stops retrying
|
||||
rotated pages."""
|
||||
lines_ = ["Expediente: A-5", "Resultado del estudio: NEGATIVO", "Observaciones: sin cambios en el control"] * 3
|
||||
document = read_document("r.pdf", scanned_pdf([lines_], rotate=180))
|
||||
assert "NEGATIVO" in document.pages[0].text
|
||||
|
||||
|
||||
def test_source_fields_key_records_and_outrank_the_text():
|
||||
"""A value handed over by a structured source keys the record and wins
|
||||
over what the page prints. Fails if `source_fields` stops reaching the
|
||||
key or loses to a text reading."""
|
||||
raw = text_pdf([["Expediente: OTRO-1", "Resultado: POSITIVO"]])
|
||||
[record] = DocumentExtractor(SPECS, key_field="pac_id_hospital").extract(
|
||||
[read_document("d.pdf", raw)], source_fields={"d.pdf": {"pac_id_hospital": "K-9", "ord_numero_hospital": "77"}}
|
||||
)
|
||||
assert record.key == "K-9"
|
||||
assert record.row()["ord_numero_hospital"] == 77
|
||||
|
||||
|
||||
def test_record_keys_group_documents_apart_from_the_key_field():
|
||||
"""Documents of one patient under two record keys stay two records;
|
||||
two documents under one record key merge. Fails if `record_keys` stops
|
||||
overriding the key field when records are merged."""
|
||||
first = read_document("a.pdf", text_pdf([["Expediente: P-1", "Resultado: POSITIVO"]]))
|
||||
second = read_document("b.pdf", text_pdf([["Expediente: P-1", "Calidad de la muestra: ADECUADA"]]))
|
||||
third = read_document("c.pdf", text_pdf([["Expediente: P-1", "Resultado: NEGATIVO"]]))
|
||||
records = DocumentExtractor(SPECS, key_field="pac_id_hospital").extract(
|
||||
[first, second, third], record_keys={"a.pdf": "O-1", "b.pdf": "O-1", "c.pdf": "O-2"}
|
||||
)
|
||||
by_key = {record.key: record.row() for record in records}
|
||||
assert set(by_key) == {"O-1", "O-2"}
|
||||
assert by_key["O-1"]["cit_calidad_especimen"] == "ADECUADA"
|
||||
assert by_key["O-2"]["cit_vph_resultado"] == "NEGATIVO"
|
||||
assert by_key["O-1"]["pac_id_hospital"] == "P-1"
|
||||
|
||||
|
||||
CP = FieldSpec("pac_codigo_postal", FieldKind.TEXT, labels=("cp", "c.p."), pattern=r"(?<!\d)\d{5}(?!\d)")
|
||||
NOMBRE = FieldSpec("cit_observaciones", FieldKind.TEXT, labels=("nombre",))
|
||||
LETTERHEAD = "Clinica Ejemplo, Av. Uno 100, Col. Centro CP: 12345"
|
||||
|
||||
|
||||
def test_an_issuers_letterhead_fills_no_patient_field():
|
||||
"""The same address line atop two different patients' reports is the
|
||||
issuer's, so its postal code is nobody's. Fails if margin lines shared
|
||||
across patients stop being treated as template (`template_lines`)."""
|
||||
first = read_document("a.pdf", text_pdf([[LETTERHEAD, "Expediente: A-10", "Resultado: POSITIVO"]]))
|
||||
second = read_document("b.pdf", text_pdf([[LETTERHEAD, "Expediente: A-11", "Resultado: NEGATIVO"]]))
|
||||
records = DocumentExtractor([KEY, CP, RESULTADO], key_field="pac_id_hospital").extract([first, second])
|
||||
assert {r.key for r in records} == {"A-10", "A-11"}
|
||||
assert all("pac_codigo_postal" not in r.row() for r in records)
|
||||
assert {r.row()["cit_vph_resultado"] for r in records} == {"POSITIVO", "NEGATIVO"}
|
||||
|
||||
|
||||
def test_a_letterhead_read_once_still_counts_when_alone():
|
||||
"""With a single patient there is nothing to compare against, so the
|
||||
line is read as usual. Fails if the template rule starts dropping
|
||||
lines without seeing them repeat across patients."""
|
||||
[record] = DocumentExtractor([KEY, CP], key_field="pac_id_hospital").extract(
|
||||
[read_document("a.pdf", text_pdf([[LETTERHEAD, "Expediente: A-12"]]))]
|
||||
)
|
||||
assert record.row()["pac_codigo_postal"] == "12345"
|
||||
|
||||
|
||||
def test_a_header_repeated_across_one_patients_documents_is_kept():
|
||||
"""A patient's own header (her name) printed atop each of her studies
|
||||
repeats only for her, so it is hers, not the template. Fails if lines
|
||||
repeated by a single owner are dropped."""
|
||||
header = "Nombre: ANA RUIZ PEREZ"
|
||||
first = read_document("a.pdf", text_pdf([[header, "Expediente: A-13", "Resultado: POSITIVO"]]))
|
||||
second = read_document("b.pdf", text_pdf([[header, "Expediente: A-13", "Resultado: POSITIVO"]]))
|
||||
other = read_document("c.pdf", text_pdf([["Nombre: LUISA GOMEZ", "Expediente: A-14"]]))
|
||||
records = DocumentExtractor([KEY, NOMBRE, RESULTADO], key_field="pac_id_hospital").extract([first, second, other])
|
||||
by_key = {r.key: r.row() for r in records}
|
||||
assert by_key["A-13"]["cit_observaciones"] == "ANA RUIZ PEREZ"
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Fields read from narrative text and from OCR: generic answers that need
|
||||
their concept next to them, the most severe of several findings, what a
|
||||
denied mention means for a presence field, measurements with units, OCR
|
||||
look-alike characters, date captions that name the time too, and text the
|
||||
report only supposes. Also the subject check that keeps one kind of report
|
||||
from filling another kind's fields.
|
||||
|
||||
Fixtures: none; field specs are declared at module level and lines and
|
||||
documents are built inline (`lines` below, `text_pdf` from
|
||||
`extraction.testing`).
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
from extraction import DocumentExtractor, FieldKind, FieldSpec, read_document
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.nlp import RecordExtractor, SegmentLine
|
||||
from extraction.segmentation import WholeDocument
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
VPH = FieldSpec(
|
||||
"cit_vph_resultado",
|
||||
FieldKind.CHOICE,
|
||||
labels=("resultado vph",),
|
||||
choices={"POSITIVO": "POSITIVO", "NEGATIVO": "NEGATIVO"},
|
||||
scan_free_text=True,
|
||||
anchors=("vph", "papiloma"),
|
||||
)
|
||||
GRADO = FieldSpec(
|
||||
"bx_cin_grado",
|
||||
FieldKind.CHOICE,
|
||||
labels=("diagnóstico",),
|
||||
choices={"NIC I": "LIEBG", "NIC II": "LIEAG", "NIC III": "LIEAG", "CARCINOMA INVASOR": "CARCINOMA"},
|
||||
scan_free_text=True,
|
||||
severity=("NORMAL", "LIEBG", "LIEAG", "CIS", "CARCINOMA"),
|
||||
)
|
||||
EPILEPTIFORME = FieldSpec(
|
||||
"eeg_actividad_epileptiforme",
|
||||
FieldKind.CHOICE,
|
||||
choices={"ACTIVIDAD EPILEPTIFORME": 1, "PUNTAS": 1},
|
||||
scan_free_text=True,
|
||||
negated_value=0,
|
||||
)
|
||||
FRECUENCIA = FieldSpec("eeg_ritmo_base_frecuencia", FieldKind.DECIMAL, anchors=("ritmo de fondo",), unit=r"HZ")
|
||||
AMPLITUD = FieldSpec("eeg_ritmo_base_amplitud", FieldKind.INTEGER, anchors=("amplitud",), unit=r"[µU]\s*V")
|
||||
EMISION = FieldSpec("bx_fecha_reporte", FieldKind.DATE, labels=("fecha de emisión",))
|
||||
|
||||
|
||||
def lines(*texts: str, ocr: bool = False) -> list[SegmentLine]:
|
||||
return [SegmentLine("doc.pdf", 1, Line(text, BBox(0, i / 40, 1, (i + 1) / 40)), ocr) for i, text in enumerate(texts)]
|
||||
|
||||
|
||||
def test_a_generic_answer_needs_its_concept():
|
||||
""""POSITIVO" alone says nothing about which test; after "VPH" it does.
|
||||
Fails if generic answers are taken without an anchor, which fills the
|
||||
HPV result from any positive line of a cytology form."""
|
||||
assert "cit_vph_resultado" not in RecordExtractor([VPH]).extract(lines("Diagnóstico para lesión: POSITIVO"))
|
||||
found = RecordExtractor([VPH]).extract(lines("Se detectó virus del papiloma humano de alto riesgo, positivo."))
|
||||
assert found["cit_vph_resultado"].value == "POSITIVO"
|
||||
|
||||
|
||||
def test_the_most_severe_affirmed_finding_wins():
|
||||
"""Two specimens, two grades: the worse one is the finding, wherever it
|
||||
is written. Fails if repetition or order outvotes severity."""
|
||||
found = RecordExtractor([GRADO]).extract(lines("Fragmento A: NIC III.", "Fragmento B: NIC I.", "Fragmento C: NIC I."))
|
||||
assert found["bx_cin_grado"].value == "LIEAG"
|
||||
|
||||
|
||||
def test_a_presumed_diagnosis_does_not_beat_the_final_one():
|
||||
"""The request's suspicion (clinical section) is not the study's result.
|
||||
Fails if a clinical caption's value outranks the diagnosis heading's."""
|
||||
found = RecordExtractor([GRADO]).extract(lines("Diagnóstico clínico: NIC III", "Diagnóstico:", "NIC I"))
|
||||
assert found["bx_cin_grado"].value == "LIEBG"
|
||||
|
||||
|
||||
def test_a_denied_presence_reads_as_absent():
|
||||
""""Sin actividad epileptiforme" means 0, not unknown. Fails if denied
|
||||
mentions of a presence field are dropped instead of read as its
|
||||
`negated_value`."""
|
||||
found = RecordExtractor([EPILEPTIFORME]).extract(lines("Trazo sin actividad epileptiforme durante el registro."))
|
||||
assert found["eeg_actividad_epileptiforme"].value == 0
|
||||
found = RecordExtractor([EPILEPTIFORME]).extract(lines("Se registran puntas en región temporal izquierda."))
|
||||
assert found["eeg_actividad_epileptiforme"].value == 1
|
||||
|
||||
|
||||
def test_measurements_with_units_after_their_concept():
|
||||
"""A range gives its midpoint; each unit fills its own field. Fails if
|
||||
`MeasurementExtractor` stops requiring the concept or mixes units."""
|
||||
found = RecordExtractor([FRECUENCIA, AMPLITUD]).extract(lines("Ritmo de fondo de 7 a 8 Hz con amplitud de 60 uV, reactivo."))
|
||||
assert found["eeg_ritmo_base_frecuencia"].value == 7.5
|
||||
assert found["eeg_ritmo_base_amplitud"].value == 60
|
||||
assert "eeg_ritmo_base_frecuencia" not in RecordExtractor([FRECUENCIA]).extract(lines("Fotoestimulación a 12 Hz sin cambios."))
|
||||
|
||||
|
||||
def test_ocr_look_alikes_still_match_captions_and_terms():
|
||||
"""`Dlagnóstico` and `NlC` are OCR misreads of `Diagnóstico` and `NIC`.
|
||||
Fails if OCR lines stop falling back to `ocr_fold`."""
|
||||
found = RecordExtractor([GRADO]).extract(lines("Dlagnóstlco: NlC II", ocr=True))
|
||||
assert found["bx_cin_grado"].value == "LIEAG"
|
||||
assert "bx_cin_grado" not in RecordExtractor([GRADO]).extract(lines("Dlagnóstlco: NlC II", ocr=False))
|
||||
|
||||
|
||||
def test_a_date_caption_may_name_the_time():
|
||||
"""Fails if `label_pattern` stops allowing "/hora" or "y hora" after "fecha"."""
|
||||
found = RecordExtractor([EMISION]).extract(lines("Fecha/hora de emisión: 03/02/2025 10:15 hrs."))
|
||||
assert found["bx_fecha_reporte"].value == date(2025, 2, 3)
|
||||
found = RecordExtractor([EMISION]).extract(lines("Fecha y hora de emisión: 4 de marzo de 2025"))
|
||||
assert found["bx_fecha_reporte"].value == date(2025, 3, 4)
|
||||
|
||||
|
||||
def test_reference_text_fills_nothing():
|
||||
"""Reference text printed under its heading describes no patient. Fails if mentions in a reference section can be chosen."""
|
||||
found = RecordExtractor([VPH]).extract(lines("Valores de referencia", "Un resultado de VPH positivo indica infección."))
|
||||
assert "cit_vph_resultado" not in found
|
||||
|
||||
|
||||
def test_every_candidate_is_kept_with_how_it_was_found():
|
||||
"""The ranker and the reviewer see all readings, with features but no
|
||||
document text in them. Fails if `RecordExtractor.candidates` drops the
|
||||
losers or features carry strings from the page."""
|
||||
candidates = RecordExtractor([GRADO]).candidates(lines("Diagnóstico: NIC I", "Se observa NIC II en otro fragmento."))
|
||||
values = {c.value for c in candidates["bx_cin_grado"]}
|
||||
assert values == {"LIEBG", "LIEAG"}
|
||||
for candidate in candidates["bx_cin_grado"]:
|
||||
assert {"assertion", "section", "rank", "agreeing"} <= set(candidate.features)
|
||||
assert all(not isinstance(v, str) or v.isidentifier() for v in candidate.features.values())
|
||||
|
||||
|
||||
BIOPSIA = text_pdf([["ESTUDIO HISTOPATOLÓGICO", "Biopsia cervical dirigida", "Diagnóstico:", "NIC I", "Fecha de emisión: 05/05/2025"]])
|
||||
SIN_TEMA = text_pdf([["Diagnóstico:", "NIC II", "Fecha de emisión: 06/06/2025"]])
|
||||
|
||||
|
||||
def _extractor(**options) -> DocumentExtractor:
|
||||
return DocumentExtractor([GRADO, EMISION], segmenter=WholeDocument(), merger=None, **options)
|
||||
|
||||
|
||||
def test_a_report_about_another_study_fills_nothing():
|
||||
"""A biopsy report fed to a cytology target names only a foreign
|
||||
subject. Fails if `foreign` stops gating its values."""
|
||||
document = read_document("biopsia.pdf", BIOPSIA)
|
||||
[record] = _extractor(subject=("citología",), foreign=("biopsia", "histopatológico")).extract([document])
|
||||
assert record.on_topic is False and record.values == {}
|
||||
[record] = _extractor(subject=("biopsia",), foreign=("citología",)).extract([document])
|
||||
assert record.on_topic is True and record.values["bx_cin_grado"].value == "LIEBG"
|
||||
|
||||
|
||||
def test_a_report_that_names_no_subject_is_not_gated():
|
||||
"""Only positive evidence of another kind of report gates. Fails if a
|
||||
report that names no study at all is treated as off topic."""
|
||||
[record] = _extractor(subject=("biopsia",), foreign=("citología",)).extract([read_document("x.pdf", SIN_TEMA)])
|
||||
assert record.on_topic is None and record.values["bx_cin_grado"].value == "LIEAG"
|
||||
|
||||
|
||||
def test_held_back_values_return_when_the_record_is_on_topic():
|
||||
"""A page that names only a foreign subject, merged by key with a page
|
||||
that names the target's, gives its values back. Fails if `withheld`
|
||||
values are lost in the merge."""
|
||||
key = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
pages = text_pdf([["Expediente: K-1", "Biopsia cervical dirigida", "Diagnóstico:", "NIC I"], ["Expediente: K-1", "Citología previa", "Fecha de emisión: 07/07/2025"]])
|
||||
extractor = DocumentExtractor([key, GRADO, EMISION], key_field="pac_id_hospital", subject=("biopsia",), foreign=("citología",))
|
||||
[record] = extractor.extract([read_document("k.pdf", pages)])
|
||||
assert record.on_topic is True
|
||||
assert record.values["bx_fecha_reporte"].value == date(2025, 7, 7)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Choosing among candidates and learning from corrections
|
||||
(`extraction.nlp.ranking`), and scoring extraction against an answer key
|
||||
(`extraction.nlp.evaluation`).
|
||||
|
||||
Fixtures: none; candidates are built inline by `candidate` below, with the
|
||||
features an extractor would give them.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
from extraction.document import BBox
|
||||
from extraction.nlp import FieldKind, FieldSpec
|
||||
from extraction.nlp.evaluation import evaluate
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue
|
||||
from extraction.nlp.ranking import TRUST_EXAMPLES, Example, HeuristicRanker, LearnedRanker, examples_for, features, same_value
|
||||
|
||||
GRADO = FieldSpec("bx_cin_grado", FieldKind.CHOICE, choices={"NIC I": "LIEBG", "NIC II": "LIEAG"})
|
||||
|
||||
|
||||
def candidate(value, confidence, method, **extra) -> ExtractedValue:
|
||||
evidence = Evidence("doc.pdf", 1, "línea", BBox(0, 0, 1, 0.1).as_list())
|
||||
return ExtractedValue(value, confidence, method, str(value), evidence, {"assertion": "afirmado", "section": "general", **extra})
|
||||
|
||||
|
||||
def test_the_heuristic_keeps_the_most_confident_and_respects_the_rules():
|
||||
"""Fails if a hypothetical mention or an off-topic document can fill a
|
||||
field without a trained ranker."""
|
||||
ranker = HeuristicRanker()
|
||||
assert ranker.choose(GRADO, [candidate("LIEBG", 0.4, "etiqueta"), candidate("LIEAG", 0.6, "texto_libre")]).value == "LIEAG"
|
||||
assert ranker.choose(GRADO, [candidate("LIEAG", 0.9, "texto_libre", assertion="hipotetico")]) is None
|
||||
assert ranker.choose(GRADO, [candidate("LIEAG", 0.9, "etiqueta", on_topic=False)]) is None
|
||||
|
||||
|
||||
def test_corrections_teach_the_ranker_to_prefer_what_was_right():
|
||||
"""People keep correcting the narrative reading to the labelled one;
|
||||
after enough corrections the ranker picks the label even though its
|
||||
confidence is lower. Fails if `learn` stops moving the weights toward
|
||||
the corrected candidates or `score` stops using them."""
|
||||
label, narrative = candidate("LIEBG", 0.5, "etiqueta"), candidate("LIEAG", 0.6, "texto_libre")
|
||||
ranker = LearnedRanker()
|
||||
assert ranker.choose(GRADO, [label, narrative]).value == "LIEAG"
|
||||
examples = examples_for([GRADO], {"bx_cin_grado": [label, narrative]}, {"bx_cin_grado": "LIEBG"})
|
||||
for _ in range(TRUST_EXAMPLES // len(examples) + 1):
|
||||
ranker.learn(examples)
|
||||
assert ranker.trust == 1.0
|
||||
assert ranker.choose(GRADO, [label, narrative]).value == "LIEBG"
|
||||
|
||||
|
||||
def test_the_rules_veto_holds_until_the_ranker_is_trusted():
|
||||
"""A ranker that has seen few examples can reorder what the rules allow
|
||||
but not revive what they rule out. Fails if a barely trained ranker
|
||||
can fill a field from a hypothetical mention."""
|
||||
hypothetical = candidate("LIEAG", 0.9, "texto_libre", assertion="hipotetico")
|
||||
ranker = LearnedRanker()
|
||||
ranker.learn([Example("bx_cin_grado", features(GRADO, hypothetical), True)] * 10)
|
||||
assert ranker.trust < 1.0 and ranker.choose(GRADO, [hypothetical]) is None
|
||||
|
||||
|
||||
def test_a_field_known_to_be_empty_makes_its_candidates_wrong():
|
||||
"""Fails if `examples_for` stops teaching that a field should stay empty,
|
||||
or starts learning from fields the truth leaves out."""
|
||||
examples = examples_for([GRADO], {"bx_cin_grado": [candidate("LIEAG", 0.6, "texto_libre")]}, {"bx_cin_grado": None})
|
||||
assert [e.label for e in examples] == [False]
|
||||
assert examples_for([GRADO], {"bx_cin_grado": [candidate("LIEAG", 0.6, "texto_libre")]}, {}) == []
|
||||
|
||||
|
||||
def test_the_ranker_survives_a_round_trip_and_holds_no_text():
|
||||
"""The stored state is weights over feature names. Fails if `to_dict`
|
||||
loses state or a feature name carries a candidate's value or raw text."""
|
||||
ranker = LearnedRanker()
|
||||
ranker.learn(examples_for([GRADO], {"bx_cin_grado": [candidate("LIEAG", 0.6, "texto_libre")]}, {"bx_cin_grado": "LIEAG"}))
|
||||
again = LearnedRanker.from_dict(ranker.to_dict())
|
||||
assert again.weights == ranker.weights and again.examples == ranker.examples
|
||||
assert not any("LIEAG" in name for name in ranker.weights)
|
||||
|
||||
|
||||
def test_values_compare_by_meaning():
|
||||
"""Dates by day, numbers by value, text without accents or case. Fails
|
||||
if a correction typed as text no longer matches the extracted value."""
|
||||
assert same_value(date(2025, 3, 4), "2025-03-04")
|
||||
assert same_value(0, "0") and same_value(7.5, 7.5)
|
||||
assert same_value("Lesión", "LESION")
|
||||
assert not same_value("LIEAG", "LIEBG") and not same_value(None, "x")
|
||||
|
||||
|
||||
def test_evaluation_counts_wrong_values_as_both_errors():
|
||||
"""A wrong value is a false positive and a false negative; a value where
|
||||
the key says empty a false positive. Fails if `evaluate` changes those
|
||||
conventions or puts values in errors when not asked to."""
|
||||
result = evaluate(
|
||||
{"a": {"f": "X", "g": "Y"}, "b": {"f": "Z"}},
|
||||
{"a": {"f": "X", "g": None}, "b": {"f": "W", "g": None}},
|
||||
)
|
||||
assert result.fields["f"].true_positives == 1 and result.fields["f"].false_negatives == 1
|
||||
assert result.fields["f"].false_positives == 1 and result.fields["g"].false_positives == 1
|
||||
assert result.fields["g"].true_negatives == 1
|
||||
assert result.overall.precision == 1 / 3
|
||||
assert result.to_dict()["errores"] == [{"documento": "a", "campo": "g"}, {"documento": "b", "campo": "f"}]
|
||||
@@ -11,7 +11,7 @@ CaCu, CaMa, TEA y gobernanza. El esquema está en `../Core`. Cambiar de motor
|
||||
| `repository.py` | `Repository`: `get`, `list`, `iter_all`, `count`, `create`, `bulk_upsert` (rechaza o actualiza por llave natural) y `open_session` para escribir varias tablas en una transacción. |
|
||||
| `identity.py` | Tras insertar ids explícitos, adelanta la secuencia en PostgreSQL (los demás motores lo hacen solos). |
|
||||
| `cacu/`, `cama/`, `tea/`, `governance/` | El ambiente de Alembic de cada base y una instancia de `Repository` por tabla (`persistance.cacu.paciente_repository`, ...). |
|
||||
| `aristas/`, `materializador.py` | Repositorios del ciclo de indicadores (`webapi.orquestacion`), por capa: bronce, plata y oro. |
|
||||
| `edges/`, `materializer.py` | Repositorios del ciclo de indicadores (`webapi.orchestration`), por capa: bronce, plata y oro. |
|
||||
|
||||
WebApi y `models` usan las mismas instancias de repositorio; no hay otra ruta
|
||||
a las tablas.
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
"""Oro: el registro (parámetros, periodos, definiciones), los reportes de indicadores y las cohortes con sus riesgos."""
|
||||
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.aristas.oro.calculo import CalculoRepository, MeasureReportRepository, guardar_reporte_en
|
||||
from persistance.aristas.oro.publicacion import PublicacionRepository, sincronizar_publicacion_en
|
||||
from persistance.aristas.oro.cohortes import (
|
||||
ERROR,
|
||||
FINAL,
|
||||
PRELIMINAR,
|
||||
PROCEDENCIA,
|
||||
CohortBuild,
|
||||
CohorteRepository,
|
||||
CohortMember,
|
||||
RiesgoFueraDeCohorte,
|
||||
cambiar_estado_en,
|
||||
guardar_armado_en,
|
||||
guardar_lote_en,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ERROR",
|
||||
"FINAL",
|
||||
"PRELIMINAR",
|
||||
"PROCEDENCIA",
|
||||
"CalculoRepository",
|
||||
"CohortBuild",
|
||||
"CohorteRepository",
|
||||
"CohortMember",
|
||||
"MeasureReportRepository",
|
||||
"PublicacionRepository",
|
||||
"RegistroRepository",
|
||||
"RiesgoFueraDeCohorte",
|
||||
"cambiar_estado_en",
|
||||
"guardar_armado_en",
|
||||
"guardar_lote_en",
|
||||
"guardar_reporte_en",
|
||||
"sincronizar_publicacion_en",
|
||||
]
|
||||
@@ -1,37 +0,0 @@
|
||||
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación, la verificación y la línea de tiempo."""
|
||||
|
||||
from persistance.aristas.plata.carga import (
|
||||
CargaRepository,
|
||||
abrir_carga,
|
||||
cerrar_carga,
|
||||
guardar_carga_en,
|
||||
)
|
||||
from persistance.aristas.plata.catalogos import CatalogoRepository
|
||||
from persistance.aristas.plata.observacion import ObservacionRepository
|
||||
from persistance.aristas.plata.procedimientos import guardar_plata_en
|
||||
from persistance.aristas.plata.timeline import (
|
||||
TIMELINE_COLUMNS,
|
||||
TimelineContractError,
|
||||
TimelineQuery,
|
||||
TimelineQueryMissing,
|
||||
TimelineRepository,
|
||||
)
|
||||
from persistance.aristas.plata.vinculos import VinculosRepository
|
||||
from persistance.aristas.plata.vistas import VistasRepository
|
||||
|
||||
__all__ = [
|
||||
"CargaRepository",
|
||||
"CatalogoRepository",
|
||||
"ObservacionRepository",
|
||||
"TIMELINE_COLUMNS",
|
||||
"TimelineContractError",
|
||||
"TimelineQuery",
|
||||
"TimelineQueryMissing",
|
||||
"TimelineRepository",
|
||||
"VinculosRepository",
|
||||
"VistasRepository",
|
||||
"abrir_carga",
|
||||
"cerrar_carga",
|
||||
"guardar_carga_en",
|
||||
"guardar_plata_en",
|
||||
]
|
||||
@@ -13,14 +13,14 @@ from enum import StrEnum
|
||||
|
||||
|
||||
class Layer(StrEnum):
|
||||
BRONZE = "bronce"
|
||||
SILVER = "plata"
|
||||
GOLD = "oro"
|
||||
MODEL = "modelo"
|
||||
BRONZE = "bronze"
|
||||
SILVER = "silver"
|
||||
GOLD = "gold"
|
||||
MODEL = "model"
|
||||
|
||||
|
||||
class Owner(StrEnum):
|
||||
EXTERNAL = "externo"
|
||||
EXTERNAL = "external"
|
||||
PYTHON = "python"
|
||||
DBT = "dbt"
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@ from core.cacu.indicadores.models import (
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CatEstudio,
|
||||
CatMapeo,
|
||||
CatResultado,
|
||||
CatSistemaFuente,
|
||||
CatValor,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
@@ -40,18 +42,25 @@ from core.cacu.models import (
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
from persistance.edges.bronze import StagingRepository
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.edges.common import ReferenceRepository
|
||||
from persistance.materializer import Materializer
|
||||
from persistance.edges.gold import (
|
||||
CalculationRepository,
|
||||
CohortRepository,
|
||||
MeasureHistoryRepository,
|
||||
MeasureReportRepository,
|
||||
PublicationRepository,
|
||||
)
|
||||
from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
SourceMappingRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.db import get_cacu_session
|
||||
from persistance.repository import Repository
|
||||
@@ -65,23 +74,23 @@ biometria_hematica_repository = Repository(get_cacu_session, BiometriaHematica)
|
||||
episodio_clinico_repository = Repository(get_cacu_session, EpisodioClinico)
|
||||
|
||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
||||
persona_repository = Repository(get_cacu_session, Persona)
|
||||
periodo_observacion_repository = RegistroRepository(get_cacu_session, PeriodoObservacion)
|
||||
carga_repository = CargaRepository(get_cacu_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = RegistroRepository(get_cacu_session, DefParametro)
|
||||
dim_periodo_repository = RegistroRepository(get_cacu_session, DimPeriodo)
|
||||
dim_fecha_repository = RegistroRepository(get_cacu_session, DimFecha)
|
||||
dim_grupo_edad_repository = RegistroRepository(get_cacu_session, DimGrupoEdad)
|
||||
periodo_observacion_repository = ReferenceRepository(get_cacu_session, PeriodoObservacion)
|
||||
carga_repository = LoadRepository(get_cacu_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = ReferenceRepository(get_cacu_session, DefParametro)
|
||||
dim_periodo_repository = ReferenceRepository(get_cacu_session, DimPeriodo)
|
||||
dim_fecha_repository = ReferenceRepository(get_cacu_session, DimFecha)
|
||||
dim_grupo_edad_repository = ReferenceRepository(get_cacu_session, DimGrupoEdad)
|
||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||
cat_measure_repository = RegistroRepository(get_cacu_session, CatMeasure)
|
||||
cat_measure_resultado_repository = RegistroRepository(get_cacu_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = RegistroRepository(get_cacu_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = RegistroRepository(get_cacu_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = RegistroRepository(get_cacu_session, CatEstrato)
|
||||
cat_estrato_valor_repository = RegistroRepository(get_cacu_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = RegistroRepository(get_cacu_session, CatMeasureEstrato)
|
||||
publicacion_repository = PublicacionRepository(
|
||||
cat_measure_repository = ReferenceRepository(get_cacu_session, CatMeasure)
|
||||
cat_measure_resultado_repository = ReferenceRepository(get_cacu_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = ReferenceRepository(get_cacu_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = ReferenceRepository(get_cacu_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = ReferenceRepository(get_cacu_session, CatEstrato)
|
||||
cat_estrato_valor_repository = ReferenceRepository(get_cacu_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = ReferenceRepository(get_cacu_session, CatMeasureEstrato)
|
||||
publication_repository = PublicationRepository(
|
||||
get_cacu_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||
)
|
||||
measure_report_unidad_repository = Repository(get_cacu_session, MeasureReportUnidad)
|
||||
@@ -93,20 +102,24 @@ cat_valor_repository = Repository(get_cacu_session, CatValor)
|
||||
procedimiento_repository = Repository(get_cacu_session, Procedimiento)
|
||||
observacion_repository = Repository(get_cacu_session, Observacion)
|
||||
|
||||
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(get_cacu_session)
|
||||
catalogo_repository = CatalogoRepository(get_cacu_session, CatEstudio, CatResultado, CatValor)
|
||||
calculo_repository = CalculoRepository(get_cacu_session, MeasureReport, periodo=DimPeriodo)
|
||||
observar_repository = ObservacionRepository(get_cacu_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_cacu_session)
|
||||
vinculos_repository = VinculosRepository(get_cacu_session)
|
||||
catalog_repository = CatalogRepository(get_cacu_session, CatEstudio, CatResultado, CatValor)
|
||||
source_mapping_repository = SourceMappingRepository(get_cacu_session, CatSistemaFuente, CatMapeo)
|
||||
calculation_repository = CalculationRepository(get_cacu_session, MeasureReport, periodo=DimPeriodo)
|
||||
history_repository = MeasureHistoryRepository(get_cacu_session, MeasureReport, unit_model=MeasureReportUnidad,
|
||||
stratum_model=MeasureReportUnidadEstrato,
|
||||
value_model=CatEstratoValor)
|
||||
observation_period_repository = ObservationRepository(get_cacu_session, PeriodoObservacion)
|
||||
views_repository = ViewsRepository(get_cacu_session)
|
||||
links_repository = LinksRepository(get_cacu_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_cacu_session, "cacu")
|
||||
dbt_query_repository = DbtQueryRepository(get_cacu_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
cohort_repository = CohortRepository(
|
||||
get_cacu_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
)
|
||||
|
||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||
materializador = Materializador(get_cacu_session)
|
||||
materializer = Materializer(get_cacu_session)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""source terminology
|
||||
|
||||
`cat_sistema_fuente` (who sends the data) and `cat_mapeo` (how each source writes the catalog's codes). Both start
|
||||
empty; the `catalogs` step seeds the catalog's own mappings, and the application adds the rest.
|
||||
|
||||
Revision ID: f89e1f081998
|
||||
Revises: b4f2d8c01e23
|
||||
Create Date: 2026-11-13 18:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
import core.indicadores.tipos
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'f89e1f081998'
|
||||
down_revision = 'b4f2d8c01e23'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('cat_sistema_fuente',
|
||||
sa.Column('sistema_fuente_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('etiqueta', sa.String(), nullable=False),
|
||||
sa.Column('fuente_tabla', sa.String(length=64), nullable=True),
|
||||
sa.Column('vigente_desde', sa.Date(), nullable=False),
|
||||
sa.Column('vigente_hasta', sa.Date(), nullable=True),
|
||||
sa.CheckConstraint('vigente_hasta IS NULL OR vigente_hasta >= vigente_desde', name='ck_cat_sistema_fuente_vigencia'),
|
||||
sa.PrimaryKeyConstraint('sistema_fuente_id')
|
||||
)
|
||||
op.create_table('cat_mapeo',
|
||||
sa.Column('mapeo_id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('sistema_fuente_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('clase', sa.String(length=16), nullable=False),
|
||||
sa.Column('forma', sa.String(length=255), nullable=False),
|
||||
sa.Column('forma_normalizada', sa.String(length=255), nullable=False),
|
||||
sa.Column('estudio_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('resultado_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('valor_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('vigente_desde', sa.Date(), nullable=False),
|
||||
sa.Column('vigente_hasta', sa.Date(), nullable=True),
|
||||
sa.Column('registrado_por', sa.String(length=64), nullable=False),
|
||||
sa.Column('registrado_en', core.indicadores.tipos.FechaHoraUTC(), nullable=False),
|
||||
sa.Column('motivo', sa.String(), nullable=True),
|
||||
sa.CheckConstraint("clase IN ('estudio', 'etiqueta', 'valor')", name='ck_cat_mapeo_clase'),
|
||||
sa.CheckConstraint("(clase = 'estudio' AND estudio_id IS NOT NULL AND resultado_id IS NULL AND valor_id IS NULL)"
|
||||
" OR (clase = 'etiqueta' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NULL)"
|
||||
" OR (clase = 'valor' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NOT NULL)",
|
||||
name='ck_cat_mapeo_destino'),
|
||||
sa.CheckConstraint('vigente_hasta IS NULL OR vigente_hasta >= vigente_desde', name='ck_cat_mapeo_vigencia'),
|
||||
sa.ForeignKeyConstraint(['sistema_fuente_id'], ['cat_sistema_fuente.sistema_fuente_id'], ),
|
||||
sa.ForeignKeyConstraint(['estudio_id'], ['cat_estudio.estudio_id'], ),
|
||||
sa.ForeignKeyConstraint(['resultado_id'], ['cat_resultado.resultado_id'], ),
|
||||
sa.ForeignKeyConstraint(['resultado_id', 'valor_id'], ['cat_valor.resultado_id', 'cat_valor.valor_id'], name='fk_cat_mapeo_valor'),
|
||||
sa.PrimaryKeyConstraint('mapeo_id'),
|
||||
sa.UniqueConstraint('sistema_fuente_id', 'clase', 'resultado_id', 'estudio_id', 'forma_normalizada', 'vigente_desde', name='uq_cat_mapeo')
|
||||
)
|
||||
op.create_index('ix_cat_mapeo_busqueda', 'cat_mapeo', ['sistema_fuente_id', 'resultado_id', 'forma_normalizada'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index('ix_cat_mapeo_busqueda', table_name='cat_mapeo')
|
||||
op.drop_table('cat_mapeo')
|
||||
op.drop_table('cat_sistema_fuente')
|
||||
@@ -2,7 +2,9 @@ from core.cama.indicadores.models import (
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CatEstudio,
|
||||
CatMapeo,
|
||||
CatResultado,
|
||||
CatSistemaFuente,
|
||||
CatValor,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
@@ -40,18 +42,25 @@ from core.cama.models import (
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
from persistance.edges.bronze import StagingRepository
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.edges.common import ReferenceRepository
|
||||
from persistance.materializer import Materializer
|
||||
from persistance.edges.gold import (
|
||||
CalculationRepository,
|
||||
CohortRepository,
|
||||
MeasureHistoryRepository,
|
||||
MeasureReportRepository,
|
||||
PublicationRepository,
|
||||
)
|
||||
from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
SourceMappingRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.db import get_cama_session
|
||||
from persistance.repository import Repository
|
||||
@@ -65,23 +74,23 @@ biometria_hematica_repository = Repository(get_cama_session, BiometriaHematica)
|
||||
episodio_clinico_repository = Repository(get_cama_session, EpisodioClinico)
|
||||
|
||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
||||
persona_repository = Repository(get_cama_session, Persona)
|
||||
periodo_observacion_repository = RegistroRepository(get_cama_session, PeriodoObservacion)
|
||||
carga_repository = CargaRepository(get_cama_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = RegistroRepository(get_cama_session, DefParametro)
|
||||
dim_periodo_repository = RegistroRepository(get_cama_session, DimPeriodo)
|
||||
dim_fecha_repository = RegistroRepository(get_cama_session, DimFecha)
|
||||
dim_grupo_edad_repository = RegistroRepository(get_cama_session, DimGrupoEdad)
|
||||
periodo_observacion_repository = ReferenceRepository(get_cama_session, PeriodoObservacion)
|
||||
carga_repository = LoadRepository(get_cama_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = ReferenceRepository(get_cama_session, DefParametro)
|
||||
dim_periodo_repository = ReferenceRepository(get_cama_session, DimPeriodo)
|
||||
dim_fecha_repository = ReferenceRepository(get_cama_session, DimFecha)
|
||||
dim_grupo_edad_repository = ReferenceRepository(get_cama_session, DimGrupoEdad)
|
||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||
cat_measure_repository = RegistroRepository(get_cama_session, CatMeasure)
|
||||
cat_measure_resultado_repository = RegistroRepository(get_cama_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = RegistroRepository(get_cama_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = RegistroRepository(get_cama_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = RegistroRepository(get_cama_session, CatEstrato)
|
||||
cat_estrato_valor_repository = RegistroRepository(get_cama_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = RegistroRepository(get_cama_session, CatMeasureEstrato)
|
||||
publicacion_repository = PublicacionRepository(
|
||||
cat_measure_repository = ReferenceRepository(get_cama_session, CatMeasure)
|
||||
cat_measure_resultado_repository = ReferenceRepository(get_cama_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = ReferenceRepository(get_cama_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = ReferenceRepository(get_cama_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = ReferenceRepository(get_cama_session, CatEstrato)
|
||||
cat_estrato_valor_repository = ReferenceRepository(get_cama_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = ReferenceRepository(get_cama_session, CatMeasureEstrato)
|
||||
publication_repository = PublicationRepository(
|
||||
get_cama_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||
)
|
||||
measure_report_unidad_repository = Repository(get_cama_session, MeasureReportUnidad)
|
||||
@@ -93,20 +102,24 @@ cat_valor_repository = Repository(get_cama_session, CatValor)
|
||||
procedimiento_repository = Repository(get_cama_session, Procedimiento)
|
||||
observacion_repository = Repository(get_cama_session, Observacion)
|
||||
|
||||
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(get_cama_session)
|
||||
catalogo_repository = CatalogoRepository(get_cama_session, CatEstudio, CatResultado, CatValor)
|
||||
calculo_repository = CalculoRepository(get_cama_session, MeasureReport, periodo=DimPeriodo)
|
||||
observar_repository = ObservacionRepository(get_cama_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_cama_session)
|
||||
vinculos_repository = VinculosRepository(get_cama_session)
|
||||
catalog_repository = CatalogRepository(get_cama_session, CatEstudio, CatResultado, CatValor)
|
||||
source_mapping_repository = SourceMappingRepository(get_cama_session, CatSistemaFuente, CatMapeo)
|
||||
calculation_repository = CalculationRepository(get_cama_session, MeasureReport, periodo=DimPeriodo)
|
||||
history_repository = MeasureHistoryRepository(get_cama_session, MeasureReport, unit_model=MeasureReportUnidad,
|
||||
stratum_model=MeasureReportUnidadEstrato,
|
||||
value_model=CatEstratoValor)
|
||||
observation_period_repository = ObservationRepository(get_cama_session, PeriodoObservacion)
|
||||
views_repository = ViewsRepository(get_cama_session)
|
||||
links_repository = LinksRepository(get_cama_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_cama_session, "cama")
|
||||
dbt_query_repository = DbtQueryRepository(get_cama_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
cohort_repository = CohortRepository(
|
||||
get_cama_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
)
|
||||
|
||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||
materializador = Materializador(get_cama_session)
|
||||
materializer = Materializer(get_cama_session)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""source terminology
|
||||
|
||||
`cat_sistema_fuente` (who sends the data) and `cat_mapeo` (how each source writes the catalog's codes). Both start
|
||||
empty; the `catalogs` step seeds the catalog's own mappings, and the application adds the rest.
|
||||
|
||||
Revision ID: f82b64f43abd
|
||||
Revises: c5a3e9d12f34
|
||||
Create Date: 2026-11-13 18:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
import core.indicadores.tipos
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'f82b64f43abd'
|
||||
down_revision = 'c5a3e9d12f34'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('cat_sistema_fuente',
|
||||
sa.Column('sistema_fuente_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('etiqueta', sa.String(), nullable=False),
|
||||
sa.Column('fuente_tabla', sa.String(length=64), nullable=True),
|
||||
sa.Column('vigente_desde', sa.Date(), nullable=False),
|
||||
sa.Column('vigente_hasta', sa.Date(), nullable=True),
|
||||
sa.CheckConstraint('vigente_hasta IS NULL OR vigente_hasta >= vigente_desde', name='ck_cat_sistema_fuente_vigencia'),
|
||||
sa.PrimaryKeyConstraint('sistema_fuente_id')
|
||||
)
|
||||
op.create_table('cat_mapeo',
|
||||
sa.Column('mapeo_id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('sistema_fuente_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('clase', sa.String(length=16), nullable=False),
|
||||
sa.Column('forma', sa.String(length=255), nullable=False),
|
||||
sa.Column('forma_normalizada', sa.String(length=255), nullable=False),
|
||||
sa.Column('estudio_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('resultado_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('valor_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('vigente_desde', sa.Date(), nullable=False),
|
||||
sa.Column('vigente_hasta', sa.Date(), nullable=True),
|
||||
sa.Column('registrado_por', sa.String(length=64), nullable=False),
|
||||
sa.Column('registrado_en', core.indicadores.tipos.FechaHoraUTC(), nullable=False),
|
||||
sa.Column('motivo', sa.String(), nullable=True),
|
||||
sa.CheckConstraint("clase IN ('estudio', 'etiqueta', 'valor')", name='ck_cat_mapeo_clase'),
|
||||
sa.CheckConstraint("(clase = 'estudio' AND estudio_id IS NOT NULL AND resultado_id IS NULL AND valor_id IS NULL)"
|
||||
" OR (clase = 'etiqueta' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NULL)"
|
||||
" OR (clase = 'valor' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NOT NULL)",
|
||||
name='ck_cat_mapeo_destino'),
|
||||
sa.CheckConstraint('vigente_hasta IS NULL OR vigente_hasta >= vigente_desde', name='ck_cat_mapeo_vigencia'),
|
||||
sa.ForeignKeyConstraint(['sistema_fuente_id'], ['cat_sistema_fuente.sistema_fuente_id'], ),
|
||||
sa.ForeignKeyConstraint(['estudio_id'], ['cat_estudio.estudio_id'], ),
|
||||
sa.ForeignKeyConstraint(['resultado_id'], ['cat_resultado.resultado_id'], ),
|
||||
sa.ForeignKeyConstraint(['resultado_id', 'valor_id'], ['cat_valor.resultado_id', 'cat_valor.valor_id'], name='fk_cat_mapeo_valor'),
|
||||
sa.PrimaryKeyConstraint('mapeo_id'),
|
||||
sa.UniqueConstraint('sistema_fuente_id', 'clase', 'resultado_id', 'estudio_id', 'forma_normalizada', 'vigente_desde', name='uq_cat_mapeo')
|
||||
)
|
||||
op.create_index('ix_cat_mapeo_busqueda', 'cat_mapeo', ['sistema_fuente_id', 'resultado_id', 'forma_normalizada'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index('ix_cat_mapeo_busqueda', table_name='cat_mapeo')
|
||||
op.drop_table('cat_mapeo')
|
||||
op.drop_table('cat_sistema_fuente')
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
"""Bronce: el staging, como lo deja la ingesta. Aquí solo se lee."""
|
||||
|
||||
from persistance.aristas.bronce.staging import StagingRepository
|
||||
from persistance.edges.bronze.staging import StagingRepository
|
||||
|
||||
__all__ = ["StagingRepository"]
|
||||
+1
-1
@@ -18,7 +18,7 @@ class StagingRepository(Repository):
|
||||
def __init__(self, session_factory):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def leer(self, modelos: Mapping[str, type[SQLModel]]) -> dict[str, list]:
|
||||
def read(self, modelos: Mapping[str, type[SQLModel]]) -> dict[str, list]:
|
||||
"""Todas las filas de cada tabla, por nombre, en una sola sesión y en el orden de su llave primaria."""
|
||||
with self._session_factory() as sesion:
|
||||
return {
|
||||
+12
-12
@@ -12,23 +12,23 @@ from sqlmodel import Session, SQLModel, delete
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
FilaT = TypeVar("FilaT", bound=SQLModel)
|
||||
RowT = TypeVar("RowT", bound=SQLModel)
|
||||
|
||||
|
||||
class RegistroRepository(Repository[FilaT]):
|
||||
class ReferenceRepository(Repository[RowT]):
|
||||
"""Una tabla de registro: se reconstruye desde archivos o se completa, nunca se edita a mano.
|
||||
|
||||
Sirve a parámetros, periodos, tablas de apoyo (fechas, grupos de edad)
|
||||
y definiciones de indicadores. Cada operación es una sesión.
|
||||
"""
|
||||
|
||||
def reemplazar(self, filas: Iterable[FilaT]) -> int:
|
||||
def replace_all(self, filas: Iterable[RowT]) -> int:
|
||||
"""Deja la tabla con exactamente estas filas. Devuelve cuántas. Todo o nada."""
|
||||
with self._session_factory() as sesion:
|
||||
return reemplazar_en(sesion, self.model, filas)
|
||||
return replace_in(sesion, self.model, filas)
|
||||
|
||||
def reemplazar_en_bloque(self, filas: Iterable[FilaT]) -> int:
|
||||
"""Como `reemplazar`, con un solo INSERT: para tablas grandes de apoyo (`dim_fecha`, decenas de miles de días).
|
||||
def replace_in_bulk(self, filas: Iterable[RowT]) -> int:
|
||||
"""Como `replace_all`, con un solo INSERT: para tablas grandes de apoyo (`dim_fecha`, decenas de miles de días).
|
||||
|
||||
Las filas pueden venir como modelos o como diccionarios de sus columnas.
|
||||
"""
|
||||
@@ -44,18 +44,18 @@ class RegistroRepository(Repository[FilaT]):
|
||||
raise
|
||||
return len(filas)
|
||||
|
||||
def agregar_faltantes(self, filas: Iterable[FilaT]) -> int:
|
||||
def add_missing(self, filas: Iterable[RowT]) -> int:
|
||||
"""Agrega las filas cuya llave no está y no toca las demás. Devuelve cuántas agregó.
|
||||
|
||||
Para tablas a las que otras apuntan (los reportes apuntan a
|
||||
`dim_periodo`): reemplazarlas violaría esas llaves foráneas.
|
||||
"""
|
||||
with self._session_factory() as sesion:
|
||||
return agregar_faltantes_en(sesion, self.model, filas)
|
||||
return add_missing_in(sesion, self.model, filas)
|
||||
|
||||
|
||||
def reemplazar_en(sesion: Session, modelo: type[FilaT], filas: Iterable[FilaT]) -> int:
|
||||
"""El cuerpo de `RegistroRepository.reemplazar`, sobre una sesión que se recibe."""
|
||||
def replace_in(sesion: Session, modelo: type[RowT], filas: Iterable[RowT]) -> int:
|
||||
"""El cuerpo de `ReferenceRepository.reemplazar`, sobre una sesión que se recibe."""
|
||||
filas = list(filas)
|
||||
try:
|
||||
sesion.exec(delete(modelo))
|
||||
@@ -67,8 +67,8 @@ def reemplazar_en(sesion: Session, modelo: type[FilaT], filas: Iterable[FilaT])
|
||||
return len(filas)
|
||||
|
||||
|
||||
def agregar_faltantes_en(sesion: Session, modelo: type[FilaT], filas: Iterable[FilaT]) -> int:
|
||||
"""El cuerpo de `RegistroRepository.agregar_faltantes`, sobre una sesión que se recibe."""
|
||||
def add_missing_in(sesion: Session, modelo: type[RowT], filas: Iterable[RowT]) -> int:
|
||||
"""El cuerpo de `ReferenceRepository.agregar_faltantes`, sobre una sesión que se recibe."""
|
||||
llave = modelo.__table__.primary_key.columns.values()
|
||||
nuevas = [
|
||||
fila
|
||||
@@ -1,7 +1,7 @@
|
||||
"""What dbt owns in a domain's database and Python reads: the timeline view and the queries dbt compiled.
|
||||
|
||||
dbt creates and changes these relations, so there's no ORM class and no Alembic migration for them. Both repositories
|
||||
read on a `SesionDeLectura`. That refuses ORM writes and `insert`/`update`/`delete` statements, but not one spelled as
|
||||
read on a `ReadSession`. That refuses ORM writes and `insert`/`update`/`delete` statements, but not one spelled as
|
||||
text, so a compiled query is trusted to be the `select` dbt wrote; a database account that can only read is what
|
||||
guarantees it.
|
||||
"""
|
||||
@@ -9,11 +9,12 @@ guarantees it.
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Date, column, select, table, text
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
from sqlalchemy import Date, Select, bindparam, column, select, table, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from persistance.aristas.plata.timeline import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.materializador import SesionDeLectura
|
||||
from persistance.edges.silver.timeline import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.materializer import ReadSession
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
@@ -28,7 +29,7 @@ def timeline_view(domain: str) -> str:
|
||||
class DbtTimelineRepository(TimelineRepository):
|
||||
"""The domain's timeline, read from dbt's view `<domain>_linea_de_tiempo`.
|
||||
|
||||
`fecha` comes back as a date on every engine. The filters run in the database; `patients` becomes one bound
|
||||
`fecha` comes back as a date and `conocida_en` as an aware UTC datetime on every engine. The filters run in the database; `patients` becomes one bound
|
||||
parameter per patient, so a long list can exceed an engine's limit (SQL Server's is 2,100): read without it and join.
|
||||
"""
|
||||
|
||||
@@ -37,7 +38,8 @@ class DbtTimelineRepository(TimelineRepository):
|
||||
super().__init__(session_factory, self._query)
|
||||
|
||||
def _query(self, *, patients: Iterable[int] | None, until: date | None, known_until: datetime | None):
|
||||
view = table(self.view, *(column(name, Date) if name == "fecha" else column(name) for name in TIMELINE_COLUMNS))
|
||||
types = {"fecha": Date, "conocida_en": FechaHoraUTC}
|
||||
view = table(self.view, *(column(name, types.get(name)) for name in TIMELINE_COLUMNS))
|
||||
query = select(*(view.c[name] for name in TIMELINE_COLUMNS))
|
||||
if patients is not None:
|
||||
query = query.where(view.c.pac_id.in_(list(patients)))
|
||||
@@ -57,13 +59,29 @@ class DbtTimelineRepository(TimelineRepository):
|
||||
|
||||
|
||||
class DbtQueryRepository(Repository):
|
||||
"""Runs a query dbt compiled (a model's `compiled_code` in `manifest.json`); one dict per row."""
|
||||
"""Runs a query dbt compiled (a model's `compiled_code` in `manifest.json`); one dict per row.
|
||||
|
||||
A query compiled with `--vars '{bind: true}'` has placeholders (`:periodo_inicio`) instead of values: `parameters`
|
||||
gives them, and a list or tuple fills an `in :name`. The database does the work; only what the query selects
|
||||
comes back.
|
||||
"""
|
||||
|
||||
def __init__(self, session_factory: Callable):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def read(self, sql: str) -> list[dict]:
|
||||
def read(self, sql: str, parameters: dict | None = None) -> list[dict]:
|
||||
columns, rows = self.rows(sql, parameters)
|
||||
return [dict(zip(columns, row)) for row in rows]
|
||||
|
||||
def rows(self, sql: str | Select, parameters: dict | None = None) -> tuple[list[str], list[tuple]]:
|
||||
"""The column names and the rows; the names come back even when there are no rows.
|
||||
|
||||
`sql` can also be a `select` built over dbt's relations, which carries its own bound values.
|
||||
"""
|
||||
parameters = parameters or {}
|
||||
query = sql if isinstance(sql, Select) else text(sql).bindparams(*(
|
||||
bindparam(name, value, expanding=isinstance(value, (list, tuple))) for name, value in parameters.items()
|
||||
))
|
||||
with self._session_factory() as session:
|
||||
result = SesionDeLectura(session).execute(text(sql))
|
||||
columns = list(result.keys())
|
||||
return [dict(zip(columns, row)) for row in result]
|
||||
result = ReadSession(session).execute(query)
|
||||
return list(result.keys()), [tuple(row) for row in result]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Oro: el registro (parámetros, periodos, definiciones), los reportes de indicadores y las cohortes con sus riesgos."""
|
||||
|
||||
from persistance.edges.common import ReferenceRepository
|
||||
from persistance.edges.gold.calculation import CalculationRepository, MeasureReportRepository, save_report_in
|
||||
from persistance.edges.gold.history import MeasureHistoryRepository
|
||||
from persistance.edges.gold.publication import PublicationRepository, sync_publication_in
|
||||
from persistance.edges.gold.cohorts import (
|
||||
ERROR,
|
||||
FINAL,
|
||||
PRELIMINAR,
|
||||
PROVENANCE,
|
||||
CohortBuild,
|
||||
CohortRepository,
|
||||
CohortMember,
|
||||
PatientMembership,
|
||||
PatientRisk,
|
||||
PendingBatch,
|
||||
RiskOutsideCohort,
|
||||
RiskHorizon,
|
||||
change_state_in,
|
||||
save_build_in,
|
||||
save_batch_in,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ERROR",
|
||||
"FINAL",
|
||||
"PRELIMINAR",
|
||||
"PROVENANCE",
|
||||
"CalculationRepository",
|
||||
"CohortBuild",
|
||||
"CohortRepository",
|
||||
"CohortMember",
|
||||
"MeasureHistoryRepository",
|
||||
"MeasureReportRepository",
|
||||
"PatientMembership",
|
||||
"PatientRisk",
|
||||
"PendingBatch",
|
||||
"PublicationRepository",
|
||||
"ReferenceRepository",
|
||||
"RiskOutsideCohort",
|
||||
"RiskHorizon",
|
||||
"change_state_in",
|
||||
"save_build_in",
|
||||
"save_batch_in",
|
||||
"save_report_in",
|
||||
"sync_publication_in",
|
||||
]
|
||||
+24
-24
@@ -1,6 +1,6 @@
|
||||
"""Oro: los reportes de indicadores. Un reporte se guarda con sus unidades (§6f), todo o nada.
|
||||
|
||||
`CalculoRepository` es lo que usa la arista `calcular`: mide (lo que calcula el
|
||||
`CalculationRepository` es lo que usa la arista `compute`: mide (lo que calcula el
|
||||
kit, como función de la sesión) y guarda en la misma sesión, una sola foto de la
|
||||
base por reporte.
|
||||
"""
|
||||
@@ -15,14 +15,14 @@ from sqlmodel import Session, SQLModel, select
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
ReporteT = TypeVar("ReporteT", bound=MeasureReportBase)
|
||||
Medicion = tuple[MeasureReportBase, Iterable[SQLModel]]
|
||||
ReportT = TypeVar("ReportT", bound=MeasureReportBase)
|
||||
Measurement = tuple[MeasureReportBase, Iterable[SQLModel]]
|
||||
|
||||
|
||||
class MeasureReportRepository(Repository[ReporteT]):
|
||||
class MeasureReportRepository(Repository[ReportT]):
|
||||
"""Los reportes de indicadores de un dominio. Un reporte se guarda con sus unidades."""
|
||||
|
||||
def guardar(self, reporte: ReporteT, filas: Iterable[SQLModel] = ()) -> int:
|
||||
def save(self, reporte: ReportT, filas: Iterable[SQLModel] = ()) -> int:
|
||||
"""Guarda un reporte y sus filas hijas con una sola sesión. Devuelve el `report_id`.
|
||||
|
||||
Las filas (las unidades de `measure_report_unidad` y sus estratos, §6f) llegan sin `report_id`:
|
||||
@@ -32,10 +32,10 @@ class MeasureReportRepository(Repository[ReporteT]):
|
||||
fecha de corte cuenta para que sea igual (MV-3). Todo o nada.
|
||||
"""
|
||||
with self._session_factory() as sesion:
|
||||
return guardar_reporte_en(sesion, reporte, filas)
|
||||
return save_report_in(sesion, reporte, filas)
|
||||
|
||||
|
||||
def guardar_reporte_en(sesion: Session, reporte: MeasureReportBase, filas: Iterable[SQLModel] = ()) -> int:
|
||||
def save_report_in(sesion: Session, reporte: MeasureReportBase, filas: Iterable[SQLModel] = ()) -> int:
|
||||
"""El cuerpo de `MeasureReportRepository.guardar`, sobre una sesión que se recibe.
|
||||
|
||||
`filas` son las unidades del reporte (`measure_report_unidad`, oro restringido) y el estrato de cada
|
||||
@@ -44,8 +44,8 @@ def guardar_reporte_en(sesion: Session, reporte: MeasureReportBase, filas: Itera
|
||||
"""
|
||||
filas = list(filas)
|
||||
try:
|
||||
anterior = _ultimo_reporte(sesion, reporte)
|
||||
if anterior is not None and _repite(sesion, anterior, reporte, filas):
|
||||
anterior = _last_report(sesion, reporte)
|
||||
if anterior is not None and _repeats(sesion, anterior, reporte, filas):
|
||||
return anterior.report_id
|
||||
sesion.add(reporte)
|
||||
sesion.flush()
|
||||
@@ -61,7 +61,7 @@ def guardar_reporte_en(sesion: Session, reporte: MeasureReportBase, filas: Itera
|
||||
|
||||
|
||||
# Lo que hace distinto a un reporte; la hora en que se generó no cuenta.
|
||||
_COLUMNAS_QUE_DISTINGUEN = (
|
||||
_DISTINGUISHING_COLUMNS = (
|
||||
"measure_version",
|
||||
"kit_version",
|
||||
"toml_sha",
|
||||
@@ -77,7 +77,7 @@ _COLUMNAS_QUE_DISTINGUEN = (
|
||||
)
|
||||
|
||||
|
||||
def _ultimo_reporte(sesion: Session, reporte: MeasureReportBase) -> MeasureReportBase | None:
|
||||
def _last_report(sesion: Session, reporte: MeasureReportBase) -> MeasureReportBase | None:
|
||||
"""El último reporte guardado del mismo indicador y periodo, por `generado_en`."""
|
||||
modelo = type(reporte)
|
||||
return sesion.exec(
|
||||
@@ -88,14 +88,14 @@ def _ultimo_reporte(sesion: Session, reporte: MeasureReportBase) -> MeasureRepor
|
||||
).first()
|
||||
|
||||
|
||||
def _repite(sesion: Session, anterior: MeasureReportBase, reporte: MeasureReportBase, filas: list[SQLModel]) -> bool:
|
||||
def _repeats(sesion: Session, anterior: MeasureReportBase, reporte: MeasureReportBase, filas: list[SQLModel]) -> bool:
|
||||
"""Si el reporte nuevo es igual al anterior: mismo encabezado (con `huella`) y mismas filas, tabla por tabla."""
|
||||
if any(getattr(anterior, columna) != getattr(reporte, columna) for columna in _COLUMNAS_QUE_DISTINGUEN):
|
||||
if any(getattr(anterior, columna) != getattr(reporte, columna) for columna in _DISTINGUISHING_COLUMNS):
|
||||
return False
|
||||
return _iguales(sesion, anterior.report_id, filas)
|
||||
return _equal(sesion, anterior.report_id, filas)
|
||||
|
||||
|
||||
def _iguales(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
||||
def _equal(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
||||
"""Las filas de las tablas hijas guardadas con el reporte anterior son estas, tabla por tabla.
|
||||
|
||||
Las filas pueden ser de varias tablas (las unidades de `measure_report_unidad` y sus estratos):
|
||||
@@ -106,27 +106,27 @@ def _iguales(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
||||
por_tabla.setdefault(type(fila), []).append(fila)
|
||||
for modelo, de_la_tabla in por_tabla.items():
|
||||
guardadas = sesion.exec(select(modelo).where(modelo.report_id == report_id)).all()
|
||||
if sorted(map(_contenido, guardadas)) != sorted(map(_contenido, de_la_tabla)):
|
||||
if sorted(map(_content, guardadas)) != sorted(map(_content, de_la_tabla)):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _contenido(fila: SQLModel) -> str:
|
||||
def _content(fila: SQLModel) -> str:
|
||||
"""Lo que dice una fila hija, sin su `report_id` ni una llave entera que numere la base.
|
||||
|
||||
En `measure_report_unidad`, `valor_id` es la categoría y sí cuenta (T-19b).
|
||||
"""
|
||||
llave = type(fila).__table__.primary_key.columns
|
||||
puesta_por_la_base = {c.name for c in llave} if len(llave) == 1 and _llave_entera(llave) else set()
|
||||
puesta_por_la_base = {c.name for c in llave} if len(llave) == 1 and _whole_key(llave) else set()
|
||||
return json.dumps(fila.model_dump(exclude={"report_id", *puesta_por_la_base}), sort_keys=True, default=str)
|
||||
|
||||
|
||||
def _llave_entera(columnas) -> bool:
|
||||
def _whole_key(columnas) -> bool:
|
||||
"""Si la única columna de la llave es entera: la numera la base."""
|
||||
return all(c.type.python_type is int for c in columnas)
|
||||
|
||||
|
||||
class CalculoRepository(MeasureReportRepository):
|
||||
class CalculationRepository(MeasureReportRepository):
|
||||
"""Los reportes de un dominio, calculados en una sola sesión: una sola foto de la base por reporte.
|
||||
|
||||
`periodo` es la tabla `dim_periodo` del dominio.
|
||||
@@ -136,7 +136,7 @@ class CalculoRepository(MeasureReportRepository):
|
||||
super().__init__(session_factory, model)
|
||||
self.periodo = periodo
|
||||
|
||||
def periodos(self, tipo: str, desde: date, hasta: date) -> list[str]:
|
||||
def periods(self, tipo: str, desde: date, hasta: date) -> list[str]:
|
||||
"""Los `periodo_id` de `tipo` que caben enteros en `[desde, hasta)`, en orden. Falla si no hay ninguno."""
|
||||
p = self.periodo
|
||||
with self._session_factory() as sesion:
|
||||
@@ -146,15 +146,15 @@ class CalculoRepository(MeasureReportRepository):
|
||||
if not ids:
|
||||
raise LookupError(
|
||||
f"dim_periodo no tiene periodos {tipo!r} entre {desde} y {hasta}: "
|
||||
"se agregan con la arista `registro`."
|
||||
"se agregan con la arista `registry`."
|
||||
)
|
||||
return ids
|
||||
|
||||
def calcular(self, medir: Callable[[Session], Medicion]) -> int:
|
||||
def compute(self, medir: Callable[[Session], Measurement]) -> int:
|
||||
"""Mide con `medir(sesion)` (el reporte y sus unidades) y lo guarda en esa misma sesión.
|
||||
|
||||
Devuelve el `report_id`; si el reporte repite al último del periodo, el de ese (`guardar`).
|
||||
"""
|
||||
with self._session_factory() as sesion:
|
||||
reporte, filas = medir(sesion)
|
||||
return guardar_reporte_en(sesion, reporte, filas)
|
||||
return save_report_in(sesion, reporte, filas)
|
||||
+132
-21
@@ -23,48 +23,48 @@ from sqlmodel import Session, SQLModel, select
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
PROCEDENCIA = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
|
||||
PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
|
||||
PRELIMINAR, FINAL, ERROR = "preliminary", "final", "entered-in-error"
|
||||
|
||||
|
||||
# Lo que el kit entrega para guardar un armado: la fila del armado y sus hijas, sin `armado_id`.
|
||||
Armado = tuple[SQLModel, Iterable[SQLModel], Iterable[SQLModel], Iterable[SQLModel]]
|
||||
BuildModel = tuple[SQLModel, Iterable[SQLModel], Iterable[SQLModel], Iterable[SQLModel]]
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class RiesgoFueraDeCohorte(ValueError):
|
||||
class RiskOutsideCohort(ValueError):
|
||||
"""Se quiso guardar el riesgo de alguien que no es miembro del armado puntuado."""
|
||||
|
||||
|
||||
class CohorteRepository(Repository):
|
||||
class CohortRepository(Repository):
|
||||
"""Los armados de cohortes de un dominio y sus lotes de riesgos. Cada método, una sesión."""
|
||||
|
||||
def __init__(self, session_factory, cohortes: TablasCohorte):
|
||||
super().__init__(session_factory, cohortes.CohorteArmado)
|
||||
self.cohortes = cohortes
|
||||
|
||||
def armar(self, armado: Callable[[Session], Armado]) -> tuple[int, bool]:
|
||||
def assemble(self, armado: Callable[[Session], BuildModel]) -> tuple[int, bool]:
|
||||
"""Calcula el armado con `armado(sesion)` y lo guarda en esa sesión. Devuelve (`armado_id`, nuevo)."""
|
||||
with self._session_factory() as sesion:
|
||||
return guardar_armado_en(sesion, *armado(sesion))
|
||||
return save_build_in(sesion, *armado(sesion))
|
||||
|
||||
def leer(self, leer: Callable[[Session], T]) -> T:
|
||||
def read(self, leer: Callable[[Session], T]) -> T:
|
||||
"""Lo que `leer(sesion)` lee de las cohortes, en una sesión (el marco de un armado para estimar). No escribe."""
|
||||
with self._session_factory() as sesion:
|
||||
return leer(sesion)
|
||||
|
||||
def guardar_lote(
|
||||
def save_batch(
|
||||
self, armado_id: int, procedencia: dict, desenlace: str, riesgos, *, ahora: datetime | None = None
|
||||
) -> tuple[int, bool]:
|
||||
with self._session_factory() as sesion:
|
||||
return guardar_lote_en(sesion, armado_id, procedencia, desenlace, riesgos, cohortes=self.cohortes,
|
||||
return save_batch_in(sesion, armado_id, procedencia, desenlace, riesgos, cohortes=self.cohortes,
|
||||
ahora=ahora)
|
||||
|
||||
def cambiar_estado(self, lote_id: int, estado: str, motivo: str, *, ahora: datetime | None = None) -> int:
|
||||
def change_state(self, lote_id: int, estado: str, motivo: str, *, ahora: datetime | None = None) -> int:
|
||||
with self._session_factory() as sesion:
|
||||
return cambiar_estado_en(sesion, lote_id, estado, motivo, cohortes=self.cohortes, ahora=ahora)
|
||||
return change_state_in(sesion, lote_id, estado, motivo, cohortes=self.cohortes, ahora=ahora)
|
||||
|
||||
def latest_build(self, url: str) -> int | None:
|
||||
"""The most recent build of the cohort `url`, or `None` if it has none."""
|
||||
@@ -98,6 +98,117 @@ class CohorteRepository(Repository):
|
||||
return [_cohort_build(row) for row in sesion.exec(query).all()]
|
||||
|
||||
|
||||
def membership(self, pac_id: int, url: str) -> "PatientMembership | None":
|
||||
"""The patient in the cohort's latest build: its version, index date and stored variables (`c`, `l`, `r`,
|
||||
`pap_0`, `hpv_0`...); `None` if the cohort has no build or the patient isn't a member of the latest one."""
|
||||
if (build_id := self.latest_build(url)) is None:
|
||||
return None
|
||||
member, variable = self.cohortes.CohorteMiembro, self.cohortes.CohorteVariable
|
||||
with self._session_factory() as sesion:
|
||||
row = sesion.get(member, (build_id, pac_id))
|
||||
if row is None:
|
||||
return None
|
||||
build = sesion.get(self.cohortes.CohorteArmado, build_id)
|
||||
values = sesion.exec(select(variable).where(variable.armado_id == build_id, variable.pac_id == pac_id)).all()
|
||||
return PatientMembership(build_id, url, build.version, row.fecha_indice,
|
||||
{v.variable: v.valor_codigo if v.valor_codigo is not None else v.valor_numerico
|
||||
for v in values})
|
||||
|
||||
def pending_batches(self) -> list["PendingBatch"]:
|
||||
"""Batches with no evaluation confirmed or voided yet (ADR-MD-008): created by estimating, waiting for
|
||||
someone's decision. Newest first."""
|
||||
lote, e = self.cohortes.EvaluacionRiesgoLote, self.cohortes.EvaluacionRiesgo
|
||||
with self._session_factory() as sesion:
|
||||
lotes = sesion.exec(select(lote).order_by(lote.lote_id.desc())).all()
|
||||
pending = []
|
||||
for fila in lotes:
|
||||
latest = _latest_versions(sesion, e, fila.lote_id)
|
||||
decided = sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == fila.lote_id, e.estado != PRELIMINAR).limit(1)).first()
|
||||
if decided is None:
|
||||
pending.append(PendingBatch(fila.lote_id, fila.modelo_nombre, fila.modelo_version,
|
||||
fila.evaluado_en, fila.n_evaluaciones))
|
||||
return pending
|
||||
|
||||
def current_risk(self, pac_id: int) -> "PatientRisk | None":
|
||||
"""The patient's risks in the current batch: the highest `lote_id` among the patient's batches where some
|
||||
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
|
||||
horizons whose latest version is `entered-in-error` are left out. `None` if no batch of the patient is
|
||||
confirmed."""
|
||||
e = self.cohortes.EvaluacionRiesgo
|
||||
with self._session_factory() as sesion:
|
||||
batches = sesion.exec(select(e.lote_id).where(e.pac_id == pac_id).distinct().order_by(e.lote_id.desc())).all()
|
||||
for lote_id in batches:
|
||||
latest = _latest_versions(sesion, e, lote_id)
|
||||
if not sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == lote_id, e.estado == FINAL).limit(1)).first():
|
||||
continue
|
||||
rows = sesion.exec(select(e).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == lote_id, e.pac_id == pac_id, e.estado != ERROR)
|
||||
.order_by(e.horizonte_anios)).all()
|
||||
batch = sesion.get(self.cohortes.EvaluacionRiesgoLote, lote_id)
|
||||
return PatientRisk(lote_id, batch.modelo_nombre, batch.modelo_version, batch.evaluado_en, FINAL,
|
||||
[RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado)
|
||||
for r in rows])
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PatientMembership:
|
||||
"""A patient in a cohort's latest build: which build, from which index date, and its stored variables."""
|
||||
|
||||
armado_id: int
|
||||
url: str
|
||||
version: str
|
||||
fecha_indice: date
|
||||
variables: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RiskHorizon:
|
||||
"""A patient's risk at one horizon, at its latest version."""
|
||||
|
||||
horizonte_anios: float
|
||||
probabilidad: float
|
||||
ic_bajo: float | None
|
||||
ic_alto: float | None
|
||||
estado: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingBatch:
|
||||
"""A risk batch waiting for someone to confirm or void it; no evaluation has reached `final` or
|
||||
`entered-in-error` yet."""
|
||||
|
||||
lote_id: int
|
||||
modelo_nombre: str
|
||||
modelo_version: str
|
||||
evaluado_en: datetime
|
||||
n_evaluaciones: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PatientRisk:
|
||||
"""A patient's risks in the current batch, with the model that produced them."""
|
||||
|
||||
lote_id: int
|
||||
modelo_nombre: str
|
||||
modelo_version: str
|
||||
evaluado_en: datetime
|
||||
estado_lote: str
|
||||
horizontes: list[RiskHorizon]
|
||||
|
||||
|
||||
def _latest_versions(sesion: Session, e, lote_id: int):
|
||||
"""The latest version of each (patient, horizon) of a batch, as a subquery."""
|
||||
return (select(e.pac_id, e.horizonte_anios, func.max(e.version).label("version"))
|
||||
.where(e.lote_id == lote_id).group_by(e.pac_id, e.horizonte_anios).subquery())
|
||||
|
||||
|
||||
def _same_version(e, latest):
|
||||
return (e.pac_id == latest.c.pac_id) & (e.horizonte_anios == latest.c.horizonte_anios) & (e.version == latest.c.version)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CohortMember:
|
||||
"""A member of a cohort build: who, from which index date, and the row of its index event."""
|
||||
@@ -136,7 +247,7 @@ def _cohort_build(row: SQLModel) -> CohortBuild:
|
||||
row.n_miembros, row.armado_en)
|
||||
|
||||
|
||||
def guardar_armado_en(
|
||||
def save_build_in(
|
||||
sesion: Session, armado: SQLModel, exclusiones: Iterable[SQLModel], miembros: Iterable[SQLModel],
|
||||
variables: Iterable[SQLModel],
|
||||
) -> tuple[int, bool]:
|
||||
@@ -168,7 +279,7 @@ def guardar_armado_en(
|
||||
return armado_id, True
|
||||
|
||||
|
||||
def guardar_lote_en(
|
||||
def save_batch_in(
|
||||
sesion: Session,
|
||||
armado_id: int,
|
||||
procedencia: dict,
|
||||
@@ -180,18 +291,18 @@ def guardar_lote_en(
|
||||
) -> tuple[int, bool]:
|
||||
"""Guarda los riesgos `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve (`lote_id`, nuevo).
|
||||
|
||||
No copia nada de MLflow: guarda sus llaves (`PROCEDENCIA`). Puntuar lo mismo
|
||||
No copia nada de MLflow: guarda sus llaves (`PROVENANCE`). Puntuar lo mismo
|
||||
otra vez (mismo armado, modelo y riesgos) no duplica: la huella del lote ya está.
|
||||
"""
|
||||
faltan = [c for c in PROCEDENCIA if not procedencia.get(c)]
|
||||
faltan = [c for c in PROVENANCE if not procedencia.get(c)]
|
||||
if faltan:
|
||||
raise ValueError(f"La procedencia no trae {faltan}.")
|
||||
miembro = cohortes.CohorteMiembro
|
||||
miembros = set(sesion.exec(select(miembro.pac_id).where(miembro.armado_id == armado_id)))
|
||||
ajenos = sorted({pac for pac, *_ in riesgos} - miembros)
|
||||
if ajenos:
|
||||
raise RiesgoFueraDeCohorte(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
|
||||
huella = _sha_json({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROCEDENCIA},
|
||||
raise RiskOutsideCohort(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
|
||||
huella = _json_sha({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROVENANCE},
|
||||
"riesgos": sorted(riesgos)})
|
||||
lote = cohortes.EvaluacionRiesgoLote
|
||||
previo = sesion.exec(select(lote).where(lote.huella == huella)).first()
|
||||
@@ -200,7 +311,7 @@ def guardar_lote_en(
|
||||
momento = ahora or datetime.now(timezone.utc)
|
||||
try:
|
||||
fila = lote(armado_id=armado_id, desenlace=desenlace, evaluado_en=momento, n_evaluaciones=len(riesgos),
|
||||
huella=huella, **{c: str(procedencia[c]) for c in PROCEDENCIA})
|
||||
huella=huella, **{c: str(procedencia[c]) for c in PROVENANCE})
|
||||
sesion.add(fila)
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
@@ -215,7 +326,7 @@ def guardar_lote_en(
|
||||
return fila.lote_id, True
|
||||
|
||||
|
||||
def cambiar_estado_en(
|
||||
def change_state_in(
|
||||
sesion: Session, lote_id: int, estado: str, motivo: str, *, cohortes: TablasCohorte,
|
||||
ahora: datetime | None = None,
|
||||
) -> int:
|
||||
@@ -248,7 +359,7 @@ def cambiar_estado_en(
|
||||
return len(vigentes)
|
||||
|
||||
|
||||
def _sha_json(objeto) -> str:
|
||||
"""sha256 del JSON canónico (el mismo de `indicadores_kit.oro.cohortes.definicion.sha_json`)."""
|
||||
def _json_sha(objeto) -> str:
|
||||
"""sha256 del JSON canónico (el mismo de `models.cohorts.definition.json_sha`)."""
|
||||
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
||||
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Oro: measures asked for on request, each answer kept once under the full key of the question.
|
||||
|
||||
A question is a measure and its definition's version, a period, the event cut-off (`fecha`), the knowledge cut-off
|
||||
(`conocida_en`) and the values of its rules. Its answer is a `measure_report` whose `parametros` is that key and
|
||||
whose `parametros_sha` is the key's hash, with its units in `measure_report_unidad` and their strata in
|
||||
`measure_report_unidad_estrato`, so the publication views read it as any other report. The database writes those
|
||||
rows (`INSERT … SELECT`): they never pass through Python. A stratum value not yet in `cat_estrato_valor` is added
|
||||
there first, labelled with itself, so the foreign key from `measure_report_unidad_estrato` holds.
|
||||
|
||||
Asking a stored key again reads it and writes nothing; what was answered can't drift when later loads change silver.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from sqlalchemy import Select, and_, distinct, exists, func, insert, literal, select
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class MeasureHistoryRepository(Repository):
|
||||
"""The reports of a domain's measures asked for on request. `unit_model` and `stratum_model` are the domain's
|
||||
`measure_report_unidad` and `measure_report_unidad_estrato`; `value_model`, its `cat_estrato_valor`."""
|
||||
|
||||
def __init__(self, session_factory, model, *, unit_model, stratum_model, value_model):
|
||||
super().__init__(session_factory, model)
|
||||
self.unit_model, self.stratum_model, self.value_model = unit_model, stratum_model, value_model
|
||||
|
||||
def counts(self, report_id: int) -> dict[tuple[str, str, str, str | None], int]:
|
||||
"""A stored answer's units counted from its rows: `{(stratum, value, resultado_id, valor_id): units}`, the
|
||||
total as `("total", "total", …)`. No view is needed to read what was answered."""
|
||||
u, e = self.unit_model, self.stratum_model
|
||||
units = func.count(distinct(u.unidad_id))
|
||||
with self._session_factory() as session:
|
||||
total = session.execute(select(u.resultado_id, u.valor_id, units).where(u.report_id == report_id)
|
||||
.group_by(u.resultado_id, u.valor_id)).all()
|
||||
by_stratum = session.execute(
|
||||
select(e.estrato_id, e.estrato_valor, u.resultado_id, u.valor_id, units)
|
||||
.join(e, (e.report_id == u.report_id) & (e.unidad_id == u.unidad_id))
|
||||
.where(u.report_id == report_id)
|
||||
.group_by(e.estrato_id, e.estrato_valor, u.resultado_id, u.valor_id)).all()
|
||||
return {**{("total", "total", r, v): n for r, v, n in total},
|
||||
**{(s, sv, r, v): n for s, sv, r, v, n in by_stratum}}
|
||||
|
||||
def group_counts(self, report_id: int) -> dict[tuple[str, str], int]:
|
||||
"""A stored answer's units per group and population: `{(grupo, resultado_id): units}`. For a measure with
|
||||
several groups, whose units repeat in each one."""
|
||||
u = self.unit_model
|
||||
with self._session_factory() as session:
|
||||
rows = session.execute(select(u.grupo, u.resultado_id, func.count(distinct(u.unidad_id)))
|
||||
.where(u.report_id == report_id).group_by(u.grupo, u.resultado_id)).all()
|
||||
return {(g, r): n for g, r, n in rows}
|
||||
|
||||
def find(self, measure_url: str, key_sha: str) -> int | None:
|
||||
"""The report already answering this key, if it was asked before."""
|
||||
report = self.model
|
||||
with self._session_factory() as session:
|
||||
return session.execute(
|
||||
select(report.report_id)
|
||||
.where(report.measure_url == measure_url, report.parametros_sha == key_sha)
|
||||
.order_by(report.report_id)
|
||||
.limit(1)
|
||||
).scalar()
|
||||
|
||||
def record(self, report: SQLModel, rows: Callable[[int], Iterable[tuple[type[SQLModel], Select]]]) -> int:
|
||||
"""Saves the report and, in the same transaction, what each `(model, select)` of `rows(report_id)` gives.
|
||||
|
||||
Each select names its columns as the model's table does. All or nothing. Returns the `report_id`.
|
||||
"""
|
||||
with self._session_factory() as session:
|
||||
try:
|
||||
session.add(report)
|
||||
session.flush()
|
||||
report_id = report.report_id
|
||||
for model, query in rows(report_id):
|
||||
table = model.__table__
|
||||
if model is self.stratum_model:
|
||||
session.execute(self._new_values(query))
|
||||
session.execute(insert(table).from_select([table.c[c.name] for c in query.selected_columns], query))
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
return report_id
|
||||
|
||||
def _new_values(self, strata: Select):
|
||||
"""`INSERT … SELECT` of the stratum values `strata` gives that `cat_estrato_valor` doesn't have yet."""
|
||||
catalog, given = self.value_model.__table__, strata.subquery()
|
||||
new = (select(given.c.estrato_id, given.c.estrato_valor, given.c.estrato_valor, literal(0))
|
||||
.where(~exists().where(and_(catalog.c.estrato_id == given.c.estrato_id,
|
||||
catalog.c.valor_id == given.c.estrato_valor)))
|
||||
.distinct())
|
||||
return insert(catalog).from_select(["estrato_id", "valor_id", "etiqueta", "orden"], new)
|
||||
+12
-12
@@ -1,6 +1,6 @@
|
||||
"""Oro: el catálogo de publicación (§6f, MD-19), `cat_measure*` y `cat_estrato*`, sincronizado con los TOML del kit.
|
||||
|
||||
Las filas llegan ya armadas y por capas (`indicadores_kit.registry.publicacion.semillas_de`). No se
|
||||
Las filas llegan ya armadas y por capas (`webapi.orchestration.reference.publicacion.semillas_de`). No se
|
||||
reemplazan enteras: las unidades de los reportes guardados apuntan a `cat_measure_resultado` y a
|
||||
`cat_estrato_valor`. Se inserta o actualiza por llave, y se borra solo lo que ya no viene **y nadie usa**.
|
||||
Lo que una fila de otra tabla todavía referencia se queda.
|
||||
@@ -15,25 +15,25 @@ from sqlmodel import Session, SQLModel, select
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class PublicacionRepository(Repository):
|
||||
class PublicationRepository(Repository):
|
||||
"""Las siete tablas del catálogo de publicación de un dominio, en orden de llaves foráneas."""
|
||||
|
||||
def __init__(self, session_factory: Callable[[], Session], modelos: Sequence[type[SQLModel]]):
|
||||
super().__init__(session_factory, modelos[0])
|
||||
self.modelos = tuple(modelos)
|
||||
|
||||
def sincronizar(self, capas: Iterable[Iterable[SQLModel]]) -> dict[str, int]:
|
||||
def sync(self, capas: Iterable[Iterable[SQLModel]]) -> dict[str, int]:
|
||||
"""Inserta o actualiza las filas, capa por capa, y borra lo que no vino y nadie usa. Una sesión, todo o nada."""
|
||||
with self._session_factory() as sesion:
|
||||
return sincronizar_publicacion_en(sesion, capas, self.modelos)
|
||||
return sync_publication_in(sesion, capas, self.modelos)
|
||||
|
||||
|
||||
def sincronizar_publicacion_en(
|
||||
def sync_publication_in(
|
||||
sesion: Session, capas: Iterable[Iterable[SQLModel]], modelos: Sequence[type[SQLModel]]
|
||||
) -> dict[str, int]:
|
||||
"""El cuerpo de `PublicacionRepository.sincronizar`, sobre una sesión que se recibe.
|
||||
"""El cuerpo de `PublicationRepository.sincronizar`, sobre una sesión que se recibe.
|
||||
|
||||
`capas`: listas de filas, cada una con sus padres en una capa anterior. `modelos`: las tablas que se
|
||||
`capas`: listas de filas, cada una con sus padres en una capa anterior. `event_models`: las tablas que se
|
||||
sincronizan, padres antes que hijos; de ellas se borra lo que no vino, de los hijos a los padres.
|
||||
Devuelve cuántas filas llegaron, cuántas se borraron y cuántas se conservaron por estar en uso.
|
||||
"""
|
||||
@@ -42,15 +42,15 @@ def sincronizar_publicacion_en(
|
||||
try:
|
||||
for capa in capas:
|
||||
for fila in capa:
|
||||
vienen.setdefault(type(fila), set()).add(_llave(fila))
|
||||
vienen.setdefault(type(fila), set()).add(_key(fila))
|
||||
sesion.merge(fila)
|
||||
cuenta["filas"] += 1
|
||||
sesion.flush()
|
||||
for modelo in reversed(modelos):
|
||||
for fila in sesion.exec(select(modelo)).all():
|
||||
if _llave(fila) in vienen[modelo]:
|
||||
if _key(fila) in vienen[modelo]:
|
||||
continue
|
||||
if _en_uso(sesion, fila):
|
||||
if _in_use(sesion, fila):
|
||||
cuenta["en_uso"] += 1
|
||||
continue
|
||||
sesion.delete(fila)
|
||||
@@ -63,11 +63,11 @@ def sincronizar_publicacion_en(
|
||||
return cuenta
|
||||
|
||||
|
||||
def _llave(fila: SQLModel) -> tuple:
|
||||
def _key(fila: SQLModel) -> tuple:
|
||||
return tuple(getattr(fila, columna.name) for columna in type(fila).__table__.primary_key.columns)
|
||||
|
||||
|
||||
def _en_uso(sesion: Session, fila: SQLModel) -> bool:
|
||||
def _in_use(sesion: Session, fila: SQLModel) -> bool:
|
||||
"""Si alguna fila de otra tabla del mismo registro apunta a esta por una llave foránea."""
|
||||
tabla = type(fila).__table__
|
||||
for otra in tabla.metadata.tables.values():
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Plata: los catálogos y cómo los escribe cada fuente, la carga del staging directo, `v_persona`, el periodo de observación, la verificación y la línea de tiempo."""
|
||||
|
||||
from persistance.edges.silver.loads import (
|
||||
LoadRepository,
|
||||
open_load,
|
||||
close_load,
|
||||
save_load_in,
|
||||
)
|
||||
from persistance.edges.silver.catalogs import CatalogRepository
|
||||
from persistance.edges.silver.source_mappings import SourceMappingRepository
|
||||
from persistance.edges.silver.observation import ObservationRepository
|
||||
from persistance.edges.silver.procedures import save_silver_in
|
||||
from persistance.edges.silver.timeline import (
|
||||
TIMELINE_COLUMNS,
|
||||
TimelineContractError,
|
||||
TimelineQuery,
|
||||
TimelineQueryMissing,
|
||||
TimelineRepository,
|
||||
)
|
||||
from persistance.edges.silver.links import LinksRepository
|
||||
from persistance.edges.silver.views import ViewsRepository
|
||||
|
||||
__all__ = [
|
||||
"LoadRepository",
|
||||
"CatalogRepository",
|
||||
"SourceMappingRepository",
|
||||
"ObservationRepository",
|
||||
"TIMELINE_COLUMNS",
|
||||
"TimelineContractError",
|
||||
"TimelineQuery",
|
||||
"TimelineQueryMissing",
|
||||
"TimelineRepository",
|
||||
"LinksRepository",
|
||||
"ViewsRepository",
|
||||
"open_load",
|
||||
"close_load",
|
||||
"save_load_in",
|
||||
"save_silver_in",
|
||||
]
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
"""Plata: `catalogos`, materializar el catálogo del proyecto en `cat_estudio`, `cat_resultado` y `cat_valor`.
|
||||
"""Plata: `catalogs`, materializar el catálogo del proyecto en `cat_estudio`, `cat_resultado` y `cat_valor`.
|
||||
|
||||
Las filas llegan ya armadas (el kit lee `core/catalogos/<proyecto>.toml`). Nada se
|
||||
borra: un valor que salió del archivo pasa a `retirado`, porque lo pueden seguir
|
||||
@@ -12,7 +12,7 @@ from sqlmodel import Session, SQLModel, select
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class CatalogoRepository(Repository):
|
||||
class CatalogRepository(Repository):
|
||||
"""Las tres tablas de catálogo de un dominio. `get`, `list` y `count` leen los estudios."""
|
||||
|
||||
def __init__(
|
||||
@@ -26,7 +26,7 @@ class CatalogoRepository(Repository):
|
||||
self.resultado = resultado
|
||||
self.valor = valor
|
||||
|
||||
def sincronizar(
|
||||
def sync(
|
||||
self, estudios: Iterable[SQLModel], resultados: Iterable[SQLModel], valores: Iterable[SQLModel]
|
||||
) -> dict[str, int]:
|
||||
"""Inserta o actualiza por llave y retira los valores que ya no vienen. Una sesión, todo o nada.
|
||||
+4
-4
@@ -10,13 +10,13 @@ from persistance.repository import Repository
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class VinculosRepository(Repository):
|
||||
class LinksRepository(Repository):
|
||||
"""Cuenta, con lo que calcula el kit sobre la sesión, cuántos resultados encuentran su toma."""
|
||||
|
||||
def __init__(self, session_factory):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def verificar(self, verificar: Callable[[Session], T]) -> T:
|
||||
"""Corre `verificar(sesion)` en una sesión de solo lectura (no hace commit)."""
|
||||
def check(self, check: Callable[[Session], T]) -> T:
|
||||
"""Corre `check(sesion)` en una sesión de solo lectura (no hace commit)."""
|
||||
with self._session_factory() as sesion:
|
||||
return verificar(sesion)
|
||||
return check(sesion)
|
||||
+21
-21
@@ -2,7 +2,7 @@
|
||||
|
||||
Desde F6 (ADR-MD-009) no hay tablas de hechos por tipo ni sus versiones: el kit arma la
|
||||
plata del staging directo (`plata_desde_staging`) y aquí se escribe en una transacción
|
||||
(`guardar_carga_en`, con `guardar_plata_en`). Aquí no se sabe qué es un indicador.
|
||||
(`save_load_in`, con `save_silver_in`). Aquí no se sabe qué es un indicador.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -13,13 +13,13 @@ from typing import TypeVar
|
||||
from core.indicadores.comunes import CargaBase, PersonaBase
|
||||
from sqlmodel import Session, SQLModel
|
||||
|
||||
from persistance.aristas.plata.procedimientos import guardar_plata_en
|
||||
from persistance.edges.silver.procedures import save_silver_in
|
||||
from persistance.repository import Repository
|
||||
|
||||
CargaT = TypeVar("CargaT", bound=CargaBase)
|
||||
LoadT = TypeVar("LoadT", bound=CargaBase)
|
||||
|
||||
|
||||
class CargaRepository(Repository[CargaT]):
|
||||
class LoadRepository(Repository[LoadT]):
|
||||
"""Las cargas de un dominio. Una carga se escribe aquí, entera.
|
||||
|
||||
`persona` es la tabla de personas del mismo dominio: la carga agrega
|
||||
@@ -30,7 +30,7 @@ class CargaRepository(Repository[CargaT]):
|
||||
def __init__(
|
||||
self,
|
||||
session_factory: Callable[[], Session],
|
||||
model: type[CargaT],
|
||||
model: type[LoadT],
|
||||
*,
|
||||
persona: type[PersonaBase],
|
||||
procedimiento: type[SQLModel] | None = None,
|
||||
@@ -41,24 +41,24 @@ class CargaRepository(Repository[CargaT]):
|
||||
self.procedimiento = procedimiento
|
||||
self.observacion = observacion
|
||||
|
||||
def guardar_carga(
|
||||
def save_load(
|
||||
self, *, fuente: str, personas: Iterable[PersonaBase], plata, codigo_sha: str | None = None
|
||||
) -> CargaT:
|
||||
"""Escribe una carga con una sola sesión y devuelve su fila de `carga` (`guardar_carga_en`)."""
|
||||
) -> LoadT:
|
||||
"""Escribe una carga con una sola sesión y devuelve su fila de `carga` (`save_load_in`)."""
|
||||
if self.procedimiento is None or self.observacion is None:
|
||||
raise ValueError("Una carga con plata necesita las tablas procedimiento, observacion.")
|
||||
with self._session_factory() as sesion:
|
||||
return guardar_carga_en(
|
||||
return save_load_in(
|
||||
sesion, carga=self.model, persona=self.persona, procedimiento=self.procedimiento,
|
||||
observacion=self.observacion, fuente=fuente, personas=personas, plata=plata,
|
||||
codigo_sha=codigo_sha,
|
||||
)
|
||||
|
||||
|
||||
def guardar_carga_en(
|
||||
def save_load_in(
|
||||
sesion: Session,
|
||||
*,
|
||||
carga: type[CargaT],
|
||||
carga: type[LoadT],
|
||||
persona: type[PersonaBase],
|
||||
procedimiento: type[SQLModel],
|
||||
observacion: type[SQLModel],
|
||||
@@ -66,7 +66,7 @@ def guardar_carga_en(
|
||||
personas: Iterable[PersonaBase],
|
||||
plata,
|
||||
codigo_sha: str | None = None,
|
||||
) -> CargaT:
|
||||
) -> LoadT:
|
||||
"""La carga del staging directo (T-20c): personas y plata, sin tablas por tipo. Una transacción.
|
||||
|
||||
Los contadores de `carga` cuentan **procedimientos** por su efecto: nuevos; cambiados, ellos o
|
||||
@@ -76,9 +76,9 @@ def guardar_carga_en(
|
||||
Se puede repetir: lo que no cambió no se toca. Todo o nada.
|
||||
"""
|
||||
try:
|
||||
fila = abrir_carga(sesion, carga, fuente=fuente, codigo_sha=codigo_sha)
|
||||
_poner_personas(sesion, persona, personas)
|
||||
cuenta = guardar_plata_en(sesion, plata, procedimiento=procedimiento, observacion=observacion,
|
||||
fila = open_load(sesion, carga, fuente=fuente, codigo_sha=codigo_sha)
|
||||
_put_persons(sesion, persona, personas)
|
||||
cuenta = save_silver_in(sesion, plata, procedimiento=procedimiento, observacion=observacion,
|
||||
carga_id=fila.carga_id)
|
||||
fila.filas_nuevas = cuenta["procedimientos_nuevos"]
|
||||
fila.filas_cambiadas = cuenta["procedimientos_tocados"]
|
||||
@@ -86,7 +86,7 @@ def guardar_carga_en(
|
||||
- cuenta["procedimientos_nuevos"] - cuenta["procedimientos_tocados"])
|
||||
descartes = {**plata.descartes, **({"huerfanos": cuenta["huerfanos"]} if cuenta["huerfanos"] else {})}
|
||||
fila.descartes = json.dumps(descartes, sort_keys=True, ensure_ascii=False) if descartes else None
|
||||
cerrar_carga(sesion, fila)
|
||||
close_load(sesion, fila)
|
||||
sesion.commit()
|
||||
except Exception:
|
||||
sesion.rollback()
|
||||
@@ -95,7 +95,7 @@ def guardar_carga_en(
|
||||
return fila
|
||||
|
||||
|
||||
def _poner_personas(sesion: Session, persona: type[PersonaBase], personas: Iterable[PersonaBase]) -> None:
|
||||
def _put_persons(sesion: Session, persona: type[PersonaBase], personas: Iterable[PersonaBase]) -> None:
|
||||
"""Agrega las personas que falten y pone al día las que ya estaban."""
|
||||
for nueva in personas:
|
||||
actual = sesion.get(persona, nueva.pac_id)
|
||||
@@ -110,9 +110,9 @@ def _poner_personas(sesion: Session, persona: type[PersonaBase], personas: Itera
|
||||
sesion.flush()
|
||||
|
||||
|
||||
def abrir_carga(
|
||||
sesion: Session, carga: type[CargaT], fuente: str, codigo_sha: str | None = None
|
||||
) -> CargaT:
|
||||
def open_load(
|
||||
sesion: Session, carga: type[LoadT], fuente: str, codigo_sha: str | None = None
|
||||
) -> LoadT:
|
||||
"""Registra el inicio de una carga y devuelve su fila, ya con `carga_id`."""
|
||||
fila = carga(fuente=fuente, inicio=datetime.now(timezone.utc), codigo_sha=codigo_sha)
|
||||
sesion.add(fila)
|
||||
@@ -120,7 +120,7 @@ def abrir_carga(
|
||||
return fila
|
||||
|
||||
|
||||
def cerrar_carga(sesion: Session, carga: CargaBase) -> None:
|
||||
def close_load(sesion: Session, carga: CargaBase) -> None:
|
||||
"""Registra el fin de una carga; los conteos ya van en la fila."""
|
||||
carga.fin = datetime.now(timezone.utc)
|
||||
sesion.add(carga)
|
||||
+4
-4
@@ -1,16 +1,16 @@
|
||||
"""Plata: `observar`, reemplazar `periodo_observacion` con las filas que se calculan en la misma sesión."""
|
||||
"""Plata: `observe`, reemplazar `periodo_observacion` con las filas que se calculan en la misma sesión."""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.comun import RegistroRepository, reemplazar_en
|
||||
from persistance.edges.common import ReferenceRepository, replace_in
|
||||
|
||||
|
||||
class ObservacionRepository(RegistroRepository):
|
||||
class ObservationRepository(ReferenceRepository):
|
||||
"""`periodo_observacion` de un dominio."""
|
||||
|
||||
def observar(self, periodos: Callable[[Session], Iterable]) -> int:
|
||||
"""Calcula los periodos con `periodos(sesion)` y deja la tabla con exactamente esos. Devuelve cuántos."""
|
||||
with self._session_factory() as sesion:
|
||||
return reemplazar_en(sesion, self.model, periodos(sesion))
|
||||
return replace_in(sesion, self.model, periodos(sesion))
|
||||
+23
-17
@@ -16,7 +16,8 @@ Persistance lo importe:
|
||||
Un procedimiento sin `pac_id` toma el de su padre; sin `fecha`, también, si el kit lo
|
||||
marca con `fecha_del_padre` (su tabla no trae fecha: un segmento de EEG, un instrumento
|
||||
aplicado). Uno que sí trae columna de fecha y la trae vacía se queda sin fecha. Uno sin `pac_id` y sin padre (el segmento de un EEG que la
|
||||
carga descartó) no se escribe, ni sus observaciones: se cuenta en `huerfanos` y se avisa. Uno que trae `orden_numero` y no encontró su orden se liga
|
||||
carga descartó) no se escribe, ni sus observaciones: se cuenta en `huerfanos` y se avisa. An observation whose
|
||||
procedure isn't in silver (it attaches to another row's procedure, which didn't enter) isn't written either. Uno que trae `orden_numero` y no encontró su orden se liga
|
||||
a ella cuando llega, aunque sea en otro lote.
|
||||
"""
|
||||
|
||||
@@ -24,12 +25,12 @@ import logging
|
||||
|
||||
from sqlmodel import Session, SQLModel, select
|
||||
|
||||
registro = logging.getLogger(__name__)
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
LLAVE = ("fuente_tabla", "fuente_id", "estudio_id", "clase")
|
||||
KEY = ("fuente_tabla", "fuente_id", "estudio_id", "clase")
|
||||
|
||||
|
||||
def guardar_plata_en(
|
||||
def save_silver_in(
|
||||
sesion: Session, plata, *, procedimiento: type[SQLModel], observacion: type[SQLModel], carga_id: int
|
||||
) -> dict[str, int]:
|
||||
"""Escribe los procedimientos y las observaciones del lote. Devuelve cuántos se agregaron y cuántos cambiaron.
|
||||
@@ -43,18 +44,19 @@ def guardar_plata_en(
|
||||
"huerfanos"), 0
|
||||
)
|
||||
huerfanos: set = set()
|
||||
huerfanas = 0
|
||||
nuevos: set = set()
|
||||
tocados: set = set()
|
||||
existentes = {tuple(getattr(fila, c) for c in LLAVE): fila for fila in sesion.exec(select(procedimiento))}
|
||||
existentes = {tuple(getattr(fila, c) for c in KEY): fila for fila in sesion.exec(select(procedimiento))}
|
||||
ordenes: dict[int, SQLModel] = {}
|
||||
for fila in sorted(existentes.values(), key=lambda f: f.procedimiento_id):
|
||||
if fila.clase == "orden" and fila.numero_hospital is not None:
|
||||
ordenes.setdefault(fila.numero_hospital, fila)
|
||||
|
||||
for p in plata.procedimientos:
|
||||
padre = _padre(p["padres"], existentes, ordenes)
|
||||
padre = _parent(p["padres"], existentes, ordenes)
|
||||
datos = {c: v for c, v in p.items() if c not in ("llave", "padres", "fecha_del_padre")}
|
||||
datos.update(dict(zip(LLAVE, p["llave"])))
|
||||
datos.update(dict(zip(KEY, p["llave"])))
|
||||
datos["padre_id"] = None if padre is None else padre.procedimiento_id
|
||||
if datos.get("pac_id") is None:
|
||||
if padre is None:
|
||||
@@ -71,12 +73,12 @@ def guardar_plata_en(
|
||||
existentes[p["llave"]] = fila
|
||||
cuenta["procedimientos_nuevos"] += 1
|
||||
nuevos.add(p["llave"])
|
||||
elif _actualizar(fila, datos, carga_id):
|
||||
elif _update(fila, datos, carga_id):
|
||||
cuenta["procedimientos_cambiados"] += 1
|
||||
tocados.add(p["llave"])
|
||||
if fila.clase == "orden" and fila.numero_hospital is not None:
|
||||
ordenes.setdefault(fila.numero_hospital, fila)
|
||||
ligados_tarde = _ligar_con_su_orden(existentes.values(), ordenes, carga_id)
|
||||
ligados_tarde = _link_to_its_order(existentes.values(), ordenes, carga_id)
|
||||
cuenta["procedimientos_cambiados"] += ligados_tarde
|
||||
|
||||
ids = [fila.procedimiento_id for fila in existentes.values()]
|
||||
@@ -85,9 +87,11 @@ def guardar_plata_en(
|
||||
for o in sesion.exec(select(observacion).where(observacion.procedimiento_id.in_(ids)))
|
||||
} if ids else {}
|
||||
for o in plata.observaciones:
|
||||
if o["procedimiento"] in huerfanos:
|
||||
dueno = existentes.get(o["procedimiento"])
|
||||
if dueno is None:
|
||||
# Its procedure didn't enter: it was an orphan, or it's the row of another table it attaches to.
|
||||
huerfanas += 1
|
||||
continue
|
||||
dueno = existentes[o["procedimiento"]]
|
||||
datos = {c: v for c, v in o.items() if c != "procedimiento"}
|
||||
datos["procedimiento_id"] = dueno.procedimiento_id
|
||||
if datos.get("pac_id") is None:
|
||||
@@ -96,7 +100,7 @@ def guardar_plata_en(
|
||||
if fila is None:
|
||||
sesion.add(observacion.model_validate({**datos, "carga_id": carga_id}))
|
||||
cuenta["observaciones_nuevas"] += 1
|
||||
elif _actualizar(fila, datos, carga_id):
|
||||
elif _update(fila, datos, carga_id):
|
||||
cuenta["observaciones_cambiadas"] += 1
|
||||
else:
|
||||
continue
|
||||
@@ -106,16 +110,18 @@ def guardar_plata_en(
|
||||
cuenta["huerfanos"] = len(huerfanos)
|
||||
cuenta["procedimientos_tocados"] = len(tocados) + ligados_tarde
|
||||
if huerfanos:
|
||||
registro.warning("%d procedimientos sin paciente ni padre no se escribieron (p. ej. %s).",
|
||||
log.warning("%d procedimientos sin paciente ni padre no se escribieron (p. ej. %s).",
|
||||
len(huerfanos), sorted(huerfanos)[0])
|
||||
if huerfanas:
|
||||
log.warning("%d observations whose procedure isn't in silver weren't written.", huerfanas)
|
||||
return cuenta
|
||||
|
||||
|
||||
def _ligar_con_su_orden(procedimientos, ordenes: dict, carga_id: int) -> int:
|
||||
def _link_to_its_order(procedimientos, ordenes: dict, carga_id: int) -> int:
|
||||
"""Los procedimientos sin padre que traen un número de orden, ligados a la orden que ya llegó.
|
||||
|
||||
Las órdenes pueden llegar en un lote posterior al de sus tomas (en CaCu, las tomas en
|
||||
`cargar` y las órdenes en `cargar_resultados`). Devuelve cuántos se ligaron.
|
||||
`load` y las órdenes en `cargar_resultados`). Devuelve cuántos se ligaron.
|
||||
"""
|
||||
ligados = 0
|
||||
for fila in procedimientos:
|
||||
@@ -127,7 +133,7 @@ def _ligar_con_su_orden(procedimientos, ordenes: dict, carga_id: int) -> int:
|
||||
return ligados
|
||||
|
||||
|
||||
def _padre(padres, existentes: dict, ordenes: dict):
|
||||
def _parent(padres, existentes: dict, ordenes: dict):
|
||||
"""El primer padre que se encuentre: por su llave, o la orden por su número del hospital."""
|
||||
for llave in padres:
|
||||
fila = ordenes.get(llave[1]) if llave[0] == "orden" and len(llave) == 2 else existentes.get(tuple(llave))
|
||||
@@ -136,7 +142,7 @@ def _padre(padres, existentes: dict, ordenes: dict):
|
||||
return None
|
||||
|
||||
|
||||
def _actualizar(fila: SQLModel, datos: dict, carga_id: int) -> bool:
|
||||
def _update(fila: SQLModel, datos: dict, carga_id: int) -> bool:
|
||||
"""Pone en la fila lo que cambió; si algo cambió, también su `carga_id`. Devuelve si cambió."""
|
||||
cambios = {c: v for c, v in datos.items() if getattr(fila, c) != v}
|
||||
for columna, valor in cambios.items():
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Silver: `cat_sistema_fuente` and `cat_mapeo`, how each source writes the catalog's codes.
|
||||
|
||||
The rows are the system of record: a deploy only adds the seed rows that are missing (`seed`), the application adds
|
||||
the rest (`add`) and closes a row instead of deleting it (`close`). The rule that the mapping is a function lives in
|
||||
the caller and runs in `add`'s session, against the rows already stored for the same form.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import date
|
||||
|
||||
from sqlmodel import Session, SQLModel, select
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
# The columns that say which form of which source a row maps: rows that share them describe the same form.
|
||||
FORM_KEY = ("sistema_fuente_id", "clase", "resultado_id", "estudio_id", "forma_normalizada")
|
||||
|
||||
|
||||
class SourceMappingRepository(Repository):
|
||||
"""A domain's source systems and mappings. `get`, `list` and `count` read the mappings."""
|
||||
|
||||
def __init__(self, session_factory: Callable[[], Session], sistema: type[SQLModel], mapeo: type[SQLModel]):
|
||||
super().__init__(session_factory, mapeo)
|
||||
self.sistema = sistema
|
||||
|
||||
def systems(self) -> list[SQLModel]:
|
||||
with self._session_factory() as sesion:
|
||||
return list(sesion.exec(select(self.sistema).order_by(self.sistema.sistema_fuente_id)))
|
||||
|
||||
def ensure_system(self, fila: SQLModel) -> bool:
|
||||
"""Adds the source system if it isn't there; an existing one is left as it is. True if added."""
|
||||
with self._session_factory() as sesion:
|
||||
if sesion.get(self.sistema, fila.sistema_fuente_id) is not None:
|
||||
return False
|
||||
sesion.add(fila)
|
||||
sesion.commit()
|
||||
return True
|
||||
|
||||
def forms(self, **igual_a) -> list[SQLModel]:
|
||||
"""The mappings whose columns equal the given values (`sistema_fuente_id=`, `resultado_id=`...)."""
|
||||
consulta = select(self.model)
|
||||
for columna, valor in igual_a.items():
|
||||
consulta = consulta.where(getattr(self.model, columna) == valor)
|
||||
with self._session_factory() as sesion:
|
||||
return list(sesion.exec(consulta.order_by(self.model.mapeo_id)))
|
||||
|
||||
def seed(self, filas: Iterable[SQLModel]) -> int:
|
||||
"""Adds each row whose form has no row yet, in force or not; never changes a stored one. Returns how many."""
|
||||
filas = list(filas)
|
||||
with self._session_factory() as sesion:
|
||||
guardadas = {_key(f) for f in sesion.exec(select(self.model))}
|
||||
nuevas = []
|
||||
for fila in filas:
|
||||
if _key(fila) not in guardadas:
|
||||
guardadas.add(_key(fila))
|
||||
nuevas.append(fila)
|
||||
sesion.add_all(nuevas)
|
||||
sesion.commit()
|
||||
return len(nuevas)
|
||||
|
||||
def add(self, fila: SQLModel, *, check: Callable[[list[SQLModel], SQLModel], None] | None = None) -> SQLModel:
|
||||
"""Adds one mapping. `check` gets the rows stored for the same form and the new one, in the same session, and
|
||||
raises to reject it."""
|
||||
with self._session_factory() as sesion:
|
||||
if check is not None:
|
||||
misma_forma = select(self.model).where(
|
||||
self.model.sistema_fuente_id == fila.sistema_fuente_id, self.model.clase == fila.clase,
|
||||
self.model.forma_normalizada == fila.forma_normalizada)
|
||||
check(list(sesion.exec(misma_forma)), fila)
|
||||
sesion.add(fila)
|
||||
sesion.commit()
|
||||
sesion.refresh(fila)
|
||||
return fila
|
||||
|
||||
def close(self, mapeo_id: int, hasta: date) -> SQLModel:
|
||||
"""Ends a mapping's validity on `hasta`. A row already closed keeps its end."""
|
||||
with self._session_factory() as sesion:
|
||||
fila = sesion.get(self.model, mapeo_id)
|
||||
if fila is None:
|
||||
raise KeyError(f"cat_mapeo {mapeo_id} no existe.")
|
||||
if fila.vigente_hasta is None:
|
||||
fila.vigente_hasta = hasta
|
||||
sesion.add(fila)
|
||||
sesion.commit()
|
||||
sesion.refresh(fila)
|
||||
return fila
|
||||
|
||||
|
||||
def _key(fila: SQLModel) -> tuple:
|
||||
return tuple(getattr(fila, c) for c in FORM_KEY)
|
||||
+14
-9
@@ -1,8 +1,8 @@
|
||||
"""Silver: each patient's timeline of procedures and observations, under a fixed column contract.
|
||||
|
||||
The query is injected. Each domain module binds dbt's view (`persistance.aristas.dbt`); another query, such as
|
||||
the indicator kit's `linea_de_tiempo_plata`, can still be bound with `with_query`. Readers keep the same columns and
|
||||
filters.
|
||||
The query is injected. Each domain module binds dbt's view (`persistance.edges.dbt`), which the orchestration,
|
||||
the cohort builds, the models' pipelines and the measures' strata all read; a test can bind another with
|
||||
`with_query`. Readers keep the same columns and filters.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
@@ -11,7 +11,7 @@ from typing import Protocol
|
||||
|
||||
from sqlalchemy import Select
|
||||
|
||||
from persistance.materializador import SesionDeLectura
|
||||
from persistance.materializer import ReadSession
|
||||
from persistance.repository import Repository
|
||||
|
||||
TIMELINE_COLUMNS = (
|
||||
@@ -48,6 +48,14 @@ class TimelineRepository(Repository):
|
||||
"""The same repository, reading through `query`."""
|
||||
return TimelineRepository(self._session_factory, query)
|
||||
|
||||
def query(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
||||
known_until: datetime | None = None) -> Select:
|
||||
"""The `select` `read` runs, for a caller that runs it on its own session (a cohort build, in its write)."""
|
||||
if self._query is None:
|
||||
raise TimelineQueryMissing("bind a timeline query with `with_query` before reading")
|
||||
return self._query(patients=None if patients is None else list(patients), until=until,
|
||||
known_until=known_until)
|
||||
|
||||
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
||||
known_until: datetime | None = None) -> list[dict]:
|
||||
"""One dict per event, keyed by `TIMELINE_COLUMNS`, in the query's order.
|
||||
@@ -55,12 +63,9 @@ class TimelineRepository(Repository):
|
||||
`until` keeps events up to that clinical date; `known_until` keeps rows already loaded at that
|
||||
moment. The query runs on a read-only session.
|
||||
"""
|
||||
if self._query is None:
|
||||
raise TimelineQueryMissing("bind a timeline query with `with_query` before reading")
|
||||
query = self._query(patients=None if patients is None else list(patients), until=until,
|
||||
known_until=known_until)
|
||||
query = self.query(patients=patients, until=until, known_until=known_until)
|
||||
with self._session_factory() as session:
|
||||
result = SesionDeLectura(session).execute(query)
|
||||
result = ReadSession(session).execute(query)
|
||||
columns = tuple(result.keys())
|
||||
if columns != TIMELINE_COLUMNS:
|
||||
raise TimelineContractError(f"expected columns {TIMELINE_COLUMNS}, got {columns}")
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
"""Plata: las vistas de un dominio (desde F6, solo `v_persona`; ADR-MD-009).
|
||||
|
||||
Las define el kit, como sentencias DDL ya armadas y en orden (`indicadores_kit.esquema.ddl_de_vistas`);
|
||||
Las define el ciclo, como sentencias DDL ya armadas y en orden (`webapi.orchestration.silver.views`, dbt's views);
|
||||
aquí solo se ejecutan, en una transacción.
|
||||
"""
|
||||
|
||||
@@ -12,13 +12,13 @@ from sqlalchemy.sql.expression import Executable
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class VistasRepository(Repository):
|
||||
class ViewsRepository(Repository):
|
||||
"""Las vistas no tienen modelo: se crean o reemplazan con la DDL que se recibe."""
|
||||
|
||||
def __init__(self, session_factory):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def construir(self, ddl: Iterable[Executable]) -> list[str]:
|
||||
def build_all(self, ddl: Iterable[Executable]) -> list[str]:
|
||||
"""Ejecuta cada sentencia en orden, en una transacción. Devuelve los nombres de las vistas de la base."""
|
||||
with self._session_factory() as sesion:
|
||||
conexion = sesion.connection()
|
||||
+14
-14
@@ -1,11 +1,11 @@
|
||||
"""El materializador de MD-20 (T0; ADR-MD-009): la E/S de una transformación.
|
||||
|
||||
Una transformación es una función pura del kit que lee por una `SesionDeLectura` y devuelve
|
||||
Una transformación es una función pura del kit que lee por una `ReadSession` y devuelve
|
||||
lo que hay que escribir. El materializador abre una sola sesión, se la da a la función de
|
||||
solo lectura, escribe lo que devolvió con un **cuerpo** y hace un solo commit, el del cuerpo.
|
||||
Sin cuerpo, solo lee: es una prueba o una lectura.
|
||||
|
||||
Es lo mismo que hace cada subclase de repositorio de `persistance/aristas/`, una sola vez:
|
||||
Es lo mismo que hace cada subclase de repositorio de `persistance/edges/`, una sola vez:
|
||||
el cuerpo es lo único que cambia de una a otra. Convive con ellas hasta MD-20 T2.
|
||||
"""
|
||||
|
||||
@@ -15,18 +15,18 @@ from typing import Any, TypeVar
|
||||
from sqlmodel import Session
|
||||
|
||||
T = TypeVar("T")
|
||||
Cuerpo = Callable[[Session, Any], Any]
|
||||
Body = Callable[[Session, Any], Any]
|
||||
|
||||
|
||||
class SoloLectura(RuntimeError):
|
||||
class ReadOnly(RuntimeError):
|
||||
"""Una transformación quiso escribir por la sesión que solo le da para leer."""
|
||||
|
||||
|
||||
class SesionDeLectura:
|
||||
class ReadSession:
|
||||
"""La sesión que recibe una transformación: lee como una `Session` y no puede escribir.
|
||||
|
||||
`add`, `add_all`, `delete`, `merge`, `flush`, `commit` y un `exec`/`execute` de INSERT,
|
||||
UPDATE o DELETE lanzan `SoloLectura`. Lo demás (`exec`, `execute`, `get`, `scalar`,
|
||||
UPDATE o DELETE lanzan `ReadOnly`. Lo demás (`exec`, `execute`, `get`, `scalar`,
|
||||
`scalars`) va a la sesión de verdad.
|
||||
"""
|
||||
|
||||
@@ -37,35 +37,35 @@ class SesionDeLectura:
|
||||
self._sesion = sesion
|
||||
|
||||
def exec(self, consulta, *args, **kwargs):
|
||||
return self._sesion.exec(self._solo_lectura(consulta), *args, **kwargs)
|
||||
return self._sesion.exec(self._read_only(consulta), *args, **kwargs)
|
||||
|
||||
def execute(self, consulta, *args, **kwargs):
|
||||
return self._sesion.execute(self._solo_lectura(consulta), *args, **kwargs)
|
||||
return self._sesion.execute(self._read_only(consulta), *args, **kwargs)
|
||||
|
||||
def __getattr__(self, nombre: str):
|
||||
if nombre in self._ESCRIBEN:
|
||||
raise SoloLectura(f"Una transformación no escribe: `{nombre}` en una SesionDeLectura.")
|
||||
raise ReadOnly(f"Una transformación no escribe: `{nombre}` en una SesionDeLectura.")
|
||||
return getattr(self._sesion, nombre)
|
||||
|
||||
@staticmethod
|
||||
def _solo_lectura(consulta):
|
||||
def _read_only(consulta):
|
||||
if getattr(consulta, "is_dml", False) and not getattr(consulta, "is_select", False):
|
||||
raise SoloLectura(f"Una transformación no escribe: {type(consulta).__name__} en una SesionDeLectura.")
|
||||
raise ReadOnly(f"Una transformación no escribe: {type(consulta).__name__} en una SesionDeLectura.")
|
||||
return consulta
|
||||
|
||||
|
||||
class Materializador:
|
||||
class Materializer:
|
||||
"""La E/S de las transformaciones de un dominio: una sesión, la función, el cuerpo y un commit."""
|
||||
|
||||
def __init__(self, session_factory: Callable[[], Session]):
|
||||
self._session_factory = session_factory
|
||||
|
||||
def materializar(self, funcion: Callable[[SesionDeLectura], T], cuerpo: Cuerpo | None = None):
|
||||
def materialize(self, funcion: Callable[[ReadSession], T], cuerpo: Body | None = None):
|
||||
"""`funcion(sesion_de_lectura)` y, con `cuerpo`, `cuerpo(sesion, lo_que_devolvio)` (escribe y hace commit).
|
||||
|
||||
Devuelve lo que devuelve el cuerpo (su resumen), o lo que devolvió la función si no hay cuerpo.
|
||||
"""
|
||||
with self._session_factory() as sesion:
|
||||
datos = funcion(SesionDeLectura(sesion))
|
||||
datos = funcion(ReadSession(sesion))
|
||||
return datos if cuerpo is None else cuerpo(sesion, datos)
|
||||
|
||||
@@ -2,7 +2,9 @@ from core.tea.indicadores.models import (
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CatEstudio,
|
||||
CatMapeo,
|
||||
CatResultado,
|
||||
CatSistemaFuente,
|
||||
CatValor,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
@@ -29,65 +31,68 @@ from core.tea.indicadores.models import (
|
||||
Persona,
|
||||
)
|
||||
from core.tea.models import (
|
||||
AntecedentesMaternosGestacion,
|
||||
EegEstudio,
|
||||
EegSegmento,
|
||||
EvaluacionPsicologica,
|
||||
InstrumentoAplicado,
|
||||
NotaMedica,
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
PartoNeonatal,
|
||||
PotencialesEvocadosAuditivos,
|
||||
)
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
from persistance.edges.bronze import StagingRepository
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.edges.common import ReferenceRepository
|
||||
from persistance.materializer import Materializer
|
||||
from persistance.edges.gold import (
|
||||
CalculationRepository,
|
||||
CohortRepository,
|
||||
MeasureHistoryRepository,
|
||||
MeasureReportRepository,
|
||||
PublicationRepository,
|
||||
)
|
||||
from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
SourceMappingRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.db import get_tea_session
|
||||
from persistance.repository import Repository
|
||||
|
||||
pacientes_repository = Repository(get_tea_session, Pacientes)
|
||||
ordenes_estudio_repository = Repository(get_tea_session, OrdenesEstudio)
|
||||
nota_medica_repository = Repository(get_tea_session, NotaMedica)
|
||||
evaluacion_psicologica_repository = Repository(get_tea_session, EvaluacionPsicologica)
|
||||
potenciales_evocados_auditivos_repository = Repository(get_tea_session, PotencialesEvocadosAuditivos)
|
||||
eeg_estudio_repository = Repository(get_tea_session, EegEstudio)
|
||||
eeg_segmento_repository = Repository(get_tea_session, EegSegmento)
|
||||
antecedentes_maternos_gestacion_repository = Repository(get_tea_session, AntecedentesMaternosGestacion)
|
||||
parto_neonatal_repository = Repository(get_tea_session, PartoNeonatal)
|
||||
instrumento_aplicado_repository = Repository(get_tea_session, InstrumentoAplicado)
|
||||
mchat_repository = Repository(get_tea_session, Mchat)
|
||||
ados2_repository = Repository(get_tea_session, Ados2)
|
||||
evaluacion_neuropediatrica_repository = Repository(get_tea_session, EvaluacionNeuropediatrica)
|
||||
eeg_repository = Repository(get_tea_session, Eeg)
|
||||
eeg_metrica_repository = Repository(get_tea_session, EegMetrica)
|
||||
eeg_metrica_electrodo_repository = Repository(get_tea_session, EegMetricaElectrodo)
|
||||
|
||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
||||
persona_repository = Repository(get_tea_session, Persona)
|
||||
periodo_observacion_repository = RegistroRepository(get_tea_session, PeriodoObservacion)
|
||||
carga_repository = CargaRepository(get_tea_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = RegistroRepository(get_tea_session, DefParametro)
|
||||
dim_periodo_repository = RegistroRepository(get_tea_session, DimPeriodo)
|
||||
dim_fecha_repository = RegistroRepository(get_tea_session, DimFecha)
|
||||
dim_grupo_edad_repository = RegistroRepository(get_tea_session, DimGrupoEdad)
|
||||
periodo_observacion_repository = ReferenceRepository(get_tea_session, PeriodoObservacion)
|
||||
carga_repository = LoadRepository(get_tea_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = ReferenceRepository(get_tea_session, DefParametro)
|
||||
dim_periodo_repository = ReferenceRepository(get_tea_session, DimPeriodo)
|
||||
dim_fecha_repository = ReferenceRepository(get_tea_session, DimFecha)
|
||||
dim_grupo_edad_repository = ReferenceRepository(get_tea_session, DimGrupoEdad)
|
||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||
cat_measure_repository = RegistroRepository(get_tea_session, CatMeasure)
|
||||
cat_measure_resultado_repository = RegistroRepository(get_tea_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = RegistroRepository(get_tea_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = RegistroRepository(get_tea_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = RegistroRepository(get_tea_session, CatEstrato)
|
||||
cat_estrato_valor_repository = RegistroRepository(get_tea_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = RegistroRepository(get_tea_session, CatMeasureEstrato)
|
||||
publicacion_repository = PublicacionRepository(
|
||||
cat_measure_repository = ReferenceRepository(get_tea_session, CatMeasure)
|
||||
cat_measure_resultado_repository = ReferenceRepository(get_tea_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = ReferenceRepository(get_tea_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = ReferenceRepository(get_tea_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = ReferenceRepository(get_tea_session, CatEstrato)
|
||||
cat_estrato_valor_repository = ReferenceRepository(get_tea_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = ReferenceRepository(get_tea_session, CatMeasureEstrato)
|
||||
publication_repository = PublicationRepository(
|
||||
get_tea_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||
)
|
||||
measure_report_unidad_repository = Repository(get_tea_session, MeasureReportUnidad)
|
||||
@@ -99,20 +104,24 @@ cat_valor_repository = Repository(get_tea_session, CatValor)
|
||||
procedimiento_repository = Repository(get_tea_session, Procedimiento)
|
||||
observacion_repository = Repository(get_tea_session, Observacion)
|
||||
|
||||
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(get_tea_session)
|
||||
catalogo_repository = CatalogoRepository(get_tea_session, CatEstudio, CatResultado, CatValor)
|
||||
calculo_repository = CalculoRepository(get_tea_session, MeasureReport, periodo=DimPeriodo)
|
||||
observar_repository = ObservacionRepository(get_tea_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_tea_session)
|
||||
vinculos_repository = VinculosRepository(get_tea_session)
|
||||
catalog_repository = CatalogRepository(get_tea_session, CatEstudio, CatResultado, CatValor)
|
||||
source_mapping_repository = SourceMappingRepository(get_tea_session, CatSistemaFuente, CatMapeo)
|
||||
calculation_repository = CalculationRepository(get_tea_session, MeasureReport, periodo=DimPeriodo)
|
||||
history_repository = MeasureHistoryRepository(get_tea_session, MeasureReport, unit_model=MeasureReportUnidad,
|
||||
stratum_model=MeasureReportUnidadEstrato,
|
||||
value_model=CatEstratoValor)
|
||||
observation_period_repository = ObservationRepository(get_tea_session, PeriodoObservacion)
|
||||
views_repository = ViewsRepository(get_tea_session)
|
||||
links_repository = LinksRepository(get_tea_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_tea_session, "tea")
|
||||
dbt_query_repository = DbtQueryRepository(get_tea_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
cohort_repository = CohortRepository(
|
||||
get_tea_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
)
|
||||
|
||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||
materializador = Materializador(get_tea_session)
|
||||
materializer = Materializer(get_tea_session)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""source terminology
|
||||
|
||||
`cat_sistema_fuente` (who sends the data) and `cat_mapeo` (how each source writes the catalog's codes). Both start
|
||||
empty; the `catalogs` step seeds the catalog's own mappings, and the application adds the rest.
|
||||
|
||||
Revision ID: 6d772e9a342f
|
||||
Revises: f2b6d1e8c934
|
||||
Create Date: 2026-11-13 18:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
import core.indicadores.tipos
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '6d772e9a342f'
|
||||
down_revision = 'f2b6d1e8c934'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('cat_sistema_fuente',
|
||||
sa.Column('sistema_fuente_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('etiqueta', sa.String(), nullable=False),
|
||||
sa.Column('fuente_tabla', sa.String(length=64), nullable=True),
|
||||
sa.Column('vigente_desde', sa.Date(), nullable=False),
|
||||
sa.Column('vigente_hasta', sa.Date(), nullable=True),
|
||||
sa.CheckConstraint('vigente_hasta IS NULL OR vigente_hasta >= vigente_desde', name='ck_cat_sistema_fuente_vigencia'),
|
||||
sa.PrimaryKeyConstraint('sistema_fuente_id')
|
||||
)
|
||||
op.create_table('cat_mapeo',
|
||||
sa.Column('mapeo_id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('sistema_fuente_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('clase', sa.String(length=16), nullable=False),
|
||||
sa.Column('forma', sa.String(length=255), nullable=False),
|
||||
sa.Column('forma_normalizada', sa.String(length=255), nullable=False),
|
||||
sa.Column('estudio_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('resultado_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('valor_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('vigente_desde', sa.Date(), nullable=False),
|
||||
sa.Column('vigente_hasta', sa.Date(), nullable=True),
|
||||
sa.Column('registrado_por', sa.String(length=64), nullable=False),
|
||||
sa.Column('registrado_en', core.indicadores.tipos.FechaHoraUTC(), nullable=False),
|
||||
sa.Column('motivo', sa.String(), nullable=True),
|
||||
sa.CheckConstraint("clase IN ('estudio', 'etiqueta', 'valor')", name='ck_cat_mapeo_clase'),
|
||||
sa.CheckConstraint("(clase = 'estudio' AND estudio_id IS NOT NULL AND resultado_id IS NULL AND valor_id IS NULL)"
|
||||
" OR (clase = 'etiqueta' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NULL)"
|
||||
" OR (clase = 'valor' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NOT NULL)",
|
||||
name='ck_cat_mapeo_destino'),
|
||||
sa.CheckConstraint('vigente_hasta IS NULL OR vigente_hasta >= vigente_desde', name='ck_cat_mapeo_vigencia'),
|
||||
sa.ForeignKeyConstraint(['sistema_fuente_id'], ['cat_sistema_fuente.sistema_fuente_id'], ),
|
||||
sa.ForeignKeyConstraint(['estudio_id'], ['cat_estudio.estudio_id'], ),
|
||||
sa.ForeignKeyConstraint(['resultado_id'], ['cat_resultado.resultado_id'], ),
|
||||
sa.ForeignKeyConstraint(['resultado_id', 'valor_id'], ['cat_valor.resultado_id', 'cat_valor.valor_id'], name='fk_cat_mapeo_valor'),
|
||||
sa.PrimaryKeyConstraint('mapeo_id'),
|
||||
sa.UniqueConstraint('sistema_fuente_id', 'clase', 'resultado_id', 'estudio_id', 'forma_normalizada', 'vigente_desde', name='uq_cat_mapeo')
|
||||
)
|
||||
op.create_index('ix_cat_mapeo_busqueda', 'cat_mapeo', ['sistema_fuente_id', 'resultado_id', 'forma_normalizada'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index('ix_cat_mapeo_busqueda', table_name='cat_mapeo')
|
||||
op.drop_table('cat_mapeo')
|
||||
op.drop_table('cat_sistema_fuente')
|
||||
@@ -0,0 +1,28 @@
|
||||
"""tea order pdf
|
||||
|
||||
`ordenes_estudio.ord_pdf_blob` holds the report of the study an order asks for, as a PDF.
|
||||
|
||||
Revision ID: a7d3c9e5b160
|
||||
Revises: f2b6d1e8c934
|
||||
Create Date: 2026-11-13 10:12:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'a7d3c9e5b160'
|
||||
down_revision = 'f2b6d1e8c934'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('ordenes_estudio', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('ord_pdf_blob', sa.LargeBinary().with_variant(mysql.LONGBLOB(), 'mariadb').with_variant(mysql.LONGBLOB(), 'mysql'), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('ordenes_estudio', schema=None) as batch_op:
|
||||
batch_op.drop_column('ord_pdf_blob')
|
||||
@@ -0,0 +1,24 @@
|
||||
"""tea heads joined
|
||||
|
||||
The source-terminology tables and `ordenes_estudio.ord_pdf_blob` were added on separate lines from the same
|
||||
revision; this joins them so the chain has one head again. Nothing to change on any engine.
|
||||
|
||||
Revision ID: b9e4d2c71a05
|
||||
Revises: 6d772e9a342f, a7d3c9e5b160
|
||||
Create Date: 2026-11-15 00:50:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b9e4d2c71a05'
|
||||
down_revision = ('6d772e9a342f', 'a7d3c9e5b160')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -0,0 +1,486 @@
|
||||
"""tea staging by study
|
||||
|
||||
One staging table per kind of study: `mchat`, `ados2`, `evaluacion_neuropediatrica` and `eeg`, with the EEG's
|
||||
metrics and electrode values from its analysis (`eeg_metrica`, `eeg_metrica_electrodo`). `pacientes` and
|
||||
`ordenes_estudio` keep their rows and lose the columns nothing reads; the orders' study codes move to the new
|
||||
catalog (`ADOS2`, `NEUROPEDIATRIA`, `EEG`). The psychological evaluation, instruments, EEG segments, auditory
|
||||
evoked potentials, birth, maternal history and medical notes go, with their rows: staging is reloaded from the
|
||||
source.
|
||||
|
||||
Revision ID: f2b6d1e8c934
|
||||
Revises: a3e1c7b90d12
|
||||
Create Date: 2026-11-12 13:44:52.541497
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'f2b6d1e8c934'
|
||||
down_revision = 'a3e1c7b90d12'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
# The orders' study codes, old -> new.
|
||||
STUDY_CODES = {"EVALUACION_PSICOLOGICA_TEA": "ADOS2", "ELECTROENCEFALOGRAMA": "EEG"}
|
||||
|
||||
|
||||
def _recode(codes: dict[str, str]) -> None:
|
||||
orders = sa.table("ordenes_estudio", sa.column("ord_tipo_estudio", sa.Text()))
|
||||
for old, new in codes.items():
|
||||
op.execute(orders.update().where(orders.c.ord_tipo_estudio == old).values(ord_tipo_estudio=new))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('ados2',
|
||||
sa.Column('ado_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('ado_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('ado_fecha', sa.Date(), nullable=True),
|
||||
sa.Column('ado_modulo', sa.Text(), nullable=True),
|
||||
sa.Column('ado_algoritmo', sa.Text(), nullable=True),
|
||||
sa.Column('ado_css', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_clasificacion', sa.Text(), nullable=True),
|
||||
sa.Column('ado_sa_a2', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_a6', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_a7', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_a8', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b1', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b2', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b3', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b4', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b5', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b6', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b7', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b8', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b9', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b10', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b11', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b12', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b13', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b14', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b15', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b16b', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b18', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_a3', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_a4', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_a5', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_d1', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_d2', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_d4', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_d5', sa.Integer(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('ado_id')
|
||||
)
|
||||
op.create_table('eeg',
|
||||
sa.Column('eeg_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('eeg_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_id_registro_laboratorio', sa.String(length=64), nullable=True),
|
||||
sa.Column('eeg_fecha_estudio', sa.Date(), nullable=True),
|
||||
sa.Column('eeg_con_sueno', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_canales', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_duracion_min', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_canales_amplitud', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_canales_alta_frecuencia', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_canales_correlacion', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_canales_sin_senal', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_ruido_linea_db', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_estudio', sa.LargeBinary().with_variant(mysql.LONGBLOB(), 'mariadb').with_variant(mysql.LONGBLOB(), 'mysql'), nullable=True),
|
||||
sa.PrimaryKeyConstraint('eeg_id')
|
||||
)
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_eeg_eeg_id_registro_laboratorio'), ['eeg_id_registro_laboratorio'], unique=False)
|
||||
|
||||
op.create_table('eeg_metrica',
|
||||
sa.Column('met_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('met_eeg_id', sa.Text(), nullable=True),
|
||||
sa.Column('met_codigo', sa.Text(), nullable=True),
|
||||
sa.Column('met_valor', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('met_id')
|
||||
)
|
||||
op.create_table('eeg_metrica_electrodo',
|
||||
sa.Column('mel_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('mel_met_id', sa.Text(), nullable=True),
|
||||
sa.Column('mel_electrodo', sa.Text(), nullable=True),
|
||||
sa.Column('mel_valor', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('mel_id')
|
||||
)
|
||||
op.create_table('evaluacion_neuropediatrica',
|
||||
sa.Column('neu_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('neu_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('neu_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('neu_fecha', sa.Date(), nullable=True),
|
||||
sa.Column('neu_cie_codigo', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('neu_id')
|
||||
)
|
||||
op.create_table('mchat',
|
||||
sa.Column('mch_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('mch_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('mch_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('mch_fecha', sa.Date(), nullable=True),
|
||||
sa.Column('mch_puntaje', sa.Integer(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('mch_id')
|
||||
)
|
||||
op.drop_table('evaluacion_psicologica')
|
||||
with op.batch_alter_table('nota_medica', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nota_medica_nm_id_hospital'))
|
||||
|
||||
op.drop_table('nota_medica')
|
||||
with op.batch_alter_table('eeg_estudio', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_eeg_estudio_eeg_id_registro_laboratorio'))
|
||||
|
||||
op.drop_table('eeg_estudio')
|
||||
op.drop_table('parto_neonatal')
|
||||
op.drop_table('potenciales_evocados_auditivos')
|
||||
op.drop_table('antecedentes_maternos_gestacion')
|
||||
op.drop_table('eeg_segmento')
|
||||
op.drop_table('instrumento_aplicado')
|
||||
with op.batch_alter_table('ordenes_estudio', schema=None) as batch_op:
|
||||
batch_op.drop_column('ord_nota_medica_id')
|
||||
batch_op.drop_column('ord_proveedor')
|
||||
batch_op.drop_column('ord_fecha_resultado')
|
||||
batch_op.drop_column('ord_especialidad')
|
||||
batch_op.drop_column('ord_ventana_madurativa')
|
||||
batch_op.drop_column('ord_diagnostico_asignado')
|
||||
batch_op.drop_column('ord_estatus')
|
||||
batch_op.drop_column('ord_pdf_ruta')
|
||||
batch_op.drop_column('ord_updated_at')
|
||||
batch_op.drop_column('ord_dias_vigencia')
|
||||
batch_op.drop_column('ord_fecha_realizacion')
|
||||
batch_op.drop_column('ord_fuente_sistema')
|
||||
batch_op.drop_column('ord_medico_solicitante')
|
||||
batch_op.drop_column('ord_cie_asignado')
|
||||
batch_op.drop_column('ord_fecha_vencimiento')
|
||||
batch_op.drop_column('ord_created_at')
|
||||
batch_op.drop_column('ord_dias_espera')
|
||||
batch_op.drop_column('ord_edad_meses')
|
||||
batch_op.drop_column('ord_observaciones')
|
||||
|
||||
with op.batch_alter_table('pacientes', schema=None) as batch_op:
|
||||
batch_op.drop_column('pac_fuente_sistema')
|
||||
batch_op.drop_column('pac_dependencia')
|
||||
batch_op.drop_column('pac_parentesco')
|
||||
batch_op.drop_column('pac_codigo_postal_vigente')
|
||||
batch_op.drop_column('pac_created_at')
|
||||
batch_op.drop_column('pac_sexo')
|
||||
batch_op.drop_column('pac_updated_at')
|
||||
batch_op.drop_column('pac_id_titular')
|
||||
|
||||
_recode(STUDY_CODES)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('pacientes', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('pac_id_titular', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_updated_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_sexo', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_created_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_codigo_postal_vigente', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_parentesco', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_dependencia', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_fuente_sistema', sa.Text(), nullable=True))
|
||||
|
||||
with op.batch_alter_table('ordenes_estudio', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('ord_observaciones', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_edad_meses', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_dias_espera', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_created_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_fecha_vencimiento', sa.Date(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_cie_asignado', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_medico_solicitante', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_fuente_sistema', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_fecha_realizacion', sa.Date(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_dias_vigencia', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_updated_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_pdf_ruta', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_estatus', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_diagnostico_asignado', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_ventana_madurativa', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_especialidad', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_fecha_resultado', sa.Date(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_proveedor', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_nota_medica_id', sa.Text(), nullable=True))
|
||||
|
||||
op.create_table('instrumento_aplicado',
|
||||
sa.Column('ins_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('ins_psi_id', sa.Text(), nullable=True),
|
||||
sa.Column('ins_instrumento', sa.Text(), nullable=True),
|
||||
sa.Column('ins_informante', sa.Text(), nullable=True),
|
||||
sa.Column('ins_area', sa.Text(), nullable=True),
|
||||
sa.Column('ins_interpretacion', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('ins_id')
|
||||
)
|
||||
op.create_table('eeg_segmento',
|
||||
sa.Column('seg_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('seg_eeg_id', sa.Text(), nullable=True),
|
||||
sa.Column('seg_estado', sa.Text(), nullable=True),
|
||||
sa.Column('seg_inicio_s', sa.Float(), nullable=True),
|
||||
sa.Column('seg_fin_s', sa.Float(), nullable=True),
|
||||
sa.Column('seg_duracion_s', sa.Float(), nullable=True),
|
||||
sa.Column('seg_fuente', sa.Text(), nullable=True),
|
||||
sa.Column('seg_frecuencia_flash_hz', sa.Float(), nullable=True),
|
||||
sa.Column('seg_n_destellos', sa.Integer(), nullable=True),
|
||||
sa.Column('seg_cobertura', sa.Float(), nullable=True),
|
||||
sa.Column('seg_rms_uv', sa.Float(), nullable=True),
|
||||
sa.Column('seg_emg', sa.Float(), nullable=True),
|
||||
sa.Column('seg_p2p_max_uv', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('seg_id')
|
||||
)
|
||||
op.create_table('antecedentes_maternos_gestacion',
|
||||
sa.Column('amg_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('amg_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_id_madre_seudonimo', sa.Text(), nullable=True),
|
||||
sa.Column('amg_fuente_antecedente', sa.Text(), nullable=True),
|
||||
sa.Column('amg_flag_vinculo_verificado', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_imc_pregestacional', sa.Float(), nullable=True),
|
||||
sa.Column('amg_categoria_peso_materno', sa.Text(), nullable=True),
|
||||
sa.Column('amg_tabaquismo_gestacion', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_acido_folico_preconcepcional', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_intervalo_intergenesico_meses', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_antecedente_aborto', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_embarazo_multiple', sa.Text(), nullable=True),
|
||||
sa.Column('amg_infeccion_gestacion', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_infeccion_tipo', sa.Text(), nullable=True),
|
||||
sa.Column('amg_infeccion_hospitalizacion', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_diabetes_gestacional', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_hipertension_preeclampsia', sa.Text(), nullable=True),
|
||||
sa.Column('amg_hipotiroidismo', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_hipertiroidismo', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_incompatibilidad_rh', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_crisis_convulsivas', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_proceso_proinflamatorio', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_enfermedad_autoinmune', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_migrana', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_asma', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_hipoxia_materna', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_estres_agudo', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_trastorno_neurologico', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_liquido_amniotico', sa.Text(), nullable=True),
|
||||
sa.Column('amg_medicamentos_gestacion', sa.Text(), nullable=True),
|
||||
sa.Column('amg_farmaco_riesgo_neurodesarrollo', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_observaciones', sa.Text(), nullable=True),
|
||||
sa.Column('amg_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('amg_nlp_version', sa.Text(), nullable=True),
|
||||
sa.Column('amg_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('amg_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('amg_fuente_sistema', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('amg_id')
|
||||
)
|
||||
op.create_table('potenciales_evocados_auditivos',
|
||||
sa.Column('pea_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('pea_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('pea_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('pea_fecha_estudio', sa.Date(), nullable=True),
|
||||
sa.Column('pea_medico_interpreta', sa.Text(), nullable=True),
|
||||
sa.Column('pea_umbral_od', sa.Integer(), nullable=True),
|
||||
sa.Column('pea_umbral_oi', sa.Integer(), nullable=True),
|
||||
sa.Column('pea_latencia_v_od', sa.Float(), nullable=True),
|
||||
sa.Column('pea_latencia_v_oi', sa.Float(), nullable=True),
|
||||
sa.Column('pea_interpico_i_v_od', sa.Float(), nullable=True),
|
||||
sa.Column('pea_interpico_i_v_oi', sa.Float(), nullable=True),
|
||||
sa.Column('pea_grado_hipoacusia', sa.Text(), nullable=True),
|
||||
sa.Column('pea_conclusion_texto', sa.Text(), nullable=True),
|
||||
sa.Column('pea_flag_diferencial_auditivo', sa.Integer(), nullable=True),
|
||||
sa.Column('pea_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('pea_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('pea_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('pea_id')
|
||||
)
|
||||
op.create_table('parto_neonatal',
|
||||
sa.Column('pnn_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('pnn_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_fuente_antecedente', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_tipo_parto', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_complicaciones_intraparto', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_complicacion_tipo', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_peso_nacer_g', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_talla_nacer_cm', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_perimetro_cefalico_nacer_cm', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_edad_gestacional_sem', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_clasificacion_eg', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_tamano_para_eg', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_peso_nacer_zscore', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_apgar_1min', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_apgar_5min', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_ingreso_ucin', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_dias_ucin', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_encefalopatia_hipoxico_isquemica', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_hipotermia_nacer', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_hiperbilirrubinemia', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_fototerapia', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_hipoglucemia_neonatal', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_anoxia', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_sindrome_congenito', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_sindrome_congenito_desc', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_flag_riesgo_neonatal', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_observaciones', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_nlp_version', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('pnn_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('pnn_fuente_sistema', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('pnn_id')
|
||||
)
|
||||
op.create_table('eeg_estudio',
|
||||
sa.Column('eeg_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('eeg_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_reporte_disponible', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_fuente_interpretacion', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_fecha_nacimiento_archivo', sa.Date(), nullable=True),
|
||||
sa.Column('eeg_edad_meses', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_fecha_estudio', sa.Date(), nullable=True),
|
||||
sa.Column('eeg_fecha_reporte', sa.Date(), nullable=True),
|
||||
sa.Column('eeg_dias_respuesta', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_medico_interpreta', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_estado_registro', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_privacion_sueno', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_sedacion', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_sedacion_farmaco', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_duracion_min', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_calidad_tecnica', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_descripcion_senal', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_ritmo_base_frecuencia', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_ritmo_base_amplitud', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_simetria', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_anormalidad_presente', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_actividad_epileptiforme', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_tipo_grafoelemento', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_distribucion_anormalidad', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_localizacion', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_activacion_sueno', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_lentificacion', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_crisis_registradas', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_respuesta_fotoestimulacion', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_conclusion_texto', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_conclusion_categoria', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_id_registro_laboratorio', sa.String(length=64), nullable=True),
|
||||
sa.Column('eeg_pdf_ruta', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_nlp_version', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_utilizable', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_estudio', sa.LargeBinary().with_variant(mysql.LONGBLOB(), 'mariadb').with_variant(mysql.LONGBLOB(), 'mysql'), nullable=True),
|
||||
sa.Column('eeg_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('eeg_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('eeg_id')
|
||||
)
|
||||
with op.batch_alter_table('eeg_estudio', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_eeg_estudio_eeg_id_registro_laboratorio'), ['eeg_id_registro_laboratorio'], unique=False)
|
||||
|
||||
op.create_table('nota_medica',
|
||||
sa.Column('nm_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('nm_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_id_hospital', sa.String(length=64), nullable=True),
|
||||
sa.Column('nm_nota_previa_id', sa.Text(), nullable=True),
|
||||
sa.Column('nm_tipo_nota', sa.Text(), nullable=True),
|
||||
sa.Column('nm_especialidad', sa.Text(), nullable=True),
|
||||
sa.Column('nm_fecha', sa.Date(), nullable=True),
|
||||
sa.Column('nm_edad_meses', sa.Float(), nullable=True),
|
||||
sa.Column('nm_ventana_madurativa', sa.Text(), nullable=True),
|
||||
sa.Column('nm_medico_tratante', sa.Text(), nullable=True),
|
||||
sa.Column('nm_motivo_consulta', sa.Text(), nullable=True),
|
||||
sa.Column('nm_interrogatorio', sa.Text(), nullable=True),
|
||||
sa.Column('nm_regresion_referida', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_antecedente_familiar_tea', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_perimetro_cefalico', sa.Float(), nullable=True),
|
||||
sa.Column('nm_diagnostico_texto', sa.Text(), nullable=True),
|
||||
sa.Column('nm_cie_codigo', sa.Text(), nullable=True),
|
||||
sa.Column('nm_cie_descripcion', sa.Text(), nullable=True),
|
||||
sa.Column('nm_tratamiento_texto', sa.Text(), nullable=True),
|
||||
sa.Column('nm_receta', sa.Text(), nullable=True),
|
||||
sa.Column('nm_plan_estudios', sa.Text(), nullable=True),
|
||||
sa.Column('nm_pronostico', sa.Text(), nullable=True),
|
||||
sa.Column('nm_observaciones', sa.Text(), nullable=True),
|
||||
sa.Column('nm_masa_corporal', sa.Float(), nullable=True),
|
||||
sa.Column('nm_talla', sa.Float(), nullable=True),
|
||||
sa.Column('nm_imc_visita', sa.Float(), nullable=True),
|
||||
sa.Column('nm_frecuencia_cardiaca', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_frecuencia_respiratoria', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_presion_arterial_sistolica', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_presion_arterial_diastolica', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_temperatura', sa.Float(), nullable=True),
|
||||
sa.Column('nm_pdf_ruta', sa.Text(), nullable=True),
|
||||
sa.Column('nm_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('nm_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('nm_fuente_sistema', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('nm_id')
|
||||
)
|
||||
with op.batch_alter_table('nota_medica', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nota_medica_nm_id_hospital'), ['nm_id_hospital'], unique=False)
|
||||
|
||||
op.create_table('evaluacion_psicologica',
|
||||
sa.Column('psi_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('psi_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('psi_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_fecha_entrevista_inicial', sa.Date(), nullable=True),
|
||||
sa.Column('psi_fecha_ados2', sa.Date(), nullable=True),
|
||||
sa.Column('psi_fecha_evaluacion', sa.Date(), nullable=True),
|
||||
sa.Column('psi_psicologo', sa.Text(), nullable=True),
|
||||
sa.Column('psi_edad_meses', sa.Float(), nullable=True),
|
||||
sa.Column('psi_ventana_madurativa', sa.Text(), nullable=True),
|
||||
sa.Column('psi_instrumento_tamizaje', sa.Text(), nullable=True),
|
||||
sa.Column('psi_tamizaje_puntaje', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_tamizaje_riesgo', sa.Text(), nullable=True),
|
||||
sa.Column('psi_ados2_modulo', sa.Text(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_a2', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_a6', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_a7', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_a8', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b1', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b2', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b3', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b4', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b5', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b6', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b7', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b8', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b9', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b10', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b11', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b12', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b13', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b14', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b15', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b16b', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b18', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_a3', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_a4', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_a5', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_d1', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_d2', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_d4', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_d5', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_total', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_css', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_css_sa', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_css_rrb', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_clasificacion', sa.Text(), nullable=True),
|
||||
sa.Column('psi_rgd', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_cociente_desarrollo', sa.Float(), nullable=True),
|
||||
sa.Column('psi_css_umbral_aplicado', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_caso_confirmado', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_cars_total', sa.Float(), nullable=True),
|
||||
sa.Column('psi_otros_instrumentos', sa.Text(), nullable=True),
|
||||
sa.Column('psi_regresion_desarrollo', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_diagnostico_texto', sa.Text(), nullable=True),
|
||||
sa.Column('psi_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('psi_nlp_version', sa.Text(), nullable=True),
|
||||
sa.Column('psi_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('psi_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('psi_id')
|
||||
)
|
||||
op.drop_table('mchat')
|
||||
op.drop_table('evaluacion_neuropediatrica')
|
||||
op.drop_table('eeg_metrica_electrodo')
|
||||
op.drop_table('eeg_metrica')
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_eeg_eeg_id_registro_laboratorio'))
|
||||
|
||||
op.drop_table('eeg')
|
||||
op.drop_table('ados2')
|
||||
|
||||
_recode({new: old for old, new in STUDY_CODES.items()})
|
||||
@@ -23,13 +23,13 @@ def _nodes(*functions, **settings):
|
||||
return driver.Builder().with_modules(module).with_config(settings).build().list_available_variables()
|
||||
|
||||
|
||||
@tag(layer="bronce", owner="externo")
|
||||
@tag(layer="bronze", owner="external")
|
||||
def staging() -> Asset:
|
||||
"""Source asset (bronze, external): what the ingestion leaves."""
|
||||
return Asset("staging")
|
||||
|
||||
|
||||
@tag(layer="plata", owner="python")
|
||||
@tag(layer="silver", owner="python")
|
||||
def hechos(staging: Asset) -> Asset:
|
||||
"""Silver asset read from `staging`."""
|
||||
return Asset("hechos", 120)
|
||||
@@ -37,19 +37,19 @@ def hechos(staging: Asset) -> Asset:
|
||||
|
||||
@config.when(registro_owner="python")
|
||||
@extract_fields({"def_parametro": Asset, "dim_periodo": Asset})
|
||||
@tag(layer="plata", owner="python")
|
||||
@tag(layer="silver", owner="python")
|
||||
def registro__python() -> dict:
|
||||
"""One function, two silver assets (`def_parametro`, `dim_periodo`), selected by `registro_owner="python"`."""
|
||||
return {"def_parametro": Asset("def_parametro"), "dim_periodo": Asset("dim_periodo")}
|
||||
|
||||
|
||||
@tag(layer="oro", owner="python")
|
||||
@tag(layer="gold", owner="python")
|
||||
def measure_report(hechos: Asset, def_parametro: Asset, dim_periodo: Asset) -> Asset:
|
||||
"""Gold asset that reads `hechos` and the two `registro` assets."""
|
||||
"""Gold asset that reads `hechos` and the two `registry` assets."""
|
||||
return Asset("measure_report", 37)
|
||||
|
||||
|
||||
@tag(layer="plata", owner="python", depends_on="measure_report")
|
||||
@tag(layer="silver", owner="python", depends_on="measure_report")
|
||||
def periodo_observacion(hechos: Asset, measure_report: Asset) -> Asset:
|
||||
"""Silver asset that reads `hechos` and waits for `measure_report` without using its data (`depends_on`)."""
|
||||
return Asset("periodo_observacion")
|
||||
@@ -101,7 +101,7 @@ def test_depends_on_must_name_a_parameter():
|
||||
|
||||
Fails if `validate` stops comparing the tag with the node's dependencies.
|
||||
"""
|
||||
@tag(layer="plata", owner="python", depends_on="measure_report")
|
||||
@tag(layer="silver", owner="python", depends_on="measure_report")
|
||||
def periodo_observacion(hechos: Asset) -> Asset:
|
||||
"""Declares `depends_on` on an asset that isn't one of its parameters."""
|
||||
return Asset("periodo_observacion")
|
||||
@@ -116,7 +116,7 @@ def test_every_problem_is_reported_at_once():
|
||||
|
||||
Fails if it raises on the first problem or changes the one-line-per-problem format.
|
||||
"""
|
||||
@tag(layer="plata")
|
||||
@tag(layer="silver")
|
||||
def cohorte_miembro(staging: Asset) -> Asset:
|
||||
"""Reads `staging`, which nobody produces, and has no owner: two problems."""
|
||||
return Asset("cohorte_miembro")
|
||||
@@ -128,14 +128,14 @@ def test_every_problem_is_reported_at_once():
|
||||
|
||||
def test_the_diagram_draws_assets_and_skips_the_functions_between_them():
|
||||
"""Pins down: `mermaid` draws one box per asset with its layer and owner, an arrow from producer to
|
||||
reader, a dotted arrow for `depends_on`, and skips functions that don't produce an asset (`registro`).
|
||||
reader, a dotted arrow for `depends_on`, and skips functions that don't produce an asset (`registry`).
|
||||
|
||||
Fails if the diagram format changes, intermediate functions appear, or the order-only arrow stops
|
||||
being dotted.
|
||||
"""
|
||||
diagram = mermaid(_nodes(*CYCLE, registro_owner="python"))
|
||||
assert diagram.startswith("flowchart LR")
|
||||
assert 'hechos["hechos<br/>plata · python"]' in diagram
|
||||
assert 'hechos["hechos<br/>silver · python"]' in diagram
|
||||
assert " staging --> hechos" in diagram
|
||||
assert " def_parametro --> measure_report" in diagram
|
||||
assert "registro" not in diagram.replace("registro_owner", "")
|
||||
@@ -144,8 +144,8 @@ def test_the_diagram_draws_assets_and_skips_the_functions_between_them():
|
||||
|
||||
|
||||
def test_enum_values_are_the_tag_values():
|
||||
"""Pins down: the enum values are the strings written in the tags (`"plata"`, `"dbt"`).
|
||||
"""Pins down: the enum values are the strings written in the tags (`"silver"`, `"dbt"`).
|
||||
|
||||
Fails if a value is renamed, which would invalidate every tag already written.
|
||||
"""
|
||||
assert Layer.SILVER == "plata" and Owner.DBT == "dbt"
|
||||
assert Layer.SILVER == "silver" and Owner.DBT == "dbt"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""What this module covers: the cohort-build reads of `CohorteRepository`: `latest_build`, `members`,
|
||||
"""What this module covers: the cohort-build reads of `CohortRepository`: `latest_build`, `members`,
|
||||
`build` and `builds`.
|
||||
|
||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables and three builds; `_build`
|
||||
@@ -21,7 +21,7 @@ from core.cacu.indicadores.models import (
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from persistance.aristas.oro import CohortBuild, CohorteRepository, CohortMember
|
||||
from persistance.edges.gold import CohortBuild, CohortRepository, CohortMember
|
||||
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo)
|
||||
@@ -59,7 +59,7 @@ def repository():
|
||||
indice_fuente_id="99"),
|
||||
])
|
||||
session.commit()
|
||||
return CohorteRepository(lambda: Session(engine), TABLES)
|
||||
return CohortRepository(lambda: Session(engine), TABLES)
|
||||
|
||||
|
||||
def test_latest_build_of_a_cohort_among_several(repository):
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
"""What this module covers: `persistance.aristas.dbt`, reading what dbt owns: the timeline from its view
|
||||
"""What this module covers: `persistance.edges.dbt`, reading what dbt owns: the timeline from its view
|
||||
(`DbtTimelineRepository`) and the queries it compiled (`DbtQueryRepository`).
|
||||
|
||||
Fixtures: `database`, an in-memory SQLite database with a table behind a `cacu_linea_de_tiempo` view holding three
|
||||
events, dates as text as dbt-sqlite leaves them, and a session factory over it.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtRelationError, DbtTimelineRepository
|
||||
from persistance.aristas.plata import TIMELINE_COLUMNS
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtRelationError, DbtTimelineRepository
|
||||
from persistance.edges.silver import TIMELINE_COLUMNS
|
||||
|
||||
EVENTS = [
|
||||
(2, "2025-02-01", "2025-06-01 00:00:00", "procedimiento", "citologia", "citologia_cervical", None, None, "citologiacervical", "3"),
|
||||
(1, "2025-03-01", "2025-03-02 00:00:00", "medicion", "biopsia", "cin", "LIEAG", None, "biopsiacervical", "7"),
|
||||
(1, "2025-01-05", "2025-01-06 00:00:00", "procedimiento", "citologia", "citologia_cervical", "SATISFACTORIA", None, "citologiacervical", "1"),
|
||||
(2, "2025-02-01", "2025-06-01T00:00:00+00:00", "procedimiento", "citologia", "citologia_cervical", None, None, "citologiacervical", "3"),
|
||||
(1, "2025-03-01", "2025-03-02T00:00:00+00:00", "medicion", "biopsia", "cin", "LIEAG", None, "biopsiacervical", "7"),
|
||||
(1, "2025-01-05", "2025-01-06T00:00:00+00:00", "procedimiento", "citologia", "citologia_cervical", "SATISFACTORIA", None, "citologiacervical", "1"),
|
||||
]
|
||||
|
||||
|
||||
@@ -46,13 +46,14 @@ def test_timeline_comes_from_the_view_in_order_with_dates(database):
|
||||
|
||||
|
||||
def test_filters_run_in_the_query(database):
|
||||
"""Pins down: `patients`, `until` and `known_until` each narrow the rows. Fails if a filter is ignored."""
|
||||
"""Pins down: `patients`, `until` and `known_until` each narrow the rows, the last as an aware datetime against the
|
||||
load times as stored. Fails if a filter is ignored or the load time is compared as text."""
|
||||
_, session_factory = database
|
||||
repository = DbtTimelineRepository(session_factory, "cacu")
|
||||
|
||||
assert {row["pac_id"] for row in repository.read(patients=[2])} == {2}
|
||||
assert [row["fuente_id"] for row in repository.read(until=date(2025, 2, 1))] == ["1", "3"]
|
||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 3, 1))] == ["1"]
|
||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 3, 1, tzinfo=timezone.utc))] == ["1"]
|
||||
|
||||
|
||||
def test_a_missing_view_names_the_dbt_command(database):
|
||||
@@ -74,6 +75,27 @@ def test_a_compiled_query_gives_one_dict_per_row(database):
|
||||
assert rows == [{"pac_id": 1}]
|
||||
|
||||
|
||||
def test_a_query_compiled_with_placeholders_takes_its_values_and_lists(database):
|
||||
"""Pins down: a query compiled with bind placeholders runs with the values given, a list filling `in :name`, so
|
||||
one compiled query serves every period. Fails if `parameters` stops being bound or lists stop expanding."""
|
||||
_, session_factory = database
|
||||
rows = DbtQueryRepository(session_factory).read(
|
||||
"select pac_id, fecha from cacu_linea_de_tiempo where fecha >= :desde and tipo in :tipos order by fecha",
|
||||
{"desde": "2025-02-01", "tipos": ["citologia", "biopsia"]})
|
||||
|
||||
assert rows == [{"pac_id": 2, "fecha": "2025-02-01"}, {"pac_id": 1, "fecha": "2025-03-01"}]
|
||||
|
||||
|
||||
def test_an_empty_result_keeps_its_columns(database):
|
||||
"""Pins down: a query with no rows still says which columns it selects, so whoever reads it can count zero.
|
||||
Fails if `rows` builds the column names from the rows."""
|
||||
_, session_factory = database
|
||||
columns, rows = DbtQueryRepository(session_factory).rows(
|
||||
"select pac_id, tipo from cacu_linea_de_tiempo where fecha > :hasta", {"hasta": "2030-01-01"})
|
||||
|
||||
assert (columns, rows) == (["pac_id", "tipo"], [])
|
||||
|
||||
|
||||
def test_reading_writes_nothing(database):
|
||||
"""Pins down: both repositories read on a read-only session and leave the database as it was. Fails if a read
|
||||
starts committing or creating objects."""
|
||||
|
||||
@@ -2,27 +2,27 @@ import pytest
|
||||
from sqlalchemy import Column, Integer, MetaData, Table, create_engine, insert, select
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.materializador import Materializador, SoloLectura
|
||||
from persistance.materializer import Materializer, ReadOnly
|
||||
|
||||
metadata = MetaData()
|
||||
numeros = Table("numeros", metadata, Column("n", Integer, primary_key=True))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def materializador():
|
||||
def materializer():
|
||||
engine = create_engine("sqlite://")
|
||||
metadata.create_all(engine)
|
||||
return Materializador(lambda: Session(engine))
|
||||
return Materializer(lambda: Session(engine))
|
||||
|
||||
|
||||
def test_the_function_reads_and_the_body_writes(materializador):
|
||||
def test_the_function_reads_and_the_body_writes(materializer):
|
||||
def escribir(sesion, filas):
|
||||
sesion.execute(insert(numeros), [{"n": n} for n in filas])
|
||||
sesion.commit()
|
||||
return len(filas)
|
||||
|
||||
assert materializador.materializar(lambda sesion: [1, 2, 3], escribir) == 3
|
||||
assert materializador.materializar(lambda sesion: sesion.execute(select(numeros.c.n)).scalars().all()) == [1, 2, 3]
|
||||
assert materializer.materialize(lambda sesion: [1, 2, 3], escribir) == 3
|
||||
assert materializer.materialize(lambda sesion: sesion.execute(select(numeros.c.n)).scalars().all()) == [1, 2, 3]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("escribe", [
|
||||
@@ -30,6 +30,6 @@ def test_the_function_reads_and_the_body_writes(materializador):
|
||||
lambda sesion: sesion.commit(),
|
||||
lambda sesion: sesion.execute(insert(numeros).values(n=1)),
|
||||
])
|
||||
def test_the_function_cannot_write(materializador, escribe):
|
||||
with pytest.raises(SoloLectura):
|
||||
materializador.materializar(escribe)
|
||||
def test_the_function_cannot_write(materializer, escribe):
|
||||
with pytest.raises(ReadOnly):
|
||||
materializer.materialize(escribe)
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
"""What this module covers: the per-patient reads of `CohortRepository` behind the risk route: `membership` (the
|
||||
patient in the cohort's latest build, with its variables) and `current_risk` (the current batch and its horizons).
|
||||
|
||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables: builds 1 and 2 of the surveillance cohort
|
||||
(patient 10 in both, patient 20 only in build 1), patient 10's variables in build 2, and batches written and confirmed
|
||||
through the repository itself.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, CohorteMiembro, CohorteVariable,
|
||||
EvaluacionRiesgo, EvaluacionRiesgoLote)
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from persistance.edges.gold import CohortRepository, PendingBatch, RiskHorizon
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo)
|
||||
PROVENANCE = {"modelo_nombre": "cacu-cin2_logistic", "modelo_sha": "s", "mlflow_run_id": "r"}
|
||||
|
||||
|
||||
def _build(armado_id):
|
||||
return CohorteArmado(armado_id=armado_id, url=URL, version=f"0.{armado_id}.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella=f"h{armado_id}", marco_sha="m",
|
||||
n_miembros=2, armado_en=datetime(2027, 1, armado_id, tzinfo=timezone.utc))
|
||||
|
||||
|
||||
def _member(armado_id, pac_id):
|
||||
return CohorteMiembro(armado_id=armado_id, pac_id=pac_id, fecha_indice=date(2025, 1, armado_id),
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repository():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
CaCuModel.metadata.create_all(engine)
|
||||
with Session(engine) as session:
|
||||
session.add_all([_build(1), _build(2), _member(1, 10), _member(1, 20), _member(2, 10)])
|
||||
session.add_all([CohorteVariable(armado_id=2, pac_id=10, variable="pap_0", valor_codigo="ASC-US"),
|
||||
CohorteVariable(armado_id=2, pac_id=10, variable="c", valor_numerico=0.0)])
|
||||
session.commit()
|
||||
return CohortRepository(lambda: Session(engine), TABLES)
|
||||
|
||||
|
||||
def _batch(repository, version, risks, armado_id=2):
|
||||
return repository.save_batch(armado_id, {**PROVENANCE, "modelo_version": version}, "cin2_12m", risks)[0]
|
||||
|
||||
|
||||
def test_membership_is_in_the_latest_build_with_its_variables(repository):
|
||||
"""Pins down: the patient is looked up in the cohort's latest build, and its variables come as code or number.
|
||||
Fails if an older build is used (patient 20 would appear) or a numeric variable is lost."""
|
||||
found = repository.membership(10, URL)
|
||||
|
||||
assert (found.armado_id, found.version, found.fecha_indice) == (2, "0.2.0", date(2025, 1, 2))
|
||||
assert found.variables == {"pap_0": "ASC-US", "c": 0.0}
|
||||
assert repository.membership(20, URL) is None and repository.membership(10, "cacu/otra") is None
|
||||
|
||||
|
||||
def test_an_unconfirmed_batch_is_not_current(repository):
|
||||
"""Pins down: a batch with only preliminary evaluations isn't shown. Fails if a risk nobody confirmed reaches the
|
||||
patient's record."""
|
||||
_batch(repository, "1", [(10, 1.0, 0.2, None, None)])
|
||||
|
||||
assert repository.current_risk(10) is None
|
||||
|
||||
|
||||
def test_the_current_batch_is_the_newest_confirmed_one_with_its_horizons(repository):
|
||||
"""Pins down: among confirmed batches the newest wins, even when a newer unconfirmed one exists; its horizons come
|
||||
in ascending order with their latest state. Fails if the newest batch is taken regardless of its state, or the
|
||||
horizons come unordered."""
|
||||
first = _batch(repository, "1", [(10, 3.0, 0.3, None, None), (10, 1.0, 0.1, 0.05, 0.2)])
|
||||
repository.change_state(first, "final", "revisado")
|
||||
_batch(repository, "2", [(10, 1.0, 0.9, None, None)])
|
||||
|
||||
risk = repository.current_risk(10)
|
||||
|
||||
assert (risk.lote_id, risk.modelo_version, risk.estado_lote) == (first, "1", "final")
|
||||
assert risk.horizontes == [RiskHorizon(1.0, 0.1, 0.05, 0.2, "final"), RiskHorizon(3.0, 0.3, None, None, "final")]
|
||||
|
||||
|
||||
def test_an_annulled_batch_is_no_longer_current(repository):
|
||||
"""Pins down: once a confirmed batch is marked `entered-in-error`, its latest versions aren't final and it stops
|
||||
being current. Fails if any version ever confirmed keeps a withdrawn risk on the record."""
|
||||
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
|
||||
repository.change_state(first, "final", "revisado")
|
||||
repository.change_state(first, "entered-in-error", "modelo equivocado")
|
||||
|
||||
assert repository.current_risk(10) is None
|
||||
|
||||
|
||||
def test_pending_batches_are_the_ones_with_no_decision_yet(repository):
|
||||
"""Pins down: a batch stays pending until it's confirmed or voided, newest first, and dropping off the list is
|
||||
permanent either way. Fails if a confirmed or a voided batch is still listed, or the order is reversed."""
|
||||
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
|
||||
second = _batch(repository, "2", [(10, 1.0, 0.2, None, None)])
|
||||
third = _batch(repository, "3", [(10, 1.0, 0.3, None, None)])
|
||||
repository.change_state(second, "final", "revisado")
|
||||
|
||||
pending = repository.pending_batches()
|
||||
|
||||
assert [(b.lote_id, b.modelo_version, b.n_evaluaciones) for b in pending] == [(third, "3", 1), (first, "1", 1)]
|
||||
assert all(isinstance(b, PendingBatch) and b.modelo_nombre == "cacu-cin2_logistic" for b in pending)
|
||||
|
||||
repository.change_state(third, "entered-in-error", "modelo equivocado")
|
||||
|
||||
assert [b.lote_id for b in repository.pending_batches()] == [first]
|
||||
@@ -0,0 +1,89 @@
|
||||
"""What this module covers: `SourceMappingRepository` over CaMa's `cat_sistema_fuente` and `cat_mapeo`: seeding only
|
||||
adds forms that have no row, `add` runs the caller's check against the rows of the same form in its session, and
|
||||
`close` ends a row's validity once.
|
||||
|
||||
Fixtures: `repo`, an in-memory SQLite database (foreign keys on) with CaMa's tables, one study, result and two values, and the
|
||||
catalog's own source system.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from core.cama.indicadores.models import CatEstudio, CatMapeo, CatResultado, CatSistemaFuente, CatValor
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlmodel import Session, SQLModel
|
||||
|
||||
from persistance.edges.silver import SourceMappingRepository
|
||||
|
||||
AHORA = datetime(2026, 11, 13, 12, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo():
|
||||
motor = create_engine("sqlite://")
|
||||
# SQLite checks foreign keys only when asked; the other engines always do.
|
||||
event.listen(motor, "connect", lambda conexion, _: conexion.execute("PRAGMA foreign_keys=ON"))
|
||||
SQLModel.metadata.create_all(motor, tables=[t.__table__ for t in (CatEstudio, CatResultado, CatValor,
|
||||
CatSistemaFuente, CatMapeo)])
|
||||
with Session(motor) as sesion:
|
||||
sesion.add(CatEstudio(estudio_id="biopsia", etiqueta="Biopsia"))
|
||||
sesion.add(CatResultado(resultado_id="biopsia.her2", estudio_id="biopsia", etiqueta="HER2", tipo_valor="codigo"))
|
||||
sesion.add_all([CatValor(resultado_id="biopsia.her2", valor_id=v, etiqueta=v, orden=i)
|
||||
for i, v in enumerate(("H2", "H3"), start=1)])
|
||||
sesion.commit()
|
||||
repositorio = SourceMappingRepository(lambda: Session(motor, expire_on_commit=False), CatSistemaFuente, CatMapeo)
|
||||
repositorio.ensure_system(CatSistemaFuente(sistema_fuente_id="catalogo", etiqueta="Catálogo",
|
||||
vigente_desde=date(1900, 1, 1)))
|
||||
return repositorio
|
||||
|
||||
|
||||
def mapeo(forma: str, valor: str, *, por: str = "catalogo", desde: date = date(1900, 1, 1)) -> CatMapeo:
|
||||
return CatMapeo(sistema_fuente_id="catalogo", clase="valor", forma=forma, forma_normalizada=forma.upper(),
|
||||
resultado_id="biopsia.her2", valor_id=valor, vigente_desde=desde, registrado_por=por,
|
||||
registrado_en=AHORA)
|
||||
|
||||
|
||||
def test_seeding_adds_only_forms_without_a_row(repo):
|
||||
"""Pins down: a deploy's seed never touches a stored row: a form already mapped, even to another code by a
|
||||
person, keeps its row, and only new forms are added. Fails if `seed` merges or replaces rows, which would undo
|
||||
a curator's change on every deploy."""
|
||||
repo.add(mapeo("3+", "H2", por="curador"))
|
||||
assert repo.seed([mapeo("3+", "H3"), mapeo("Positivo (3+)", "H3")]) == 1
|
||||
assert {(m.forma, m.valor_id, m.registrado_por) for m in repo.forms()} == {
|
||||
("3+", "H2", "curador"), ("Positivo (3+)", "H3", "catalogo")}
|
||||
assert repo.seed([mapeo("3+", "H3")]) == 0
|
||||
assert repo.ensure_system(CatSistemaFuente(sistema_fuente_id="catalogo", etiqueta="Otro",
|
||||
vigente_desde=date(2000, 1, 1))) is False
|
||||
|
||||
|
||||
def test_add_runs_the_check_against_the_same_form(repo):
|
||||
"""Pins down: `add` hands the caller's check the stored rows of the same form, and a check that raises leaves
|
||||
nothing written. Fails if the check runs on other forms or after the insert."""
|
||||
repo.add(mapeo("3+", "H3"))
|
||||
repo.add(mapeo("Positivo", "H3"))
|
||||
vistas = []
|
||||
|
||||
def rechaza(misma_forma, nueva):
|
||||
vistas.extend(m.forma for m in misma_forma)
|
||||
raise ValueError("ambigua")
|
||||
|
||||
with pytest.raises(ValueError, match="ambigua"):
|
||||
repo.add(mapeo("3+", "H2", desde=date(2027, 1, 1)), check=rechaza)
|
||||
assert vistas == ["3+"]
|
||||
assert len(repo.forms(forma_normalizada="3+")) == 1
|
||||
|
||||
|
||||
def test_close_ends_a_row_once_and_the_schema_rejects_a_bad_row(repo):
|
||||
"""Pins down: `close` sets `vigente_hasta` and a second close keeps the first end; a value outside `cat_valor`
|
||||
or an end before the start is rejected by the database itself. Fails if `close` overwrites an end or a
|
||||
constraint of `reglas_de_mapeo` is lost."""
|
||||
fila = repo.add(mapeo("3+", "H3"))
|
||||
assert repo.close(fila.mapeo_id, date(2026, 12, 31)).vigente_hasta == date(2026, 12, 31)
|
||||
assert repo.close(fila.mapeo_id, date(2027, 6, 30)).vigente_hasta == date(2026, 12, 31)
|
||||
with pytest.raises(IntegrityError):
|
||||
repo.add(mapeo("H4", "H4"))
|
||||
malo = mapeo("Equívoco", "H2", desde=date(2027, 1, 1))
|
||||
malo.vigente_hasta = date(2026, 1, 1)
|
||||
with pytest.raises(IntegrityError):
|
||||
repo.add(malo)
|
||||
@@ -12,8 +12,8 @@ from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String,
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineContractError, TimelineQueryMissing, TimelineRepository
|
||||
from persistance.materializador import SoloLectura
|
||||
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineContractError, TimelineQueryMissing, TimelineRepository
|
||||
from persistance.materializer import ReadOnly
|
||||
|
||||
metadata = MetaData()
|
||||
events = Table(
|
||||
@@ -99,7 +99,7 @@ def test_a_query_with_other_columns_breaks_the_contract(session_factory):
|
||||
|
||||
|
||||
def test_the_query_runs_on_a_read_only_session(session_factory):
|
||||
"""Pins down: the query runs on a `SesionDeLectura`, so a query that writes is rejected.
|
||||
"""Pins down: the query runs on a `ReadSession`, so a query that writes is rejected.
|
||||
|
||||
Fails if `read` uses a plain session.
|
||||
"""
|
||||
@@ -107,7 +107,7 @@ def test_the_query_runs_on_a_read_only_session(session_factory):
|
||||
"""Returns an INSERT instead of a SELECT."""
|
||||
return insert(events).values(pac_id=9)
|
||||
|
||||
with pytest.raises(SoloLectura):
|
||||
with pytest.raises(ReadOnly):
|
||||
TimelineRepository(session_factory, writing_query).read()
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ def test_each_domain_module_reads_its_dbt_view_and_can_be_rebound(session_factor
|
||||
Fails if a domain module drops either repository, reads another domain's view, or loses `with_query`.
|
||||
"""
|
||||
from persistance import cacu, cama, tea
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
|
||||
for name, domain in (("cacu", cacu), ("cama", cama), ("tea", tea)):
|
||||
assert isinstance(domain.timeline_repository, DbtTimelineRepository)
|
||||
|
||||
@@ -15,10 +15,10 @@ operación, en [`dist/MANUAL.md`](dist/MANUAL.md).
|
||||
| `Core/` | Esquema SQLModel (tablas y vocabularios controlados) de cada padecimiento y de gobernanza. Cada dominio tiene su propio registro de SQLAlchemy. |
|
||||
| `Persistance/` | Conexión, repositorios y migraciones de Alembic (una cadena por base). Cuatro bases independientes: CaCu, CaMa, TEA y gobernanza. |
|
||||
| `Extraction/` | Lectura de documentos clínicos (PDF con texto o escaneado, imágenes) y de EEG (EDF, con MNE): OCR, separación por paciente, extracción de campos y combinación de registros. |
|
||||
| `WebApi/` (submódulo) | API REST en Flask: importación, consulta de datos, indicadores, bitácora y gobernanza. `GET /api` lista las rutas. `webapi/orquestacion/` es el ciclo de indicadores de cada dominio (staging → plata → reportes), con Hamilton. |
|
||||
| `WebApi/` (submódulo) | API REST en Flask: importación, consulta de datos, indicadores, bitácora y gobernanza. `GET /api` lista las rutas. `webapi/orchestration/` es el ciclo de indicadores de cada dominio (staging → plata → reportes), con Hamilton. |
|
||||
| `WebApp/` (submódulo) | Interfaz en Angular y Angular Material. |
|
||||
| `models/` (submódulo) | Registro de modelos en MLflow, predicciones y trabajos de OCR de reportes. |
|
||||
| `indicadores_kit/` (submódulo) | Definiciones y cálculo de los indicadores, del equipo clínico. |
|
||||
| `Transformation/` | dbt: los modelos sobre la plata genérica y las definiciones de los indicadores (capa semántica). |
|
||||
| `dist/` | Paquete de instalación: `docker-compose.yml`, scripts y manual. |
|
||||
|
||||
Cambiar de motor de base de datos (SQLite, MySQL/MariaDB, PostgreSQL o SQL
|
||||
@@ -48,7 +48,7 @@ uv run python main.py # http://localhost:5050
|
||||
cd WebApp && npm install && npm start # http://localhost:4200
|
||||
|
||||
# Indicadores de un dominio, después de importar datos
|
||||
cd WebApi && uv run python -m webapi.orquestacion ciclo cacu --desde 2021 --hasta 2026 --permitir-sin-definir
|
||||
cd WebApi && uv run python -m webapi.orchestration cycle cacu --from 2021 --to 2026 --allow-undecided
|
||||
```
|
||||
|
||||
Con Docker, `docker compose up --build` levanta la API (puerto 5050), el
|
||||
|
||||
@@ -6,3 +6,5 @@ uv.lock
|
||||
.user.yml
|
||||
package-lock.yml
|
||||
.venv/
|
||||
graphify-out/
|
||||
*.db
|
||||
|
||||
@@ -28,6 +28,97 @@ vars:
|
||||
cie_antecedente: ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
||||
horizonte_toma_reporte_dias: 60
|
||||
horizonte_toma_diagnostico_dias: 180
|
||||
# ASCCP follow-up (the kit's cacu.seguimiento.*; provisional): what counts as a colposcopy and a treatment
|
||||
# (models/cacu/silver/cacu_procedimientos_inferidos.sql).
|
||||
seguimiento:
|
||||
colposcopia_evidencias: ["motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia"]
|
||||
colposcopia_requisito: "valoracion_previa"
|
||||
biopsia_requisito: "mismo_dia_que_colposcopia"
|
||||
colposcopia_motivos: ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
|
||||
colposcopia_especialidades: ["CLINICA_MUJER_COLPOSCOPIA"]
|
||||
colposcopia_cie: ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
|
||||
colposcopia_diagnosticos: ["VIRUS DEL PAPILOMA HUMANO"]
|
||||
tratamiento_cie: ["D06", "D060", "D061", "D067", "D069"]
|
||||
vigilancia_especialidades: ["MEDICINA_FAMILIAR", "CLINICA_MUJER_COLPOSCOPIA"]
|
||||
# The risk estimates a band summary reads (the kit's cacu.riesgos.horizonte_banda; provisional): years from the
|
||||
# index date, 0 is prevalent.
|
||||
riesgos_horizonte_banda: 0
|
||||
# CaMa's rules (the kit's cama.*; provisional). The diagnosis rules: a note with one of `cie_diagnostico` written by
|
||||
# one of `especialidades_diagnostico` resolves a mammogram within `horizonte_toma_diagnostico_dias`; one with one
|
||||
# of `cie_antecedente` before it leaves it out. `birads_gravedad`: BI-RADS from least to most severe.
|
||||
cama:
|
||||
cie_diagnostico: ["Z123", "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", "N61", "N62", "N63",
|
||||
"N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", "D24", "R92", "D05",
|
||||
"D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506",
|
||||
"C508", "C509"]
|
||||
cie_antecedente: ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505",
|
||||
"C506", "C508", "C509"]
|
||||
especialidades_diagnostico: ["CIRUGIA_ONCOLOGICA"]
|
||||
horizonte_toma_diagnostico_dias: 180
|
||||
birads_gravedad: ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"]
|
||||
# Biopsy grades from least to most severe (models/cama/gold/eventos/cama_resultado_biopsia.sql): the keys of
|
||||
# cama.catalogos.biopsia.
|
||||
biopsia_gravedad: ["BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
|
||||
# The grades that count as cancer in the detection rate (models/cama/gold/eventos/cama_deteccion_biopsia.sql): the
|
||||
# values of the parameter cama.biopsia_cancer (a test keeps them equal).
|
||||
grados_cancer: ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
|
||||
# The analysis' stratifiers (models/cama/silver/cama_estratificadores.sql), from the catalog's provisional results
|
||||
# read from reports; placeholders until the domain expert validates them. `estadios`: each clinical stage's
|
||||
# group; `etapa_temprana`: the groups counted as early, the rest of the known ones advanced. The surrogate
|
||||
# molecular subtype: HER2 3+ is HER2-positive; HER2 0 or 1+ with both receptors negative, triple negative; with a
|
||||
# positive receptor, luminal A when Ki-67 is under `ki67_corte` % and progesterone positive with at least
|
||||
# `rp_corte` % (or no percentage), luminal B when Ki-67 is at least `ki67_corte` % or progesterone falls short;
|
||||
# without Ki-67, none. `tamano_t`: T by the lesion's largest diameter in mm, each up to its bound.
|
||||
# The biopsy grades that are an invasive cancer (models/cama/gold/eventos/cama_cancer_invasor.sql).
|
||||
grados_invasor: ["CARCINOMA_INVASOR"]
|
||||
estratos:
|
||||
estadios: {E0: "0", EI: "i", EIIA: "ii", EIIB: "ii", EIIIA: "iii", EIIIB: "iii", EIIIC: "iii", EIV: "iv"}
|
||||
etapa_temprana: ["0", "i", "ii"]
|
||||
her2_positivo: ["H3"]
|
||||
her2_negativo: ["H0", "H1"]
|
||||
ki67_corte: 20
|
||||
rp_corte: 20
|
||||
tamano_t: [{t: "t1", hasta_mm: 20}, {t: "t2", hasta_mm: 50}, {t: "t3", hasta_mm: null}]
|
||||
# TEA's rules (models/tea). The cohort: children whose first M-CHAT was at `edad_min_meses` to `edad_max_meses`
|
||||
# completed months (days / `dias_por_mes`, rounded to one decimal, then truncated); `ventanas`, the age groups of
|
||||
# that age. A confirmation is a neuropediatrics note with one of `cie_tea` (without the dot, compared exactly).
|
||||
# An EEG is bad when any quality criterion passes its threshold (`calidad`); a metric is altered when its z-score
|
||||
# against the reference of the child's age group at the EEG is at least `alteracion_z` away from 0.
|
||||
# The references, thresholds and `alteracion_z` are placeholders until the domain expert validates them.
|
||||
tea:
|
||||
edad_min_meses: 16
|
||||
edad_max_meses: 36
|
||||
dias_por_mes: 30.4375
|
||||
ventanas:
|
||||
- {clave: "16_23", desde: 16, hasta: 23}
|
||||
- {clave: "24_29", desde: 24, hasta: 29}
|
||||
- {clave: "30_36", desde: 30, hasta: 36}
|
||||
cie_tea: ["F840"]
|
||||
alteracion_z: 2
|
||||
calidad:
|
||||
canales_amplitud: 2
|
||||
canales_alta_frecuencia: 2
|
||||
canales_correlacion: 2
|
||||
canales_sin_senal: 2
|
||||
ruido_linea_db: 8
|
||||
# Reference range of each metric by age group at the EEG: (metric, group, min, max). The mean is the middle of
|
||||
# the range and the standard deviation a quarter of its width.
|
||||
referencias:
|
||||
- ["ritmo_posterior", "16_23", 4.5, 7.0]
|
||||
- ["ritmo_posterior", "24_29", 5.0, 7.5]
|
||||
- ["ritmo_posterior", "30_36", 5.5, 8.5]
|
||||
- ["husos_sueno_n2", "16_23", 2.5, 6.5]
|
||||
- ["husos_sueno_n2", "24_29", 2.25, 6.25]
|
||||
- ["husos_sueno_n2", "30_36", 2.0, 6.0]
|
||||
- ["husos_sueno_n3", "16_23", 0.75, 2.75]
|
||||
- ["husos_sueno_n3", "24_29", 0.5, 2.5]
|
||||
- ["husos_sueno_n3", "30_36", 0.5, 2.5]
|
||||
- ["picos_paroxisticos", "16_23", 0.0, 1.0]
|
||||
- ["picos_paroxisticos", "24_29", 0.0, 1.0]
|
||||
- ["picos_paroxisticos", "30_36", 0.0, 1.0]
|
||||
- ["gradiente_anteroposterior", "16_23", 2.0, 3.5]
|
||||
- ["gradiente_anteroposterior", "24_29", 1.75, 3.25]
|
||||
- ["gradiente_anteroposterior", "30_36", 1.5, 3.0]
|
||||
# The surveillance cohort's rules (models/cacu/cohorts/surveillance).
|
||||
surveillance_cohort:
|
||||
recruitment_start: "2024-01-01"
|
||||
|
||||
@@ -34,16 +34,18 @@ from (
|
||||
{%- set valor_codigo = as_text('null') -%}
|
||||
{%- set valor_numerico = 'cast(o.valor_numerico as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- elif resultado -%}
|
||||
{%- set valor_codigo = as_text(
|
||||
{#- Every branch as text: SQL Server gives a CASE the type of highest precedence among its branches, so a
|
||||
number and a date in one CASE fail there. -#}
|
||||
{%- set valor_codigo =
|
||||
"case r.tipo_valor"
|
||||
~ " when 'codigo' then coalesce(o.valor_id, o.valor_fuente)"
|
||||
~ " when 'booleano' then " ~ as_integer('o.valor_numerico')
|
||||
~ " when 'numero' then o.valor_numerico"
|
||||
~ " when 'fecha' then o.valor_fecha"
|
||||
~ " else o.valor_texto end") -%}
|
||||
~ " when 'codigo' then " ~ as_text('coalesce(o.valor_id, o.valor_fuente)')
|
||||
~ " when 'booleano' then " ~ as_text(as_integer('o.valor_numerico'))
|
||||
~ " when 'numero' then " ~ as_text('o.valor_numerico')
|
||||
~ " when 'fecha' then " ~ as_text('o.valor_fecha')
|
||||
~ " else " ~ as_text('o.valor_texto') ~ " end" -%}
|
||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- elif f.get('columna') -%}
|
||||
{%- set valor_codigo = "nullif(trim(p." ~ f['columna'] ~ "), '')" -%}
|
||||
{%- set valor_codigo = "nullif(ltrim(rtrim(p." ~ f['columna'] ~ ")), '')" -%}
|
||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- else -%}
|
||||
{%- set valor_codigo = as_text('null') -%}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
{#
|
||||
Completed months from a number of days, as TEA counts them: days / `tea.dias_por_mes`, rounded to one decimal,
|
||||
then truncated (a child of 26.96 months is 27.0 and so 27, one of 26.94 is 26). Days are differences of
|
||||
`dim_fecha.dia_num`, never negative here.
|
||||
|
||||
Truncation is `floor`, except on SQLite, where a cast to integer truncates (PostgreSQL and MySQL round on that
|
||||
cast). PostgreSQL only rounds a numeric to a number of decimals, hence the cast to decimal first.
|
||||
#}
|
||||
{% macro tea_meses_cumplidos(dias) -%}
|
||||
{{ return(adapter.dispatch('tea_meses_cumplidos', 'isssteleon')(dias)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__tea_meses_cumplidos(dias) -%}
|
||||
{{ as_integer('floor(round(cast(' ~ dias ~ ' as decimal(12, 4)) / ' ~ var('tea')['dias_por_mes'] ~ ', 1))') }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro sqlite__tea_meses_cumplidos(dias) -%}
|
||||
cast(round(({{ dias }}) / {{ var('tea')['dias_por_mes'] }}, 1) as integer)
|
||||
{%- endmacro %}
|
||||
|
||||
{#
|
||||
The age group of a number of completed months: the `tea.ventanas` window it falls in, `sin_dato` when the months
|
||||
are null (no birth date), and null when it falls outside every window.
|
||||
#}
|
||||
{% macro tea_grupo_edad(meses) -%}
|
||||
case
|
||||
when {{ meses }} is null then {{ as_text("'sin_dato'") }}
|
||||
{%- for v in var('tea')['ventanas'] %}
|
||||
when {{ meses }} between {{ v['desde'] }} and {{ v['hasta'] }} then {{ as_text("'" ~ v['clave'] ~ "'") }}
|
||||
{%- endfor %}
|
||||
end
|
||||
{%- endmacro %}
|
||||
|
||||
{# A bounded number of the EEG's quality: within its threshold of `tea.calidad`. #}
|
||||
{% macro tea_criterio_bueno(columna, umbral) -%}
|
||||
({{ columna }} is not null and {{ columna }} <= {{ var('tea')['calidad'][umbral] }})
|
||||
{%- endmacro %}
|
||||
|
||||
{# The later of two values when both are known, else null: a step reached after the previous one is dated by the
|
||||
later of its fact and that step. SQL Server 2016 has no GREATEST. #}
|
||||
{% macro tea_despues(previo, propio) -%}
|
||||
case when ({{ previo }}) is null or ({{ propio }}) is null then null
|
||||
when ({{ propio }}) > ({{ previo }}) then ({{ propio }}) else ({{ previo }}) end
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,12 @@
|
||||
{# A list of strings as an SQL list: ('a', 'b'). For rules from dbt vars, which are compiled in. #}
|
||||
{% macro sql_list(valores) -%}
|
||||
({% for v in valores %}'{{ v | replace("'", "''") }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
{%- endmacro %}
|
||||
|
||||
{# A text column without accents and in upper case, to compare by containment with rules written that way. The
|
||||
accents go first: SQLite's `upper` only knows ASCII. #}
|
||||
{% macro sin_acentos_mayusculas(columna) -%}
|
||||
{%- set pares = [('Á','A'),('É','E'),('Í','I'),('Ó','O'),('Ú','U'),('Ü','U'),
|
||||
('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u')] -%}
|
||||
upper({% for _ in pares %}replace({% endfor %}{{ columna }}{% for con, sin in pares %}, '{{ con }}', '{{ sin }}'){% endfor %})
|
||||
{%- endmacro %}
|
||||
@@ -4,7 +4,7 @@ version: 2
|
||||
# (`--profile cacu|cama|tea`). Written by the Python load; dbt only reads them.
|
||||
sources:
|
||||
- name: silver
|
||||
schema: main
|
||||
schema: "{{ target.schema }}"
|
||||
tables:
|
||||
- name: procedimiento
|
||||
- name: observacion_clinica
|
||||
@@ -13,4 +13,24 @@ sources:
|
||||
- name: cat_estudio
|
||||
- name: cat_resultado
|
||||
- name: cat_valor
|
||||
- name: cat_sistema_fuente
|
||||
# How each source writes the catalog's codes. A study code or a spelling maps to one target while in force:
|
||||
# the writer checks it, and this test finds rows written past it. Captions have no target here (their result
|
||||
# is part of the form), so they never fail it.
|
||||
- name: cat_mapeo
|
||||
tests:
|
||||
- vigencias_sin_traslape:
|
||||
llave: mapeo_id
|
||||
forma: [sistema_fuente_id, clase, resultado_id, forma_normalizada]
|
||||
destino: [estudio_id, valor_id]
|
||||
- name: dim_fecha
|
||||
|
||||
# Restricted gold the Python cycle writes: the cohort builds and the risk estimates scored on them. dbt only reads
|
||||
# them, like silver.
|
||||
- name: oro
|
||||
schema: "{{ target.schema }}"
|
||||
tables:
|
||||
- name: cohorte_armado
|
||||
- name: cohorte_miembro
|
||||
- name: evaluacion_riesgo_lote
|
||||
- name: evaluacion_riesgo
|
||||
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
-- CACU_CONFIRMACION_CITOLOGIA: confirmación por biopsia según resultado citológico. Unidad: paciente.
|
||||
-- población: pacientes cuya última citología válida del periodo es de alto grado (citologia_alto_grado)
|
||||
-- categoría: grado más grave de biopsia originada por esa citología (ligada por toma_id);
|
||||
-- SIN_BIOPSIA si no tiene ninguna; SIN_DATO si tiene pero sin grado
|
||||
-- gravedad: orden de catalogo_biopsia, de menos a más grave
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
biopsias as (
|
||||
select * from {{ ref('cacu_biopsias') }}
|
||||
),
|
||||
|
||||
en_periodo as (
|
||||
select *
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
-- Último resultado válido por paciente, con su toma_id para ligar biopsias
|
||||
por_recientes as (
|
||||
select
|
||||
pac_id,
|
||||
procedimiento_id as toma_id,
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then resultado end as resultado,
|
||||
row_number() over (
|
||||
partition by pac_id
|
||||
order by
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then 1 else 0 end desc,
|
||||
fecha_toma desc,
|
||||
fuente_id desc
|
||||
) as lugar
|
||||
from en_periodo
|
||||
),
|
||||
|
||||
ultimo_resultado as (
|
||||
select pac_id, toma_id, resultado
|
||||
from por_recientes
|
||||
where lugar = 1
|
||||
),
|
||||
|
||||
de_alto_grado as (
|
||||
select pac_id, toma_id
|
||||
from ultimo_resultado
|
||||
where resultado in ({% for g in var("citologia_alto_grado") %}'{{ g }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
),
|
||||
|
||||
-- Biopsia más grave ligada a la toma de esa citología
|
||||
por_gravedad as (
|
||||
select
|
||||
d.pac_id,
|
||||
b.grado,
|
||||
row_number() over (
|
||||
partition by d.pac_id
|
||||
order by
|
||||
case b.grado
|
||||
{% for g in var("catalogo_biopsia") %}
|
||||
when '{{ g }}' then {{ loop.index }}
|
||||
{% endfor %}
|
||||
else 0
|
||||
end desc,
|
||||
b.fecha_reporte desc,
|
||||
b.fuente_id desc
|
||||
) as lugar
|
||||
from de_alto_grado d
|
||||
join biopsias b
|
||||
on b.toma_id = d.toma_id
|
||||
and b.pac_id = d.pac_id
|
||||
where b.fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
biopsia_mas_grave as (
|
||||
select pac_id, grado
|
||||
from por_gravedad
|
||||
where lugar = 1
|
||||
)
|
||||
|
||||
select
|
||||
d.pac_id as unidad_id,
|
||||
'TOTAL' as grupo,
|
||||
case
|
||||
when b.pac_id is null then 'SIN_BIOPSIA'
|
||||
else coalesce(b.grado, 'SIN_DATO')
|
||||
end as categoria
|
||||
from de_alto_grado d
|
||||
left join biopsia_mas_grave b on b.pac_id = d.pac_id
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_confirmacion_citologia
|
||||
description: "Confirmación por biopsia del resultado citológico de alto grado (C2). Población: pacientes cuya última citología válida del periodo es de alto grado."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
||||
contrato: C2
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
||||
citologia_alto_grado: cacu.citologia_alto_grado
|
||||
catalogo_biopsia: cacu.catalogo_biopsia
|
||||
poblaciones:
|
||||
initial-population: "Pacientes cuya última citología válida del periodo es de alto grado"
|
||||
columns:
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
- name: grupo
|
||||
description: "TOTAL"
|
||||
- name: categoria
|
||||
description: "Grado más grave de biopsia ligada a esa citología; SIN_BIOPSIA o SIN_DATO"
|
||||
@@ -1,106 +0,0 @@
|
||||
-- CACU_DIAS_TOMA_DIAGNOSTICO: días naturales de la toma de citología al diagnóstico. Unidad: examen. C3r.
|
||||
-- initial-population: citologías del periodo medibles (sin antecedente previo y con horizonte vencido o diagnóstico)
|
||||
-- measure-observation: de ellas, con diagnóstico, con los días
|
||||
--
|
||||
-- El diagnóstico es la primera nota con CIE en cie_diagnostico y especialidad en
|
||||
-- especialidades_diagnostico, posterior a la toma y dentro del horizonte.
|
||||
-- Se excluyen tomas de pacientes con nota con CIE en cie_antecedente anterior a la toma.
|
||||
-- Workaround SQLite 3.40: primer_antecedente y join a diagnosticos se calculan una vez
|
||||
-- mediante uniones, no subconsultas correlacionadas (ver consultas/tiempos.py).
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
notas as (
|
||||
select * from {{ ref('cacu_notas') }}
|
||||
),
|
||||
|
||||
-- Notas que cuentan como diagnóstico: CIE en la lista Y especialidad conocida
|
||||
diagnosticos as (
|
||||
select n.pac_id, n.fecha
|
||||
from notas n
|
||||
where n.cie_codigo in ({% for c in var("cie_diagnostico") %}'{{ c }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.especialidad in ({% for e in var("especialidades_diagnostico") %}'{{ e }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.fecha <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
-- Notas que cuentan como antecedente (incidencia previa)
|
||||
antecedentes as (
|
||||
select n.pac_id, n.fecha
|
||||
from notas n
|
||||
where n.cie_codigo in ({% for c in var("cie_antecedente") %}'{{ c }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.fecha <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
tomas_del_periodo as (
|
||||
select fuente_id, pac_id, fecha_toma as toma
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
-- Primer antecedente por paciente (calculado una vez, no correlacionado)
|
||||
primer_antecedente as (
|
||||
select pac_id, min(fecha) as fecha
|
||||
from antecedentes
|
||||
group by pac_id
|
||||
),
|
||||
|
||||
-- Primer diagnóstico posterior a la toma y dentro del horizonte, por toma
|
||||
tomas_con_fechas as (
|
||||
select
|
||||
t.fuente_id,
|
||||
t.pac_id,
|
||||
t.toma,
|
||||
pa.fecha as antecedente,
|
||||
min(d.fecha) as diagnostico
|
||||
from tomas_del_periodo t
|
||||
left join primer_antecedente pa
|
||||
on pa.pac_id = t.pac_id
|
||||
left join diagnosticos d
|
||||
on d.pac_id = t.pac_id
|
||||
and d.fecha > t.toma
|
||||
and {{ dbt.datediff("t.toma", "d.fecha", "day") }}
|
||||
< {{ var("horizonte_toma_diagnostico_dias") }}
|
||||
group by t.fuente_id, t.pac_id, t.toma, pa.fecha
|
||||
),
|
||||
|
||||
-- Excluir tomas de pacientes con antecedente anterior a la toma
|
||||
tomas as (
|
||||
select fuente_id, pac_id, toma, diagnostico
|
||||
from tomas_con_fechas
|
||||
where antecedente is null or antecedente >= toma
|
||||
),
|
||||
|
||||
con_estado as (
|
||||
select
|
||||
fuente_id,
|
||||
pac_id,
|
||||
toma,
|
||||
diagnostico,
|
||||
diagnostico is null
|
||||
and {{ dbt.datediff("toma", date_literal(var("fecha_corte")), "day") }}
|
||||
< {{ var("horizonte_toma_diagnostico_dias") }} as pendiente
|
||||
from tomas
|
||||
),
|
||||
|
||||
poblacion_inicial as (
|
||||
select fuente_id as unidad_id, pac_id, 'TOTAL' as grupo
|
||||
from con_estado
|
||||
where not pendiente
|
||||
),
|
||||
|
||||
observacion as (
|
||||
select
|
||||
fuente_id as unidad_id,
|
||||
pac_id,
|
||||
'TOTAL' as grupo,
|
||||
{{ dbt.datediff("toma", "diagnostico", "day") }} as valor
|
||||
from con_estado
|
||||
where diagnostico is not null
|
||||
)
|
||||
|
||||
select 'initial-population' as poblacion, unidad_id, pac_id, grupo, null as valor from poblacion_inicial
|
||||
union all
|
||||
select 'measure-observation' as poblacion, unidad_id, pac_id, grupo, valor from observacion
|
||||
@@ -1,29 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_dias_toma_diagnostico
|
||||
description: "Días naturales de la toma de citología al diagnóstico en nota médica (C3r). Unidad: examen. Excluye tomas de pacientes con diagnóstico previo."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
|
||||
contrato: C3r
|
||||
unidad: examen
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
horizonte_toma_diagnostico_dias: cacu.horizontes.toma_diagnostico_dias
|
||||
especialidades_diagnostico: cacu.diagnostico.especialidades
|
||||
poblaciones:
|
||||
initial-population: "Citologías medibles: sin antecedente previo y con horizonte vencido o diagnóstico al corte"
|
||||
measure-observation: "De ellas, con primera nota de diagnóstico, con los días"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "initial-population | measure-observation"
|
||||
- name: unidad_id
|
||||
description: "fuente_id de la citología"
|
||||
- name: pac_id
|
||||
description: "pac_id del paciente (para estratificación)"
|
||||
- name: grupo
|
||||
description: "TOTAL"
|
||||
- name: valor
|
||||
description: "Días naturales de toma a primera nota de diagnóstico (NULL en initial-population)"
|
||||
@@ -1,44 +0,0 @@
|
||||
-- CACU_EU13: pacientes tamizadas con lesión confirmada por biopsia.
|
||||
-- denominador: pacientes con citología tomada en el periodo
|
||||
-- numerador: de ellas, las que tienen biopsia reportada con grado en deteccion_grados,
|
||||
-- originada por una de sus citologías del periodo (ligada por toma_id)
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
biopsias as (
|
||||
select * from {{ ref('cacu_biopsias') }}
|
||||
),
|
||||
|
||||
tomas_del_periodo as (
|
||||
select distinct
|
||||
procedimiento_id,
|
||||
pac_id
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
poblacion_inicial as (
|
||||
select distinct pac_id as unidad_id
|
||||
from tomas_del_periodo
|
||||
),
|
||||
|
||||
denominador as (
|
||||
select unidad_id from poblacion_inicial
|
||||
),
|
||||
|
||||
numerador as (
|
||||
select distinct t.pac_id as unidad_id
|
||||
from tomas_del_periodo t
|
||||
join biopsias b
|
||||
on b.toma_id = t.procedimiento_id
|
||||
and b.pac_id = t.pac_id
|
||||
where b.fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and b.grado in ({% for g in var("deteccion_grados") %}'{{ g }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
)
|
||||
|
||||
select 'denominador' as poblacion, unidad_id from denominador
|
||||
union all
|
||||
select 'numerador' as poblacion, unidad_id from numerador
|
||||
@@ -1,22 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_eu13
|
||||
description: "Pacientes tamizadas con lesión confirmada por biopsia (C1). Denominador: con citología en el periodo. Numerador: con biopsia ligada a esa citología con grado en deteccion_grados."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_EU13"
|
||||
contrato: C1
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
deteccion_grados: cacu.deteccion_grados
|
||||
poblaciones:
|
||||
denominador: "Pacientes con citología tomada en el periodo"
|
||||
numerador: "De ellas, con biopsia reportada con grado en deteccion_grados"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "denominador | numerador"
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
@@ -1,49 +0,0 @@
|
||||
-- CACU_EU7: distribución de resultados citológicos por semestre. Unidad: paciente.
|
||||
-- población: pacientes con ≥1 citología tomada en el periodo
|
||||
-- resultado: último resultado válido del periodo a la fecha de corte; SIN_DATO si ninguna
|
||||
-- válida: tiene resultado, reportada al corte, calidad ≠ calidad_insatisfactoria
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
en_periodo as (
|
||||
select *
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
por_recientes as (
|
||||
select
|
||||
pac_id,
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then resultado end as resultado,
|
||||
row_number() over (
|
||||
partition by pac_id
|
||||
order by
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then 1 else 0 end desc,
|
||||
fecha_toma desc,
|
||||
fuente_id desc
|
||||
) as lugar
|
||||
from en_periodo
|
||||
),
|
||||
|
||||
ultimo_resultado as (
|
||||
select pac_id, resultado
|
||||
from por_recientes
|
||||
where lugar = 1
|
||||
)
|
||||
|
||||
select
|
||||
pac_id as unidad_id,
|
||||
coalesce(resultado, 'SIN_DATO') as categoria,
|
||||
'TOTAL' as grupo
|
||||
from ultimo_resultado
|
||||
@@ -1,23 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_eu7
|
||||
description: "Distribución de resultados citológicos por semestre (C2). Último resultado válido por paciente al corte; SIN_DATO si ninguno válido."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_EU7"
|
||||
contrato: C2
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
||||
poblaciones:
|
||||
initial-population: "Pacientes con ≥1 citología tomada en el periodo"
|
||||
columns:
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
- name: categoria
|
||||
description: "Resultado citológico (bethesda) o SIN_DATO"
|
||||
- name: grupo
|
||||
description: "TOTAL (sin desgloses por ahora)"
|
||||
@@ -0,0 +1,41 @@
|
||||
-- One row per member of the surveillance cohort build that the current batch of risk estimates scored, with her
|
||||
-- index date and the probability of her estimate in force, null if she has none. The current batch is the latest one
|
||||
-- of the cohort with some estimate in force; an estimate is in force when its latest version, at the horizon
|
||||
-- `riesgos_horizonte_banda`, is `final` (a later `entered-in-error` version voids it). When a member and an estimate
|
||||
-- became known: the build's and the estimate's registration.
|
||||
|
||||
with recientes as (
|
||||
select
|
||||
e.lote_id,
|
||||
e.pac_id,
|
||||
e.probabilidad,
|
||||
e.estado,
|
||||
e.registrado_en,
|
||||
row_number() over (partition by e.lote_id, e.pac_id order by e.version desc) as lugar
|
||||
from {{ source('oro', 'evaluacion_riesgo') }} e
|
||||
where e.horizonte_anios = {{ var('riesgos_horizonte_banda') }}
|
||||
),
|
||||
|
||||
vigentes as (
|
||||
select lote_id, pac_id, probabilidad, registrado_en from recientes where lugar = 1 and estado = 'final'
|
||||
),
|
||||
|
||||
lote_vigente as (
|
||||
select max(l.lote_id) as lote_id
|
||||
from {{ source('oro', 'evaluacion_riesgo_lote') }} l
|
||||
join {{ source('oro', 'cohorte_armado') }} a on a.armado_id = l.armado_id
|
||||
where a.url = 'cacu/cohorte_vigilancia'
|
||||
and l.lote_id in (select lote_id from vigentes)
|
||||
)
|
||||
|
||||
select
|
||||
m.pac_id,
|
||||
m.fecha_indice,
|
||||
a.armado_en as miembro_conocido_en,
|
||||
v.probabilidad,
|
||||
v.registrado_en as evaluacion_conocida_en
|
||||
from lote_vigente lv
|
||||
join {{ source('oro', 'evaluacion_riesgo_lote') }} l on l.lote_id = lv.lote_id
|
||||
join {{ source('oro', 'cohorte_armado') }} a on a.armado_id = l.armado_id
|
||||
join {{ source('oro', 'cohorte_miembro') }} m on m.armado_id = l.armado_id
|
||||
left join vigentes v on v.lote_id = lv.lote_id and v.pac_id = m.pac_id
|
||||
@@ -0,0 +1,76 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_riesgo_vigilancia
|
||||
description: "Las miembros de la cohorte de vigilancia que puntuó el lote de riesgos vigente, con su probabilidad."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cacu_riesgo_vigilancia
|
||||
description: "Surveillance cohort members scored by the current batch of risk estimates: the band summary's grain."
|
||||
model: ref('cacu_riesgo_vigilancia')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_indice
|
||||
entities:
|
||||
- name: miembro
|
||||
type: primary
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- name: fecha_indice
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: miembro_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: evaluacion_conocida_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: probabilidad
|
||||
type: categorical
|
||||
measures:
|
||||
- name: miembros
|
||||
description: "Distinct members: each patient once."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: cacu_riesgo_banda
|
||||
label: "Pacientes en vigilancia por banda de riesgo de CIN2+"
|
||||
description: >-
|
||||
Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo
|
||||
estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene
|
||||
evaluación confirmada en ese lote.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: miembros
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_RIESGO_BANDA
|
||||
version: 0.1.0
|
||||
scoring: composition
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [miembro_conocido_en]
|
||||
parametros:
|
||||
corte_intermedio: comun.riesgos.corte_intermedio
|
||||
corte_alto: comun.riesgos.corte_alto
|
||||
# One row per member, so nothing to choose between; the category is her probability's band, by rules of the
|
||||
# question: below `corte_intermedio` BAJO, below `corte_alto` INTERMEDIO, else ALTO.
|
||||
categoria:
|
||||
valor: probabilidad
|
||||
sin_dato: SIN_DATO
|
||||
elige: ultimo_valido
|
||||
valido: "{% raw %}{{ Dimension('miembro__probabilidad') }} is not null{% endraw %}"
|
||||
conocida_en: [evaluacion_conocida_en]
|
||||
orden: [fecha_indice]
|
||||
bandas:
|
||||
- {valor: BAJO, menor_que: corte_intermedio}
|
||||
- {valor: INTERMEDIO, menor_que: corte_alto}
|
||||
- {valor: ALTO}
|
||||
@@ -0,0 +1,41 @@
|
||||
-- One row per cytology taken and each biopsy report it led to (one row with nulls when it led to none): the event
|
||||
-- grain of the measures that follow a sample to its biopsy. When the sample and the report became known are the
|
||||
-- start of the loads that wrote them. The birth date is the patient's, for strata by age. The sample's own result
|
||||
-- (with its quality and when it was known) lets a measure pick a patient's last valid sample, and `biopsia_gravedad`
|
||||
-- orders her biopsies from least to most severe by `catalogo_biopsia`: 0 for a grade the catalog doesn't know, -1 for
|
||||
-- a report without one.
|
||||
|
||||
select
|
||||
c.procedimiento_id,
|
||||
c.fuente_id,
|
||||
c.pac_id,
|
||||
c.fecha_toma,
|
||||
toma.inicio as toma_conocida_en,
|
||||
c.resultado,
|
||||
c.calidad_muestra,
|
||||
c.fecha_reporte as citologia_fecha_reporte,
|
||||
resultado.inicio as resultado_conocido_en,
|
||||
b.fuente_id as biopsia_fuente_id,
|
||||
b.fecha_reporte as biopsia_fecha_reporte,
|
||||
b.grado as biopsia_grado,
|
||||
case
|
||||
when b.procedimiento_id is null then null
|
||||
when b.grado is null then -1
|
||||
{%- for grado in var('catalogo_biopsia') %}
|
||||
when b.grado = '{{ grado }}' then {{ loop.index }}
|
||||
{%- endfor %}
|
||||
else 0
|
||||
end as biopsia_gravedad,
|
||||
reporte.inicio as biopsia_conocida_en,
|
||||
persona.fecha_nacimiento
|
||||
from {{ ref('cacu_citologias') }} c
|
||||
join {{ source('silver', 'carga') }} toma
|
||||
on toma.carga_id = c.toma_carga_id
|
||||
join {{ source('silver', 'persona') }} persona
|
||||
on persona.pac_id = c.pac_id
|
||||
left join {{ source('silver', 'carga') }} resultado
|
||||
on resultado.carga_id = c.resultado_carga_id and c.resultado is not null
|
||||
left join {{ ref('cacu_biopsias') }} b
|
||||
on b.toma_id = c.procedimiento_id and b.pac_id = c.pac_id
|
||||
left join {{ source('silver', 'carga') }} reporte
|
||||
on reporte.carga_id = b.reporte_carga_id
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user