Compare commits
126 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0989e6f063 | |||
| b9e73d5a5a | |||
| 06bd9cfc2e | |||
| 86177fa45e | |||
| dc0c493af4 | |||
| 8313623c63 | |||
| 152aa3cca3 | |||
| 6b39935d8e | |||
| e928eeae57 | |||
| 321552224d | |||
| 3f1deada2e | |||
| 8166dd2ee8 | |||
| 360d2f7ab0 | |||
| 9689c60168 | |||
| be9ab7c8df | |||
| cf1213e280 | |||
| 6d87071756 | |||
| 4366a9cb67 | |||
| fe767dae21 | |||
| 2d86d54fe5 | |||
| 4402b77ec7 | |||
| 0df069383f | |||
| a8b4b64873 | |||
| f3f21bb64b | |||
| 74b421d434 | |||
| 07c7a66e3e | |||
| 2b642a57b9 | |||
| cb9ca9d735 | |||
| 21885d6a10 | |||
| 56520a33c6 | |||
| 6a91ba67cf | |||
| 50decaf915 | |||
| 10d30d18c4 | |||
| 5c2c689d47 | |||
| eefefed966 | |||
| 7af7fd12db | |||
| 87977b4ca5 | |||
| 5fdb23a28e | |||
| ba99bbd311 | |||
| f7a5693455 | |||
| 06839a6f35 | |||
| 8ec77fc4f8 | |||
| 1f144a5cec | |||
| 3f1925b775 | |||
| 650b3fdf7b | |||
| f01dcbbde5 | |||
| 9b4e18c345 | |||
| 697702d497 | |||
| 8fc3dda18a | |||
| 26cf87a49a | |||
| 4b363b9c97 | |||
| 5105059c0c | |||
| ddeabab640 | |||
| 1937834b25 | |||
| 655067e47d | |||
| 27caa1173e | |||
| f106a3e09d | |||
| 6ca7f7f368 | |||
| 75a114df94 | |||
| 97b68cc316 | |||
| 6bb7b1d5e9 | |||
| 0b6384097a | |||
| 8ecef0bb03 | |||
| ab82a4c805 | |||
| 9a3f9f2813 | |||
| 315ad3b269 | |||
| 1bbf5d4877 | |||
| 65e153aae8 | |||
| ea316a6d59 | |||
| ea4b8ef235 | |||
| 13e8c4fd87 | |||
| 70f10e57d1 | |||
| 752495bbc8 | |||
| 59de353672 | |||
| ef0cdff393 | |||
| 746ad93c4e | |||
| a67eaa0646 | |||
| 1a8bad2815 | |||
| 8e43dccfe0 | |||
| b8f58585ad | |||
| 2144d60d06 | |||
| 6bd3f40a6c | |||
| 87cfae3969 | |||
| 47046eaea7 | |||
| b81c626013 | |||
| aa840b9f31 | |||
| d2f597cec8 | |||
| cc5738d036 | |||
| 3cd094a8c5 | |||
| 9ace5da517 | |||
| 0017b0ca4c | |||
| 9903e22c2a | |||
| 8885162147 | |||
| 20f244c014 | |||
| 9baeeb7ff0 | |||
| 28d80ad7e3 | |||
| 80e0677b3a | |||
| a6a05febfd | |||
| 1405208c3e | |||
| 64abc56989 | |||
| 72d092d0f3 | |||
| d6e2c68dbf | |||
| 14dff24f85 | |||
| 74eb5a4a4c | |||
| 66c4ba5c5f | |||
| 86b8da08bf | |||
| 7842170a0e | |||
| 087168044e | |||
| 0f3b5851eb | |||
| cb5a56de15 | |||
| 865412ea7a | |||
| 47caff4034 | |||
| cef2c62c3c | |||
| ef872f6b12 | |||
| 5d2d5ea4cb | |||
| 0b8ba5c43a | |||
| 4ce7f21017 | |||
| 5d80c480ef | |||
| 4275f9bcc9 | |||
| 2188d7a5e8 | |||
| d8ff604b6f | |||
| f6d00f51f3 | |||
| 32df6dadf8 | |||
| 362d97af70 | |||
| 461cae1490 | |||
| e6eb3157a3 |
@@ -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
|
||||
|
||||
@@ -13,6 +13,11 @@ class CelulasEscamosas(str, Enum):
|
||||
LIEAG = "LIEAG"
|
||||
CIS = "CIS"
|
||||
|
||||
class CelulasGlandulares(str, Enum):
|
||||
"""Resultado de células glandulares (Bethesda): atípicas o adenocarcinoma."""
|
||||
AGC = "AGC"
|
||||
ADENOCARCINOMA = "ADENOCARCINOMA"
|
||||
|
||||
CELULAS_ESCAMOSAS_ALIAS: dict[str,str] = {
|
||||
# Long forms, as the hospital platform is expected to write them
|
||||
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from core.cacu.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
|
||||
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
|
||||
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CelulasGlandulares, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
|
||||
from core.cacu.biopsia_cervical.enums import GradoCIN, GRADO_CIN_ALIAS
|
||||
from core.cacu.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
|
||||
from core.cacu.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
|
||||
|
||||
@@ -6,6 +6,8 @@ aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
|
||||
staging: `persona` es propia aunque repita a `paciente`.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.indicadores.cohortes import (
|
||||
CohorteArmadoBase,
|
||||
@@ -20,10 +22,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,
|
||||
@@ -67,6 +73,8 @@ from core.indicadores.reportes import (
|
||||
class Persona(CaCuModel, PersonaDerechohabienteBase, table=True):
|
||||
__tablename__ = "persona"
|
||||
|
||||
fecha_defuncion: date | None = None # survival's outcome (`pac_fecha_defuncion`); null while alive or unknown
|
||||
|
||||
|
||||
class PeriodoObservacion(CaCuModel, PeriodoObservacionBase, table=True):
|
||||
__tablename__ = "periodo_observacion"
|
||||
@@ -157,6 +165,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) ---
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
| `pac_id` | Derivado, autoincrement | Llave primaria sustituta |
|
||||
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, índice único, permite lookup desde tablas de resultado |
|
||||
| `pac_fecha_nacimiento` | Hospital, DG2 | Fecha de nacimiento |
|
||||
| `pac_fecha_defuncion` | Hospital, — | Fecha de defunción; nula mientras vive o si se desconoce |
|
||||
| `pac_sexo` | Hospital, DG3 | Sexo biológico |
|
||||
| `pac_codigo_postal` | Hospital, DG4 | Código postal de residencia |
|
||||
| `pac_dependencia` | Hospital, DG5 | Unidad de cobertura o dependencia administrativa |
|
||||
|
||||
@@ -28,6 +28,11 @@ class Paciente(CaCuModel, table=True):
|
||||
pac_fecha_nacimiento: date = Field(
|
||||
sa_column=sa.Column(sa.Date, nullable=False),
|
||||
)
|
||||
# Survival's outcome and a competing risk; null while she is alive or the date is unknown.
|
||||
pac_fecha_defuncion: Optional[date] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Date),
|
||||
)
|
||||
pac_codigo_postal: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(
|
||||
|
||||
@@ -6,6 +6,8 @@ aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
|
||||
staging: `persona` es propia aunque repita a `paciente`.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cama.base import CaMaModel
|
||||
from core.indicadores.cohortes import (
|
||||
CohorteArmadoBase,
|
||||
@@ -20,10 +22,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,
|
||||
@@ -67,6 +73,8 @@ from core.indicadores.reportes import (
|
||||
class Persona(CaMaModel, PersonaDerechohabienteBase, table=True):
|
||||
__tablename__ = "persona"
|
||||
|
||||
fecha_defuncion: date | None = None # survival's outcome (`pac_fecha_defuncion`); null while alive or unknown
|
||||
|
||||
|
||||
class PeriodoObservacion(CaMaModel, PeriodoObservacionBase, table=True):
|
||||
__tablename__ = "periodo_observacion"
|
||||
@@ -157,6 +165,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) ---
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, índice único, permite lookup desde tablas de resultado |
|
||||
| `pac_fecha_nacimiento` | Hospital, DG2 | Fecha de nacimiento |
|
||||
| `pac_sexo` | Hospital, DG3 | Sexo biológico |
|
||||
| `pac_fecha_defuncion` | Hospital, — | Fecha de defunción; nula mientras vive o si se desconoce |
|
||||
| `pac_codigo_postal` | Hospital, DG4 | Código postal de residencia |
|
||||
| `pac_dependencia` | Hospital, DG5 | Unidad de cobertura o dependencia administrativa |
|
||||
| `pac_parentesco` | Hospital, — | Parentesco del titular respecto al trabajador |
|
||||
|
||||
@@ -28,6 +28,11 @@ class Paciente(CaMaModel, table=True):
|
||||
pac_fecha_nacimiento: date = Field(
|
||||
sa_column=sa.Column(sa.Date, nullable=False),
|
||||
)
|
||||
# Survival's outcome; null while she is alive or the date is unknown.
|
||||
pac_fecha_defuncion: Optional[date] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Date),
|
||||
)
|
||||
pac_codigo_postal: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(
|
||||
|
||||
@@ -13,11 +13,31 @@ codigos_hospital = ["..."] # cómo lo nombra el hospital (tipo de estud
|
||||
etiqueta = "..."
|
||||
tipo_valor = "codigo" # codigo, booleano, numero, fecha, texto, externo
|
||||
unidad = "min" # opcional (numero)
|
||||
sistema = "CIE-10" # solo externo
|
||||
sistema = "CIE-10" # externo o codigo: el sistema de códigos de sus valores
|
||||
valores = [ # solo codigo; el orden de la lista es el de presentación
|
||||
{ valor = "NORMAL", etiqueta = "Normal" },
|
||||
]
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
A coded result with `sistema` takes its `valor` from that code system as the system writes it (`8500/3` in CIE-O-3,
|
||||
`T1c` in TNM-AJCC, `C504` in CIE-10): the code is what other systems exchange, and how the hospital or a lab prints
|
||||
it goes in `alias` or, per source, in `cat_mapeo`. A result without `sistema` uses the project's own codes.
|
||||
|
||||
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.
|
||||
|
||||
@@ -26,7 +26,11 @@ valores = [
|
||||
|
||||
[citologia.resultados.celulas_glandulares]
|
||||
etiqueta = "Células glandulares"
|
||||
tipo_valor = "texto"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "AGC", etiqueta = "Células glandulares atípicas (AGC)" },
|
||||
{ valor = "ADENOCARCINOMA", etiqueta = "Adenocarcinoma" },
|
||||
]
|
||||
|
||||
[citologia.resultados.carcinoma_invasor]
|
||||
etiqueta = "Carcinoma invasor"
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
# BI-RADS: el hospital reporta 4A, 4B y 4C, normalizados (usuario, 2026-10-16); un 4 sin subcategoría
|
||||
# también puede llegar (`cama.birads_gravedad` en parametros.toml).
|
||||
|
||||
# Mammography. Procedures: the `toma` (the study, both breasts), its `reporte` (the interpretation), one `parte` of the
|
||||
# report per breast and, inside each breast, one `parte` per finding. Each result says which one it goes in.
|
||||
[mastografia]
|
||||
etiqueta = "Mastografía"
|
||||
codigos_hospital = ["MASTOGRAFIA"]
|
||||
|
||||
# In the toma.
|
||||
[mastografia.resultados.calidad_imagen]
|
||||
etiqueta = "Calidad de la imagen"
|
||||
tipo_valor = "codigo"
|
||||
@@ -14,6 +17,21 @@ valores = [
|
||||
{ valor = "INSATISFACTORIO", etiqueta = "Insatisfactoria" },
|
||||
]
|
||||
|
||||
# In the toma. Screening or diagnostic (NOM-041-SSA2-2011, 7.3.3 and 9.2): the registry's method of primary detection
|
||||
# (Apéndice Normativo G). SEGUIMIENTO is the six-monthly control of a BI-RADS 3 (14.4.5.4).
|
||||
[mastografia.resultados.tipo_estudio]
|
||||
etiqueta = "Tipo de estudio"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Tipo de estudio", "Estudio", "Indicación"]
|
||||
valores = [
|
||||
{ valor = "TAMIZAJE", etiqueta = "Tamizaje", alias = ["Tamizaje", "Detección", "Escrutinio", "Screening"] },
|
||||
{ valor = "DIAGNOSTICA", etiqueta = "Diagnóstica", alias = ["Diagnóstica", "Diagnóstico"] },
|
||||
{ valor = "SEGUIMIENTO", etiqueta = "Seguimiento", alias = ["Seguimiento", "Control"] },
|
||||
]
|
||||
|
||||
# In the report (the final category) and in each breast's part (that breast's); the last BI-RADS edition, 7.3.4.1
|
||||
# and 9.2.
|
||||
[mastografia.resultados.birads]
|
||||
etiqueta = "BI-RADS"
|
||||
tipo_valor = "codigo"
|
||||
@@ -30,10 +48,98 @@ valores = [
|
||||
{ valor = "B6", etiqueta = "BI-RADS 6" },
|
||||
]
|
||||
|
||||
# In the report. 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"] },
|
||||
]
|
||||
|
||||
# In each breast's part.
|
||||
[mastografia.resultados.lateralidad]
|
||||
etiqueta = "Mama"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Mama", "Lado", "Lateralidad"]
|
||||
valores = [
|
||||
{ valor = "DERECHA", etiqueta = "Derecha", alias = ["Mama derecha", "MD", "Der"] },
|
||||
{ valor = "IZQUIERDA", etiqueta = "Izquierda", alias = ["Mama izquierda", "MI", "Izq"] },
|
||||
]
|
||||
|
||||
# In each finding's part: the BI-RADS lexicon's kinds of finding.
|
||||
[mastografia.resultados.tipo_hallazgo]
|
||||
etiqueta = "Tipo de hallazgo"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Hallazgo", "Hallazgos", "Tipo de hallazgo"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "MASA", etiqueta = "Masa", alias = ["Masa", "Nódulo", "Tumoración"] },
|
||||
{ valor = "CALCIFICACIONES", etiqueta = "Calcificaciones", alias = ["Calcificaciones", "Microcalcificaciones"] },
|
||||
{ valor = "ASIMETRIA", etiqueta = "Asimetría", alias = ["Asimetría", "Asimetría focal", "Asimetría global", "Asimetría en desarrollo", "Densidad asimétrica"] },
|
||||
{ valor = "DISTORSION_ARQUITECTURAL", etiqueta = "Distorsión de la arquitectura", alias = ["Distorsión de la arquitectura", "Distorsión arquitectural"] },
|
||||
{ valor = "GANGLIO_INTRAMAMARIO", etiqueta = "Ganglio intramamario", alias = ["Ganglio intramamario"] },
|
||||
{ valor = "LESION_CUTANEA", etiqueta = "Lesión cutánea", alias = ["Lesión cutánea", "Lesión de piel"] },
|
||||
{ valor = "CONDUCTO_DILATADO", etiqueta = "Conducto dilatado solitario", alias = ["Conducto dilatado", "Ectasia ductal"] },
|
||||
]
|
||||
|
||||
# In each finding's part that is a mass: its margin in the BI-RADS lexicon (5th edition). A spiculated margin is the
|
||||
# strongest single sign of malignancy.
|
||||
[mastografia.resultados.margen_masa]
|
||||
etiqueta = "Margen de la masa"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Margen", "Márgenes", "Bordes", "Contorno"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "CIRCUNSCRITO", etiqueta = "Circunscrito", alias = ["Circunscrito", "Bien definido", "Bordes definidos", "Bordes regulares"] },
|
||||
{ valor = "OSCURECIDO", etiqueta = "Oscurecido", alias = ["Oscurecido", "Obscurecido", "Parcialmente oscurecido"] },
|
||||
{ valor = "MICROLOBULADO", etiqueta = "Microlobulado", alias = ["Microlobulado", "Microlobulados"] },
|
||||
{ valor = "INDISTINTO", etiqueta = "Indistinto", alias = ["Indistinto", "Mal definido", "Bordes mal definidos", "Bordes irregulares"] },
|
||||
{ valor = "ESPICULADO", etiqueta = "Espiculado", alias = ["Espiculado", "Espiculada", "Bordes espiculados", "Espículas"] },
|
||||
]
|
||||
|
||||
# In each finding's part.
|
||||
[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"]
|
||||
|
||||
# In each finding's part: the subsite by its ICD-10 code, as `biopsia.localizacion`.
|
||||
[mastografia.resultados.localizacion]
|
||||
etiqueta = "Localización en la mama"
|
||||
tipo_valor = "codigo"
|
||||
sistema = "CIE-10"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Localización", "Cuadrante", "Sitio"]
|
||||
valores = [
|
||||
{ valor = "C500", etiqueta = "Pezón y areola", alias = ["C50.0", "Pezón", "Areola", "Retroareolar"] },
|
||||
{ valor = "C501", etiqueta = "Porción central", alias = ["C50.1", "Central"] },
|
||||
{ valor = "C502", etiqueta = "Cuadrante superior interno", alias = ["C50.2", "CSI", "Superior interno"] },
|
||||
{ valor = "C503", etiqueta = "Cuadrante inferior interno", alias = ["C50.3", "CII", "Inferior interno"] },
|
||||
{ valor = "C504", etiqueta = "Cuadrante superior externo", alias = ["C50.4", "CSE", "Superior externo"] },
|
||||
{ valor = "C505", etiqueta = "Cuadrante inferior externo", alias = ["C50.5", "CIE", "Inferior externo"] },
|
||||
{ valor = "C506", etiqueta = "Prolongación axilar", alias = ["C50.6", "Cola axilar", "Prolongación axilar"] },
|
||||
{ valor = "C508", etiqueta = "Lesión de sitios contiguos", alias = ["C50.8", "Unión de cuadrantes", "Sitios contiguos"] },
|
||||
{ valor = "C509", etiqueta = "Mama, parte no especificada", alias = ["C50.9", "No especificada"] },
|
||||
]
|
||||
|
||||
# Biopsy and surgical specimen. Procedures: the `orden` (the request), one `toma` per breast (a surgical specimen's
|
||||
# hangs from its `cirugia`) and its `reporte` (the pathology report, NOM-041-SSA2-2011 8.3.5).
|
||||
[biopsia]
|
||||
etiqueta = "Biopsia de mama"
|
||||
codigos_hospital = ["BIOPSIA_CHICA"]
|
||||
|
||||
# In the report.
|
||||
[biopsia.resultados.grado]
|
||||
etiqueta = "Grado histológico"
|
||||
tipo_valor = "codigo"
|
||||
@@ -48,6 +154,335 @@ valores = [
|
||||
etiqueta = "Fecha de solicitud"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
# In the toma (8.3.5.1).
|
||||
[biopsia.resultados.lateralidad]
|
||||
etiqueta = "Mama"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Mama", "Lado", "Lateralidad"]
|
||||
valores = [
|
||||
{ valor = "DERECHA", etiqueta = "Derecha", alias = ["Mama derecha", "MD", "Der"] },
|
||||
{ valor = "IZQUIERDA", etiqueta = "Izquierda", alias = ["Mama izquierda", "MI", "Izq"] },
|
||||
]
|
||||
|
||||
# In the toma. The subsite of the breast by its ICD-10 code, as the hospital writes diagnoses (`nota_medica.diagnostico`);
|
||||
# ICD-O-3's topography uses the same codes, so this is also the registry's anatomical site (Apéndice Normativo G).
|
||||
[biopsia.resultados.localizacion]
|
||||
etiqueta = "Localización en la mama"
|
||||
tipo_valor = "codigo"
|
||||
sistema = "CIE-10"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Localización", "Cuadrante", "Sitio", "Topografía"]
|
||||
valores = [
|
||||
{ valor = "C500", etiqueta = "Pezón y areola", alias = ["C50.0", "Pezón", "Areola", "Retroareolar"] },
|
||||
{ valor = "C501", etiqueta = "Porción central", alias = ["C50.1", "Central"] },
|
||||
{ valor = "C502", etiqueta = "Cuadrante superior interno", alias = ["C50.2", "CSI", "Superior interno"] },
|
||||
{ valor = "C503", etiqueta = "Cuadrante inferior interno", alias = ["C50.3", "CII", "Inferior interno"] },
|
||||
{ valor = "C504", etiqueta = "Cuadrante superior externo", alias = ["C50.4", "CSE", "Superior externo"] },
|
||||
{ valor = "C505", etiqueta = "Cuadrante inferior externo", alias = ["C50.5", "CIE", "Inferior externo"] },
|
||||
{ valor = "C506", etiqueta = "Prolongación axilar", alias = ["C50.6", "Cola axilar", "Prolongación axilar"] },
|
||||
{ valor = "C508", etiqueta = "Lesión de sitios contiguos", alias = ["C50.8", "Unión de cuadrantes", "Sitios contiguos"] },
|
||||
{ valor = "C509", etiqueta = "Mama, parte no especificada", alias = ["C50.9", "No especificada"] },
|
||||
]
|
||||
|
||||
# In the toma: how the tissue was obtained (3.5, 8.3.4); a surgical specimen's surgery is its `cirugia`.
|
||||
[biopsia.resultados.tipo_biopsia]
|
||||
etiqueta = "Tipo de biopsia"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Tipo de biopsia", "Tipo de espécimen", "Tipo de muestra", "Procedimiento", "Espécimen"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "BAAF", etiqueta = "Aspiración con aguja fina", alias = ["BAAF", "Biopsia por aspiración con aguja fina", "Aspiración con aguja fina"] },
|
||||
{ valor = "AGUJA_CORTE", etiqueta = "Aguja de corte grueso (14 a 18 G)", alias = ["Aguja de corte", "Aguja de corte grueso", "Biopsia con aguja de corte", "Tru-cut", "Trucut", "Core"] },
|
||||
{ valor = "ASPIRACION_VACIO", etiqueta = "Aguja de corte con aspiración por vacío (8 a 14 G)", alias = ["Aspiración por vacío", "Biopsia asistida por vacío", "Mammotome", "BAV"] },
|
||||
{ valor = "ESCISIONAL", etiqueta = "Biopsia escisional", alias = ["Escisional", "Biopsia escisional", "Biopsia excisional"] },
|
||||
{ valor = "PIEZA_QUIRURGICA", etiqueta = "Pieza quirúrgica", alias = ["Pieza quirúrgica", "Segmentectomía", "Cuadrantectomía", "Mastectomía", "Tumorectomía", "Lumpectomía"] },
|
||||
]
|
||||
|
||||
# Provisional, as the mammography's. The values are the
|
||||
# WHO classification of breast tumours (NOM-041-SSA2-2011, 8.3.6 and Apéndice Informativo C) by their ICD-O-3
|
||||
# morphology code, which the case registry asks for (Apéndice Normativo G). The NOM prints 8211/3 for medullary
|
||||
# carcinoma and 8290/2 for oncocytic carcinoma; ICD-O-3 gives 8510/3 and 8290/3. A lesion the WHO list names
|
||||
# without a code (atypical ductal hyperplasia, radial scar) isn't a value here.
|
||||
[biopsia.resultados.tipo_histologico]
|
||||
etiqueta = "Tipo histológico (OMS)"
|
||||
tipo_valor = "codigo"
|
||||
sistema = "CIE-O-3"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Tipo histológico", "Diagnóstico histopatológico", "Diagnóstico", "Variedad histológica"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "8500/3", etiqueta = "Carcinoma ductal invasivo (sin tipo especial)", alias = ["8500/3", "Carcinoma ductal infiltrante", "Ductal infiltrante", "Carcinoma ductal invasor", "Carcinoma infiltrante de tipo no especial", "Carcinoma ductal invasivo", "CDI"] },
|
||||
{ valor = "8520/3", etiqueta = "Carcinoma lobulillar invasivo", alias = ["8520/3", "Carcinoma lobulillar infiltrante", "Lobulillar infiltrante", "Carcinoma lobulillar invasor", "Carcinoma lobular invasivo", "CLI"] },
|
||||
{ valor = "8211/3", etiqueta = "Carcinoma tubular", alias = ["8211/3"] },
|
||||
{ valor = "8201/3", etiqueta = "Carcinoma cribiforme invasivo", alias = ["8201/3", "Carcinoma cribiforme"] },
|
||||
{ valor = "8510/3", etiqueta = "Carcinoma medular", alias = ["8510/3"] },
|
||||
{ valor = "8480/3", etiqueta = "Carcinoma mucinoso", alias = ["8480/3", "Carcinoma coloide"] },
|
||||
{ valor = "8490/3", etiqueta = "Carcinoma de células en anillo de sello", alias = ["8490/3"] },
|
||||
{ valor = "8503/3", etiqueta = "Carcinoma papilar invasivo", alias = ["8503/3"] },
|
||||
{ valor = "8507/3", etiqueta = "Carcinoma micropapilar invasivo", alias = ["8507/3"] },
|
||||
{ valor = "8401/3", etiqueta = "Carcinoma apocrino", alias = ["8401/3", "Carcinoma apócrino"] },
|
||||
{ valor = "8575/3", etiqueta = "Carcinoma metaplásico", alias = ["8575/3", "Carcinoma metaplásicos"] },
|
||||
{ valor = "8070/3", etiqueta = "Carcinoma de células escamosas", alias = ["8070/3", "Carcinoma epidermoide"] },
|
||||
{ valor = "8572/3", etiqueta = "Adenocarcinoma con metaplasia de células fusiformes", alias = ["8572/3"] },
|
||||
{ valor = "8560/3", etiqueta = "Carcinoma adenoescamoso", alias = ["8560/3"] },
|
||||
{ valor = "8430/3", etiqueta = "Carcinoma mucoepidermoide", alias = ["8430/3"] },
|
||||
{ valor = "8022/3", etiqueta = "Carcinoma pleomórfico", alias = ["8022/3"] },
|
||||
{ valor = "8035/3", etiqueta = "Carcinoma con células gigantes osteoclásticas", alias = ["8035/3", "Carcinoma con células osteoclásticas gigantes"] },
|
||||
{ valor = "8249/3", etiqueta = "Carcinoma neuroendocrino sólido", alias = ["8249/3"] },
|
||||
{ valor = "8041/3", etiqueta = "Carcinoma de células pequeñas", alias = ["8041/3", "Carcinoma de células avenoides pequeñas"] },
|
||||
{ valor = "8013/3", etiqueta = "Carcinoma neuroendocrino de células grandes", alias = ["8013/3"] },
|
||||
{ valor = "8314/3", etiqueta = "Carcinoma rico en lípidos", alias = ["8314/3"] },
|
||||
{ valor = "8502/3", etiqueta = "Carcinoma secretor", alias = ["8502/3"] },
|
||||
{ valor = "8290/3", etiqueta = "Carcinoma oncocítico", alias = ["8290/3"] },
|
||||
{ valor = "8200/3", etiqueta = "Carcinoma adenoide quístico", alias = ["8200/3"] },
|
||||
{ valor = "8550/3", etiqueta = "Carcinoma de células acinares", alias = ["8550/3", "Carcinoma de células acínicas"] },
|
||||
{ valor = "8315/3", etiqueta = "Carcinoma de células claras rico en glucógeno", alias = ["8315/3"] },
|
||||
{ valor = "8410/3", etiqueta = "Carcinoma sebáceo", alias = ["8410/3"] },
|
||||
{ valor = "8530/3", etiqueta = "Carcinoma inflamatorio", alias = ["8530/3"] },
|
||||
{ valor = "8540/3", etiqueta = "Enfermedad de Paget del pezón", alias = ["8540/3", "Enfermedad de Paget de la mama", "Enfermedad de Paget"] },
|
||||
{ valor = "8982/3", etiqueta = "Mioepitelioma maligno", alias = ["8982/3"] },
|
||||
{ valor = "9020/3", etiqueta = "Tumor filodes maligno", alias = ["9020/3"] },
|
||||
{ valor = "9120/3", etiqueta = "Angiosarcoma", alias = ["9120/3"] },
|
||||
{ valor = "8850/3", etiqueta = "Liposarcoma", alias = ["8850/3"] },
|
||||
{ valor = "8900/3", etiqueta = "Rabdomiosarcoma", alias = ["8900/3"] },
|
||||
{ valor = "9180/3", etiqueta = "Osteosarcoma", alias = ["9180/3"] },
|
||||
{ valor = "8890/3", etiqueta = "Leiomiosarcoma", alias = ["8890/3"] },
|
||||
{ valor = "9680/3", etiqueta = "Linfoma difuso de células B grandes", alias = ["9680/3", "Linfoma difuso de células B"] },
|
||||
{ valor = "9687/3", etiqueta = "Linfoma de Burkitt", alias = ["9687/3"] },
|
||||
{ valor = "9699/3", etiqueta = "Linfoma extranodal de células B tipo MALT", alias = ["9699/3"] },
|
||||
{ valor = "9690/3", etiqueta = "Linfoma folicular", alias = ["9690/3"] },
|
||||
# Not in the WHO list, but coded by cancer registries (SEER) for breast primaries.
|
||||
{ valor = "8522/3", etiqueta = "Carcinoma ductal y lobulillar infiltrante", alias = ["8522/3", "Carcinoma ductal y lobulillar", "Carcinoma mixto ductal y lobulillar", "Carcinoma ductolobulillar"] },
|
||||
{ valor = "8523/3", etiqueta = "Carcinoma ductal infiltrante mixto con otros tipos", alias = ["8523/3"] },
|
||||
{ valor = "8521/3", etiqueta = "Carcinoma ductular infiltrante", alias = ["8521/3"] },
|
||||
{ valor = "8541/3", etiqueta = "Enfermedad de Paget con carcinoma ductal infiltrante", alias = ["8541/3"] },
|
||||
{ valor = "8543/3", etiqueta = "Enfermedad de Paget con carcinoma intraductal", alias = ["8543/3"] },
|
||||
{ valor = "8509/3", etiqueta = "Carcinoma papilar sólido invasivo", alias = ["8509/3"] },
|
||||
{ valor = "8504/3", etiqueta = "Carcinoma papilar encapsulado invasivo", alias = ["8504/3"] },
|
||||
{ valor = "8050/3", etiqueta = "Carcinoma papilar, SAI", alias = ["8050/3"] },
|
||||
{ valor = "8032/3", etiqueta = "Carcinoma de células fusiformes", alias = ["8032/3"] },
|
||||
{ valor = "8246/3", etiqueta = "Carcinoma neuroendocrino, SAI", alias = ["8246/3"] },
|
||||
{ valor = "8255/3", etiqueta = "Adenocarcinoma con subtipos mixtos", alias = ["8255/3"] },
|
||||
{ valor = "8140/3", etiqueta = "Adenocarcinoma, SAI", alias = ["8140/3", "Adenocarcinoma"] },
|
||||
{ valor = "8010/3", etiqueta = "Carcinoma, SAI", alias = ["8010/3", "Carcinoma"] },
|
||||
{ valor = "8000/3", etiqueta = "Neoplasia maligna", alias = ["8000/3", "Neoplasia maligna", "Tumor maligno"] },
|
||||
{ valor = "8500/2", etiqueta = "Carcinoma ductal in situ", alias = ["8500/2", "Ductal in situ", "Carcinoma intraductal", "CDIS"] },
|
||||
{ valor = "8520/2", etiqueta = "Carcinoma lobulillar in situ", alias = ["8520/2", "Carcinoma lobular in situ", "CLIS"] },
|
||||
{ valor = "8503/2", etiqueta = "Carcinoma papilar intraductal", alias = ["8503/2"] },
|
||||
{ valor = "8504/2", etiqueta = "Carcinoma papilar intraquístico", alias = ["8504/2"] },
|
||||
{ valor = "9020/1", etiqueta = "Tumor filodes limítrofe", alias = ["9020/1", "Tumor filodes borderline"] },
|
||||
{ valor = "8821/1", etiqueta = "Fibromatosis (agresiva)", alias = ["8821/1"] },
|
||||
{ valor = "8825/1", etiqueta = "Tumor miofibroblástico inflamatorio", alias = ["8825/1"] },
|
||||
{ valor = "9150/1", etiqueta = "Hemangiopericitoma", alias = ["9150/1"] },
|
||||
{ valor = "9010/0", etiqueta = "Fibroadenoma", alias = ["9010/0"] },
|
||||
{ valor = "9020/0", etiqueta = "Tumor filodes benigno", alias = ["9020/0"] },
|
||||
{ valor = "8503/0", etiqueta = "Papiloma intraductal", alias = ["8503/0", "Papiloma central", "Papiloma periférico", "Adenoma ductal"] },
|
||||
{ valor = "8211/0", etiqueta = "Adenoma tubular", alias = ["8211/0"] },
|
||||
{ valor = "8204/0", etiqueta = "Adenoma de la lactancia", alias = ["8204/0"] },
|
||||
{ valor = "8401/0", etiqueta = "Adenoma apocrino", alias = ["8401/0", "Adenoma apócrino"] },
|
||||
{ valor = "8940/0", etiqueta = "Adenoma pleomórfico", alias = ["8940/0"] },
|
||||
{ valor = "8983/0", etiqueta = "Adenomioepitelioma", alias = ["8983/0"] },
|
||||
{ valor = "8506/0", etiqueta = "Adenoma del pezón", alias = ["8506/0", "Adenoma de pezón"] },
|
||||
{ valor = "8407/0", etiqueta = "Adenoma siringomatoso", alias = ["8407/0"] },
|
||||
{ valor = "8825/0", etiqueta = "Miofibroblastoma", alias = ["8825/0"] },
|
||||
{ valor = "9120/0", etiqueta = "Hemangioma", alias = ["9120/0"] },
|
||||
{ valor = "8850/0", etiqueta = "Lipoma", alias = ["8850/0"] },
|
||||
{ valor = "8861/0", etiqueta = "Angiolipoma", alias = ["8861/0"] },
|
||||
{ valor = "9580/0", etiqueta = "Tumor de células granulares", alias = ["9580/0", "Tumor de células granulosas"] },
|
||||
{ valor = "9540/0", etiqueta = "Neurofibroma", alias = ["9540/0"] },
|
||||
{ valor = "9560/0", etiqueta = "Schwannoma", alias = ["9560/0"] },
|
||||
{ valor = "8890/0", etiqueta = "Leiomioma", alias = ["8890/0"] },
|
||||
]
|
||||
|
||||
[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"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "G1", etiqueta = "Grado 1", alias = ["1", "I", "Grado I", "Bien diferenciado", "1 de Nottingham", "Nottingham 1"] },
|
||||
{ valor = "G2", etiqueta = "Grado 2", alias = ["2", "II", "Grado II", "Moderadamente diferenciado", "2 de Nottingham", "Nottingham 2"] },
|
||||
{ valor = "G3", etiqueta = "Grado 3", alias = ["3", "III", "Grado III", "Poco diferenciado", "3 de Nottingham", "Nottingham 3"] },
|
||||
]
|
||||
|
||||
[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/neu (IHQ)", "HER2 (IHQ)", "HER2 IHQ", "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 = ["Índice de proliferación Ki-67", "Índice de proliferación Ki67", "Ki-67", "Ki67", "Índice de proliferación"]
|
||||
|
||||
# The confirmation by in situ hybridization of an equivocal HER2 (Apéndice Informativo B: negative under 4 copies
|
||||
# per nucleus or a HER2/CEP17 ratio under 1.8, positive over 6 or over 2.2).
|
||||
[biopsia.resultados.her2_fish]
|
||||
etiqueta = "HER2 (hibridación in situ)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["FISH", "HER2 FISH", "Hibridación in situ", "SISH", "CISH"]
|
||||
valores = [
|
||||
{ valor = "NEGATIVO", etiqueta = "No amplificado", alias = ["Negativo", "No amplificado"] },
|
||||
{ valor = "EQUIVOCO", etiqueta = "Equívoco", alias = ["Equívoco", "Indeterminado"] },
|
||||
{ valor = "POSITIVO", etiqueta = "Amplificado", alias = ["Positivo", "Amplificado"] },
|
||||
]
|
||||
|
||||
# The tumour's largest dimension; for an in situ carcinoma, its size or extent. T in `pt` is read from it
|
||||
# (Apéndice Normativo E: T1 up to 20 mm, T2 up to 50 mm, T3 beyond).
|
||||
[biopsia.resultados.tamano_tumor_mm]
|
||||
etiqueta = "Tamaño del tumor"
|
||||
tipo_valor = "numero"
|
||||
unidad = "mm"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Tamaño del tumor", "Tamaño tumoral", "Tamaño de la lesión", "Extensión de la lesión", "Diámetro mayor", "Tumor mide"]
|
||||
|
||||
[biopsia.resultados.invasion_linfovascular]
|
||||
etiqueta = "Invasión vascular o linfática"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Invasión linfovascular", "Invasión vascular", "Invasión linfática", "Permeación linfovascular", "Permeación vascular"]
|
||||
valores = [
|
||||
{ valor = "PRESENTE", etiqueta = "Presente", alias = ["Presente", "Positiva", "Sí", "Identificada"] },
|
||||
{ valor = "AUSENTE", etiqueta = "Ausente", alias = ["Ausente", "Negativa", "No", "No identificada"] },
|
||||
]
|
||||
|
||||
# The nodes: counts, which the St. Gallen risk categories read (Apéndice Normativo F: 1 to 3, 4 or more), and pN.
|
||||
[biopsia.resultados.ganglios_examinados]
|
||||
etiqueta = "Ganglios linfáticos examinados"
|
||||
tipo_valor = "numero"
|
||||
unidad = "ganglios"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Ganglios examinados", "Ganglios disecados", "Ganglios disecados totales", "Ganglios linfáticos examinados"]
|
||||
|
||||
[biopsia.resultados.ganglios_positivos]
|
||||
etiqueta = "Ganglios linfáticos con metástasis"
|
||||
tipo_valor = "numero"
|
||||
unidad = "ganglios"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Ganglios positivos", "Ganglios con metástasis", "Ganglios metastásicos", "Ganglios comprometidos"]
|
||||
|
||||
# Pathological T and N (Apéndice Normativo E). The values are the AJCC categories the NOM lists, written as AJCC
|
||||
# writes them; a subcategory the NOM doesn't list for N (N2a, N3b, a 7th or 8th edition's pN1a) is an alias of its
|
||||
# category, and the node counts keep what it adds.
|
||||
[biopsia.resultados.pt]
|
||||
etiqueta = "T patológica (pT)"
|
||||
tipo_valor = "codigo"
|
||||
sistema = "TNM-AJCC"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["pT", "T patológica", "Tumor primario (pT)"]
|
||||
valores = [
|
||||
{ valor = "TX", etiqueta = "TX", alias = ["pTX"] },
|
||||
{ valor = "T0", etiqueta = "T0", alias = ["pT0"] },
|
||||
{ valor = "Tis", etiqueta = "Tis", alias = ["pTis"] },
|
||||
{ valor = "T1mi", etiqueta = "T1mi", alias = ["pT1mi", "T1mic", "pT1mic"] },
|
||||
{ valor = "T1a", etiqueta = "T1a", alias = ["pT1a"] },
|
||||
{ valor = "T1b", etiqueta = "T1b", alias = ["pT1b"] },
|
||||
{ valor = "T1c", etiqueta = "T1c", alias = ["pT1c"] },
|
||||
{ valor = "T1", etiqueta = "T1", alias = ["pT1"] },
|
||||
{ valor = "T2", etiqueta = "T2", alias = ["pT2"] },
|
||||
{ valor = "T3", etiqueta = "T3", alias = ["pT3"] },
|
||||
{ valor = "T4a", etiqueta = "T4a", alias = ["pT4a"] },
|
||||
{ valor = "T4b", etiqueta = "T4b", alias = ["pT4b"] },
|
||||
{ valor = "T4c", etiqueta = "T4c", alias = ["pT4c"] },
|
||||
{ valor = "T4d", etiqueta = "T4d", alias = ["pT4d"] },
|
||||
{ valor = "T4", etiqueta = "T4", alias = ["pT4"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.pn]
|
||||
etiqueta = "N patológica (pN)"
|
||||
tipo_valor = "codigo"
|
||||
sistema = "TNM-AJCC"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["pN", "N patológica", "Ganglios linfáticos regionales (pN)"]
|
||||
valores = [
|
||||
{ valor = "NX", etiqueta = "NX", alias = ["pNX"] },
|
||||
{ valor = "N0", etiqueta = "N0", alias = ["pN0", "pN0(i-)", "pN0(i+)", "pN0(mol-)", "pN0(mol+)"] },
|
||||
{ valor = "N1", etiqueta = "N1", alias = ["pN1", "pN1mi", "pN1a", "pN1b", "pN1c", "pN1bI", "pN1bII", "pN1bIII", "pN1bIV"] },
|
||||
{ valor = "N2", etiqueta = "N2", alias = ["pN2", "pN2a", "pN2b"] },
|
||||
{ valor = "N3", etiqueta = "N3", alias = ["pN3", "pN3a", "pN3b", "pN3c"] },
|
||||
]
|
||||
|
||||
# In the report of an excisional or surgical specimen (8.3.5.8): a needle biopsy has none of these.
|
||||
[biopsia.resultados.margenes]
|
||||
etiqueta = "Márgenes quirúrgicos"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Márgenes quirúrgicos", "Márgenes", "Bordes quirúrgicos", "Bordes de sección", "Lechos quirúrgicos"]
|
||||
valores = [
|
||||
{ valor = "LIBRES", etiqueta = "Libres", alias = ["Libres", "Negativos", "Libres de neoplasia", "Sin neoplasia"] },
|
||||
{ valor = "CERCANOS", etiqueta = "Cercanos", alias = ["Cercanos", "Próximos"] },
|
||||
{ valor = "AFECTADOS", etiqueta = "Afectados", alias = ["Afectados", "Positivos", "Comprometidos", "Con neoplasia"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.multicentricidad]
|
||||
etiqueta = "Multicentricidad"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Multicentricidad", "Multicéntrico"]
|
||||
valores = [
|
||||
{ valor = "PRESENTE", etiqueta = "Presente", alias = ["Presente", "Sí", "Multicéntrico"] },
|
||||
{ valor = "AUSENTE", etiqueta = "Ausente", alias = ["Ausente", "No", "Unicéntrico"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.multifocalidad]
|
||||
etiqueta = "Multifocalidad"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Multifocalidad", "Multifocal"]
|
||||
valores = [
|
||||
{ valor = "PRESENTE", etiqueta = "Presente", alias = ["Presente", "Sí", "Multifocal"] },
|
||||
{ valor = "AUSENTE", etiqueta = "Ausente", alias = ["Ausente", "No", "Unifocal"] },
|
||||
]
|
||||
|
||||
# Medical note: an `encuentro`.
|
||||
[nota_medica]
|
||||
etiqueta = "Nota médica"
|
||||
|
||||
@@ -56,15 +491,333 @@ 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"
|
||||
valores = [
|
||||
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
|
||||
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
|
||||
{ valor = "ONCOLOGIA_MEDICA", etiqueta = "Oncología médica" },
|
||||
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
|
||||
]
|
||||
|
||||
# The kind of visit, as Core's `TipoNota`. A discharge note (EGRESO, URG_EGRESO) is where a discharge reason, death
|
||||
# among them, would be written: survival's outcome.
|
||||
[nota_medica.resultados.tipo_nota]
|
||||
etiqueta = "Tipo de nota"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "CONSULTA", etiqueta = "Consulta" },
|
||||
{ valor = "INGRESO", etiqueta = "Ingreso hospitalario" },
|
||||
{ valor = "EGRESO", etiqueta = "Egreso hospitalario" },
|
||||
{ valor = "URG_EGRESO", etiqueta = "Egreso de urgencias" },
|
||||
]
|
||||
|
||||
# Clinical T, N and M (Apéndice Normativo E).
|
||||
[nota_medica.resultados.ct]
|
||||
etiqueta = "T clínica (cT)"
|
||||
tipo_valor = "codigo"
|
||||
sistema = "TNM-AJCC"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["cT", "T clínica", "Tumor primario"]
|
||||
valores = [
|
||||
{ valor = "TX", etiqueta = "TX", alias = ["cTX"] },
|
||||
{ valor = "T0", etiqueta = "T0", alias = ["cT0"] },
|
||||
{ valor = "Tis", etiqueta = "Tis", alias = ["cTis"] },
|
||||
{ valor = "T1mi", etiqueta = "T1mi", alias = ["cT1mi", "T1mic"] },
|
||||
{ valor = "T1a", etiqueta = "T1a", alias = ["cT1a"] },
|
||||
{ valor = "T1b", etiqueta = "T1b", alias = ["cT1b"] },
|
||||
{ valor = "T1c", etiqueta = "T1c", alias = ["cT1c"] },
|
||||
{ valor = "T1", etiqueta = "T1", alias = ["cT1"] },
|
||||
{ valor = "T2", etiqueta = "T2", alias = ["cT2"] },
|
||||
{ valor = "T3", etiqueta = "T3", alias = ["cT3"] },
|
||||
{ valor = "T4a", etiqueta = "T4a", alias = ["cT4a"] },
|
||||
{ valor = "T4b", etiqueta = "T4b", alias = ["cT4b"] },
|
||||
{ valor = "T4c", etiqueta = "T4c", alias = ["cT4c"] },
|
||||
{ valor = "T4d", etiqueta = "T4d", alias = ["cT4d", "Carcinoma inflamatorio"] },
|
||||
{ valor = "T4", etiqueta = "T4", alias = ["cT4"] },
|
||||
]
|
||||
|
||||
[nota_medica.resultados.cn]
|
||||
etiqueta = "N clínica (cN)"
|
||||
tipo_valor = "codigo"
|
||||
sistema = "TNM-AJCC"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["cN", "N clínica", "Ganglios linfáticos regionales"]
|
||||
valores = [
|
||||
{ valor = "NX", etiqueta = "NX", alias = ["cNX"] },
|
||||
{ valor = "N0", etiqueta = "N0", alias = ["cN0"] },
|
||||
{ valor = "N1", etiqueta = "N1", alias = ["cN1", "N1mi"] },
|
||||
{ valor = "N2", etiqueta = "N2", alias = ["cN2", "N2a", "N2b", "cN2a", "cN2b"] },
|
||||
{ valor = "N3", etiqueta = "N3", alias = ["cN3", "N3a", "N3b", "N3c", "cN3a", "cN3b", "cN3c"] },
|
||||
]
|
||||
|
||||
[nota_medica.resultados.m]
|
||||
etiqueta = "Metástasis a distancia (M)"
|
||||
tipo_valor = "codigo"
|
||||
sistema = "TNM-AJCC"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Metástasis a distancia", "Metástasis distante", "cM"]
|
||||
valores = [
|
||||
{ valor = "MX", etiqueta = "MX", alias = ["cMX"] },
|
||||
{ valor = "M0", etiqueta = "M0", alias = ["cM0", "Mo", "M0(i+)"] },
|
||||
{ valor = "M1", etiqueta = "M1", alias = ["cM1", "pM1"] },
|
||||
]
|
||||
|
||||
# The visit's body measurements.
|
||||
[nota_medica.resultados.peso]
|
||||
etiqueta = "Peso"
|
||||
tipo_valor = "numero"
|
||||
unidad = "kg"
|
||||
|
||||
[nota_medica.resultados.talla]
|
||||
etiqueta = "Talla"
|
||||
tipo_valor = "numero"
|
||||
unidad = "m"
|
||||
|
||||
[nota_medica.resultados.imc]
|
||||
etiqueta = "Índice de masa corporal"
|
||||
tipo_valor = "numero"
|
||||
unidad = "kg/m2"
|
||||
|
||||
# The risk factors the clinical history investigates (NOM-041-SSA2-2011, 7.1.1 and 8.2.1.1): a `parte` hanging from
|
||||
# the document they were recorded in (a note, a mammogram's intake interview), dated by it, so what changes
|
||||
# (menopause) is read as of a date. Age comes from the birth date, density from the mammogram, BRCA from its own
|
||||
# test (`prueba_genetica`).
|
||||
[factores_riesgo]
|
||||
etiqueta = "Factores de riesgo"
|
||||
|
||||
[factores_riesgo.resultados.menarca_edad]
|
||||
etiqueta = "Edad a la menarca"
|
||||
tipo_valor = "numero"
|
||||
unidad = "años"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Menarca", "Menarquia", "Edad de menarca", "Edad a la menarca"]
|
||||
|
||||
[factores_riesgo.resultados.menopausia]
|
||||
etiqueta = "Estado menopáusico"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Menopausia", "Estado menopáusico", "Estado hormonal", "Climaterio"]
|
||||
valores = [
|
||||
{ valor = "PREMENOPAUSICA", etiqueta = "Premenopáusica", alias = ["Premenopausia", "Premenopáusica", "No"] },
|
||||
{ valor = "PERIMENOPAUSICA", etiqueta = "Perimenopáusica", alias = ["Perimenopausia", "Perimenopáusica", "Climaterio"] },
|
||||
{ valor = "POSTMENOPAUSICA", etiqueta = "Postmenopáusica", alias = ["Postmenopausia", "Postmenopáusica", "Posmenopausia", "Posmenopáusica", "Sí"] },
|
||||
]
|
||||
|
||||
[factores_riesgo.resultados.menopausia_edad]
|
||||
etiqueta = "Edad a la menopausia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "años"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Edad de menopausia", "Edad a la menopausia", "Menopausia a los"]
|
||||
|
||||
[factores_riesgo.resultados.gestas]
|
||||
etiqueta = "Embarazos (gestas)"
|
||||
tipo_valor = "numero"
|
||||
unidad = "embarazos"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Gestas", "Gesta", "Embarazos", "Número de embarazos"]
|
||||
|
||||
[factores_riesgo.resultados.primer_embarazo_edad]
|
||||
etiqueta = "Edad al primer embarazo a término"
|
||||
tipo_valor = "numero"
|
||||
unidad = "años"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Edad al primer embarazo", "Primer embarazo a término", "Edad al primer hijo", "Primer embarazo", "Primer parto"]
|
||||
|
||||
[factores_riesgo.resultados.familiares_primer_grado]
|
||||
etiqueta = "Familiares de primer grado con cáncer de mama"
|
||||
tipo_valor = "numero"
|
||||
unidad = "familiares"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Familiares de primer grado con cáncer de mama", "Antecedentes familiares de cáncer de mama", "AHF cáncer de mama"]
|
||||
|
||||
[factores_riesgo.resultados.biopsia_previa]
|
||||
etiqueta = "Biopsia o procedimiento mamario previo"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Biopsia previa", "Biopsias previas", "Procedimientos mamarios previos", "Cirugías mamarias previas"]
|
||||
valores = [
|
||||
{ valor = "SI", etiqueta = "Sí", alias = ["Sí", "Si", "Positiva"] },
|
||||
{ valor = "NO", etiqueta = "No", alias = ["No", "Negativa", "Negada", "Ninguna"] },
|
||||
]
|
||||
|
||||
[factores_riesgo.resultados.lesion_previa_alto_riesgo]
|
||||
etiqueta = "Lesión de alto riesgo en biopsia previa"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Resultado de biopsia previa", "Antecedente de biopsia", "Hallazgo previo"]
|
||||
valores = [
|
||||
{ valor = "HIPERPLASIA_DUCTAL_ATIPICA", etiqueta = "Hiperplasia ductal atípica", alias = ["Hiperplasia ductal atípica", "HDA"] },
|
||||
{ valor = "CARCINOMA_LOBULILLAR_IN_SITU", etiqueta = "Carcinoma lobulillar in situ", alias = ["Carcinoma lobulillar in situ", "Carcinoma lobular in situ", "CLIS"] },
|
||||
{ valor = "CICATRIZ_RADIAL", etiqueta = "Imagen radial o estrellada", alias = ["Cicatriz radial", "Imagen radial", "Imagen estrellada", "Lesión esclerosante compleja"] },
|
||||
]
|
||||
|
||||
[factores_riesgo.resultados.terapia_hormonal_anos]
|
||||
etiqueta = "Terapia hormonal en la peri o postmenopausia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "años"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Terapia hormonal de reemplazo", "Terapia de reemplazo hormonal", "TRH"]
|
||||
|
||||
[factores_riesgo.resultados.radioterapia_torax]
|
||||
etiqueta = "Radioterapia previa en tórax"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Radioterapia en tórax", "Radioterapia previa", "Radiación torácica"]
|
||||
valores = [
|
||||
{ valor = "SI", etiqueta = "Sí", alias = ["Sí", "Si", "Positiva"] },
|
||||
{ valor = "NO", etiqueta = "No", alias = ["No", "Negativa", "Negada"] },
|
||||
]
|
||||
|
||||
# What the record says about the patient that changes over time: a `parte` hanging from the document that records it
|
||||
# (the admission sheet, a note), dated by it, so it's read as of a date.
|
||||
[sociodemografico]
|
||||
etiqueta = "Datos sociodemográficos"
|
||||
|
||||
[sociodemografico.resultados.estado_civil]
|
||||
etiqueta = "Estado civil"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Estado civil", "Edo. civil", "Edo civil"]
|
||||
valores = [
|
||||
{ valor = "SOLTERA", etiqueta = "Soltera", alias = ["Soltera", "Soltero", "S"] },
|
||||
{ valor = "CASADA", etiqueta = "Casada", alias = ["Casada", "Casado", "C"] },
|
||||
{ valor = "UNION_LIBRE", etiqueta = "Unión libre", alias = ["Unión libre", "Union libre", "Concubinato", "UL"] },
|
||||
{ valor = "SEPARADA", etiqueta = "Separada", alias = ["Separada", "Separado"] },
|
||||
{ valor = "DIVORCIADA", etiqueta = "Divorciada", alias = ["Divorciada", "Divorciado", "D"] },
|
||||
{ valor = "VIUDA", etiqueta = "Viuda", alias = ["Viuda", "Viudo", "V"] },
|
||||
]
|
||||
|
||||
# The BRCA1 and BRCA2 test (7.1.1.1.7, 7.5.3): `orden`, `toma` and its `reporte`. Each gene gets the class of the
|
||||
# variant found, in the ACMG/AMP five tiers, or NEGATIVO when the report finds none.
|
||||
[prueba_genetica]
|
||||
etiqueta = "Prueba genética (BRCA1 y BRCA2)"
|
||||
|
||||
[prueba_genetica.resultados.brca1]
|
||||
etiqueta = "BRCA1"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["BRCA1"]
|
||||
valores = [
|
||||
{ valor = "PATOGENICA", etiqueta = "Variante patogénica", alias = ["Patogénica", "Mutación patogénica", "Positivo"] },
|
||||
{ valor = "PROBABLEMENTE_PATOGENICA", etiqueta = "Variante probablemente patogénica", alias = ["Probablemente patogénica"] },
|
||||
{ valor = "SIGNIFICADO_INCIERTO", etiqueta = "Variante de significado incierto", alias = ["Significado incierto", "VUS", "VSI"] },
|
||||
{ valor = "PROBABLEMENTE_BENIGNA", etiqueta = "Variante probablemente benigna", alias = ["Probablemente benigna"] },
|
||||
{ valor = "BENIGNA", etiqueta = "Variante benigna", alias = ["Benigna"] },
|
||||
{ valor = "NEGATIVO", etiqueta = "Sin variantes", alias = ["Negativo", "No se detectaron variantes", "Sin mutación"] },
|
||||
]
|
||||
|
||||
[prueba_genetica.resultados.brca2]
|
||||
etiqueta = "BRCA2"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["BRCA2"]
|
||||
valores = [
|
||||
{ valor = "PATOGENICA", etiqueta = "Variante patogénica", alias = ["Patogénica", "Mutación patogénica", "Positivo"] },
|
||||
{ valor = "PROBABLEMENTE_PATOGENICA", etiqueta = "Variante probablemente patogénica", alias = ["Probablemente patogénica"] },
|
||||
{ valor = "SIGNIFICADO_INCIERTO", etiqueta = "Variante de significado incierto", alias = ["Significado incierto", "VUS", "VSI"] },
|
||||
{ valor = "PROBABLEMENTE_BENIGNA", etiqueta = "Variante probablemente benigna", alias = ["Probablemente benigna"] },
|
||||
{ valor = "BENIGNA", etiqueta = "Variante benigna", alias = ["Benigna"] },
|
||||
{ valor = "NEGATIVO", etiqueta = "Sin variantes", alias = ["Negativo", "No se detectaron variantes", "Sin mutación"] },
|
||||
]
|
||||
|
||||
# Treatment (10.2.5): a procedure per method, an `orden` when a note indicates it and an `encuentro` when it was done;
|
||||
# one per course, surgery and radiotherapy one per breast. The procedure's date is the start.
|
||||
[cirugia]
|
||||
etiqueta = "Cirugía de mama"
|
||||
|
||||
[cirugia.resultados.lateralidad]
|
||||
etiqueta = "Mama"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Mama", "Lado", "Lateralidad"]
|
||||
valores = [
|
||||
{ valor = "DERECHA", etiqueta = "Derecha", alias = ["Mama derecha", "MD", "Der"] },
|
||||
{ valor = "IZQUIERDA", etiqueta = "Izquierda", alias = ["Mama izquierda", "MI", "Izq"] },
|
||||
]
|
||||
|
||||
[cirugia.resultados.tipo_cirugia]
|
||||
etiqueta = "Tipo de cirugía"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "ESCISIONAL", etiqueta = "Biopsia escisional o tumorectomía" },
|
||||
{ valor = "SEGMENTECTOMIA", etiqueta = "Segmentectomía o cuadrantectomía" },
|
||||
{ valor = "MASTECTOMIA_TOTAL", etiqueta = "Mastectomía total" },
|
||||
{ valor = "MASTECTOMIA_RADICAL_MODIFICADA", etiqueta = "Mastectomía radical modificada" },
|
||||
]
|
||||
|
||||
[cirugia.resultados.cirugia_axilar]
|
||||
etiqueta = "Cirugía axilar"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NINGUNA", etiqueta = "Ninguna" },
|
||||
{ valor = "GANGLIO_CENTINELA", etiqueta = "Ganglio centinela" },
|
||||
{ valor = "DISECCION_AXILAR", etiqueta = "Disección axilar" },
|
||||
]
|
||||
|
||||
[radioterapia]
|
||||
etiqueta = "Radioterapia"
|
||||
|
||||
[radioterapia.resultados.intencion]
|
||||
etiqueta = "Intención"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NEOADYUVANTE", etiqueta = "Neoadyuvante" },
|
||||
{ valor = "ADYUVANTE", etiqueta = "Adyuvante" },
|
||||
{ valor = "PALIATIVA", etiqueta = "Paliativa" },
|
||||
]
|
||||
|
||||
[radioterapia.resultados.lateralidad]
|
||||
etiqueta = "Mama"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Mama", "Lado", "Lateralidad"]
|
||||
valores = [
|
||||
{ valor = "DERECHA", etiqueta = "Derecha", alias = ["Mama derecha", "MD", "Der"] },
|
||||
{ valor = "IZQUIERDA", etiqueta = "Izquierda", alias = ["Mama izquierda", "MI", "Izq"] },
|
||||
]
|
||||
|
||||
[radioterapia.resultados.fecha_fin]
|
||||
etiqueta = "Fecha de término"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[quimioterapia]
|
||||
etiqueta = "Quimioterapia"
|
||||
|
||||
[quimioterapia.resultados.intencion]
|
||||
etiqueta = "Intención"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NEOADYUVANTE", etiqueta = "Neoadyuvante" },
|
||||
{ valor = "ADYUVANTE", etiqueta = "Adyuvante" },
|
||||
{ valor = "PALIATIVA", etiqueta = "Paliativa" },
|
||||
]
|
||||
|
||||
[quimioterapia.resultados.fecha_fin]
|
||||
etiqueta = "Fecha de término"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
|
||||
# `codigos_hospital`). ADR-MD-007.
|
||||
[orden]
|
||||
@@ -96,5 +849,18 @@ tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
|
||||
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
|
||||
{ valor = "ONCOLOGIA_MEDICA", etiqueta = "Oncología médica" },
|
||||
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
|
||||
]
|
||||
|
||||
|
||||
# Left out of the minimum, to add later (NOM-041-SSA2-2011):
|
||||
# mastografia axillary nodes (per breast), clock position (per finding)
|
||||
# biopsia date taken (8.3.5 b); nuclear grade, mitotic index and tubule formation (8.3.5.5; the Nottingham
|
||||
# total suffices); architectural pattern, necrosis, microcalcifications, specimen size, closest
|
||||
# margin, coexisting intraductal carcinoma and its extent (Apéndice Informativo B); extracapsular
|
||||
# invasion, size and site of the metastasis (8.3.5.8.5, 8.3.5.8.6); receptors' H-score
|
||||
# nota_medica the St. Gallen category as the note writes it (10.3.3; dbt derives it from the report)
|
||||
# factores_riesgo breastfeeding (7.1.1.6), implants (Apéndice Informativo D)
|
||||
# treatment reconstruction (10.2.3); radiotherapy's dose, fractions and site; chemotherapy's cycles and
|
||||
# regimen; hormone and biological therapy (10.2.5.4, 10.2.5.5)
|
||||
|
||||
+330
-25
@@ -196,13 +196,40 @@ etiqueta = "Diagnóstico"
|
||||
tipo_valor = "externo"
|
||||
sistema = "CIE-10"
|
||||
|
||||
# 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.
|
||||
# The EEG: what its analysis (the `tea` library) writes. On the recording (`toma`): the verdict, triage level, clean
|
||||
# fraction, sleep, channels, duration and line noise; each study-wide quality check (`calidad_<check>`, with
|
||||
# `_anormal`, `_decisivo` and its limit, `_bajo` or `_alto`); and each metric's value with, against its age baseline, its z
|
||||
# (`_z`), -1/0/+1 (`_fuera`), the curve's p5, median and p95 there and the registered label of the baseline that curve
|
||||
# belongs to (`_modelo`). On each bad channel (`parte`, `codigo_fuente` the electrode): the check that flagged it, with
|
||||
# the library's reason. On each electrode of a metric (`parte`, `codigo_fuente` the electrode): the metric's value and z
|
||||
# there, under the same results.
|
||||
[eeg]
|
||||
etiqueta = "Electroencefalograma"
|
||||
codigos_hospital = ["EEG"]
|
||||
|
||||
[eeg.resultados.valido]
|
||||
etiqueta = "EEG válido para el estudio"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.nivel]
|
||||
etiqueta = "Nivel de triaje"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.fraccion_limpia]
|
||||
etiqueta = "Fracción del registro limpia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "fracción"
|
||||
|
||||
[eeg.resultados.canales_malos]
|
||||
etiqueta = "Canales malos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.edad_meses]
|
||||
etiqueta = "Edad al estudio"
|
||||
tipo_valor = "numero"
|
||||
unidad = "meses"
|
||||
|
||||
[eeg.resultados.con_sueno]
|
||||
etiqueta = "Registro con sueño"
|
||||
tipo_valor = "booleano"
|
||||
@@ -217,55 +244,333 @@ 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]
|
||||
[eeg.resultados.ruido_linea]
|
||||
etiqueta = "Ruido de la línea eléctrica"
|
||||
tipo_valor = "numero"
|
||||
unidad = "dB"
|
||||
|
||||
[eeg.resultados.calidad_clean_windows]
|
||||
etiqueta = "Ventanas limpias"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
|
||||
[eeg.resultados.calidad_clean_windows_anormal]
|
||||
etiqueta = "Ventanas limpias: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_clean_windows_decisivo]
|
||||
etiqueta = "Ventanas limpias: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_clean_windows_bajo]
|
||||
etiqueta = "Ventanas limpias: límite inferior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
|
||||
[eeg.resultados.calidad_internal_coverage]
|
||||
etiqueta = "Cobertura interna"
|
||||
tipo_valor = "numero"
|
||||
unidad = "fracción"
|
||||
|
||||
[eeg.resultados.calidad_internal_coverage_anormal]
|
||||
etiqueta = "Cobertura interna: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_internal_coverage_decisivo]
|
||||
etiqueta = "Cobertura interna: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_internal_coverage_bajo]
|
||||
etiqueta = "Cobertura interna: límite inferior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "fracción"
|
||||
|
||||
[eeg.resultados.calidad_bad_scalp_triage]
|
||||
etiqueta = "Electrodos del cuero cabelludo inservibles"
|
||||
tipo_valor = "numero"
|
||||
unidad = "electrodos"
|
||||
|
||||
[eeg.resultados.calidad_bad_scalp_triage_anormal]
|
||||
etiqueta = "Electrodos del cuero cabelludo inservibles: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_bad_scalp_triage_decisivo]
|
||||
etiqueta = "Electrodos del cuero cabelludo inservibles: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_bad_scalp_triage_alto]
|
||||
etiqueta = "Electrodos del cuero cabelludo inservibles: límite superior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "electrodos"
|
||||
|
||||
[eeg.resultados.calidad_usable_scalp]
|
||||
etiqueta = "Electrodos del cuero cabelludo útiles"
|
||||
tipo_valor = "numero"
|
||||
unidad = "electrodos"
|
||||
|
||||
[eeg.resultados.calidad_usable_scalp_anormal]
|
||||
etiqueta = "Electrodos del cuero cabelludo útiles: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_usable_scalp_decisivo]
|
||||
etiqueta = "Electrodos del cuero cabelludo útiles: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_usable_scalp_bajo]
|
||||
etiqueta = "Electrodos del cuero cabelludo útiles: límite inferior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "electrodos"
|
||||
|
||||
[eeg.resultados.calidad_triage_level]
|
||||
etiqueta = "Nivel de triaje"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_triage_level_anormal]
|
||||
etiqueta = "Nivel de triaje: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_triage_level_decisivo]
|
||||
etiqueta = "Nivel de triaje: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_line_noise]
|
||||
etiqueta = "Ruido de la línea eléctrica"
|
||||
tipo_valor = "numero"
|
||||
unidad = "dB"
|
||||
|
||||
[eeg.resultados.calidad_line_noise_anormal]
|
||||
etiqueta = "Ruido de la línea eléctrica: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_line_noise_decisivo]
|
||||
etiqueta = "Ruido de la línea eléctrica: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_line_noise_alto]
|
||||
etiqueta = "Ruido de la línea eléctrica: límite superior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "dB"
|
||||
|
||||
[eeg.resultados.calidad_file]
|
||||
etiqueta = "Archivo EDF"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_file_anormal]
|
||||
etiqueta = "Archivo EDF: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_file_decisivo]
|
||||
etiqueta = "Archivo EDF: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_dead_channel]
|
||||
etiqueta = "Canal muerto"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_frozen]
|
||||
etiqueta = "Señal congelada"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_saturated]
|
||||
etiqueta = "Señal saturada"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_inf_values]
|
||||
etiqueta = "Valores infinitos"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_own_gaps]
|
||||
etiqueta = "Huecos propios"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_bridge]
|
||||
etiqueta = "Puente con otro electrodo"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_amplitude]
|
||||
etiqueta = "Amplitud anómala frente al cuero cabelludo"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_aux_amplitude]
|
||||
etiqueta = "Amplitud fuera de rango (canal auxiliar)"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_does_not_correlate]
|
||||
etiqueta = "Sin correlación con sus vecinos"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_intermittent_contact]
|
||||
etiqueta = "Contacto intermitente"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_intermittent_bursts]
|
||||
etiqueta = "Contacto intermitente por ráfagas"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.ritmo_posterior]
|
||||
etiqueta = "Ritmo posterior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_z]
|
||||
etiqueta = "Ritmo posterior: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_fuera]
|
||||
etiqueta = "Ritmo posterior: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_p5]
|
||||
etiqueta = "Ritmo posterior: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_mediana]
|
||||
etiqueta = "Ritmo posterior: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_p95]
|
||||
etiqueta = "Ritmo posterior: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_modelo]
|
||||
etiqueta = "Ritmo posterior: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2]
|
||||
etiqueta = "Husos de sueño N2"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_z]
|
||||
etiqueta = "Husos de sueño N2: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_fuera]
|
||||
etiqueta = "Husos de sueño N2: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_p5]
|
||||
etiqueta = "Husos de sueño N2: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_mediana]
|
||||
etiqueta = "Husos de sueño N2: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_p95]
|
||||
etiqueta = "Husos de sueño N2: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_modelo]
|
||||
etiqueta = "Husos de sueño N2: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3]
|
||||
etiqueta = "Husos de sueño N3"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_z]
|
||||
etiqueta = "Husos de sueño N3: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_fuera]
|
||||
etiqueta = "Husos de sueño N3: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_p5]
|
||||
etiqueta = "Husos de sueño N3: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_mediana]
|
||||
etiqueta = "Husos de sueño N3: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_p95]
|
||||
etiqueta = "Husos de sueño N3: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_modelo]
|
||||
etiqueta = "Husos de sueño N3: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos]
|
||||
etiqueta = "Picos paroxísticos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_z]
|
||||
etiqueta = "Picos paroxísticos: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_fuera]
|
||||
etiqueta = "Picos paroxísticos: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_p5]
|
||||
etiqueta = "Picos paroxísticos: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_mediana]
|
||||
etiqueta = "Picos paroxísticos: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_p95]
|
||||
etiqueta = "Picos paroxísticos: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_modelo]
|
||||
etiqueta = "Picos paroxísticos: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior]
|
||||
etiqueta = "Gradiente anteroposterior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "razón posterior/anterior"
|
||||
unidad = "pendiente"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_z]
|
||||
etiqueta = "Gradiente anteroposterior: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_fuera]
|
||||
etiqueta = "Gradiente anteroposterior: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_p5]
|
||||
etiqueta = "Gradiente anteroposterior: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "pendiente"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_mediana]
|
||||
etiqueta = "Gradiente anteroposterior: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "pendiente"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_p95]
|
||||
etiqueta = "Gradiente anteroposterior: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "pendiente"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_modelo]
|
||||
etiqueta = "Gradiente anteroposterior: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
|
||||
[orden]
|
||||
|
||||
@@ -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"),
|
||||
)
|
||||
|
||||
@@ -99,7 +99,9 @@ class EvaluacionRiesgoBase(SQLModel):
|
||||
evaluacion_id: int | None = Field(default=None, primary_key=True)
|
||||
lote_id: int = Field(foreign_key="evaluacion_riesgo_lote.lote_id", index=True)
|
||||
pac_id: int = Field(foreign_key="persona.pac_id") # subject
|
||||
horizonte_anios: float # prediction.when: años desde la fecha índice; 0 = prevalente
|
||||
# El punto de decisión desde el que el modelo predice para esta paciente (lo define el modelo, no la cohorte).
|
||||
fecha_indice: date
|
||||
horizonte_anios: float # prediction.when: años desde `fecha_indice`; 0 = prevalente
|
||||
probabilidad: float # prediction.probabilityDecimal, de 0 a 1
|
||||
# Incertidumbre, si el modelo la da (solo con un Hessiano definido positivo). Nula si no.
|
||||
ic_bajo: float | None = None
|
||||
|
||||
@@ -54,6 +54,34 @@ class MetricaEeg(str, Enum):
|
||||
GRADIENTE_ANTEROPOSTERIOR = "GRADIENTE_ANTEROPOSTERIOR"
|
||||
|
||||
|
||||
class NivelRelacionAdos2(str, Enum):
|
||||
"""rel_nivel and rel_tipo in table relacion_ados2: what the model relates, an ADOS-2 item or a domain."""
|
||||
ITEM = "item"
|
||||
DOMINIO = "dominio"
|
||||
|
||||
|
||||
class CriterioEeg(str, Enum):
|
||||
"""cri_codigo in table eeg_criterio: the EEG analysis's check codes, channel reasons without their numbers."""
|
||||
ARCHIVO = "file"
|
||||
VENTANAS_LIMPIAS = "clean-windows"
|
||||
COBERTURA_INTERNA = "internal-coverage"
|
||||
CUERO_CABELLUDO_MALO = "bad-scalp-triage"
|
||||
CUERO_CABELLUDO_UTIL = "usable-scalp"
|
||||
NIVEL_TRIAJE = "triage-level"
|
||||
RUIDO_LINEA = "line-noise"
|
||||
CANAL_MUERTO = "dead-channel"
|
||||
CONGELADO = "frozen"
|
||||
SATURADO = "saturated"
|
||||
VALORES_INF = "inf-values"
|
||||
HUECOS_PROPIOS = "own-gaps"
|
||||
PUENTE = "bridge"
|
||||
AMPLITUD = "amplitude"
|
||||
AMPLITUD_AUXILIAR = "aux-amplitude"
|
||||
SIN_CORRELACION = "does-not-correlate"
|
||||
CONTACTO_INTERMITENTE = "intermittent-contact"
|
||||
CONTACTO_POR_RAFAGAS = "intermittent-bursts"
|
||||
|
||||
|
||||
# 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",
|
||||
|
||||
@@ -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) ---
|
||||
|
||||
|
||||
|
||||
+86
-8
@@ -1,14 +1,15 @@
|
||||
"""TEA staging tables (data dictionary: spec/tablas_TEA.md).
|
||||
|
||||
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.
|
||||
the orders. The EEG's verdict, quality checks, channels, duration, sleep, metrics and electrode values are written
|
||||
by the EEG analysis (the `tea` library) from the stored EDF. The ADOS-2 association model's cohort odds ratios and
|
||||
per-patient z and probability land in relacion_ados2 and relacion_ados2_paciente.
|
||||
|
||||
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
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
@@ -49,6 +50,10 @@ def _date() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
|
||||
|
||||
def _datetime() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
|
||||
|
||||
class Pacientes(TeaModel, table=True):
|
||||
__tablename__ = "pacientes"
|
||||
|
||||
@@ -152,13 +157,37 @@ class Eeg(TeaModel, table=True):
|
||||
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
|
||||
# The analysis's verdict: 1 valid, 0 not valid, null not analysed yet. Its checks are rows of eeg_criterio.
|
||||
eeg_valido: Optional[int] = _int()
|
||||
eeg_nivel: Optional[str] = _text() # triage level: completo, sin_referencia_auricular, parcial, no_analizable
|
||||
eeg_fraccion_limpia: Optional[float] = _float()
|
||||
eeg_canales_malos: Optional[int] = _int()
|
||||
eeg_edad_meses: Optional[float] = _float() # the age the analysis compared the metrics at
|
||||
# What produced the analysis, so a new plan or module version analyses the EEG again.
|
||||
eeg_plan_hash: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(16)))
|
||||
eeg_versiones: Optional[str] = _text()
|
||||
eeg_analizado_en: Optional[datetime] = _datetime()
|
||||
eeg_error: Optional[str] = _text()
|
||||
|
||||
|
||||
class EegCriterio(TeaModel, table=True):
|
||||
"""One quality check the EEG analysis evaluated on an EEG: a study rule, or a bad channel with its electrode."""
|
||||
|
||||
__tablename__ = "eeg_criterio"
|
||||
|
||||
cri_id: Optional[str] = _id()
|
||||
cri_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
|
||||
cri_codigo: Optional[str] = _text() # CriterioEeg
|
||||
cri_electrodo: Optional[str] = _text()
|
||||
cri_valor: Optional[float] = _float()
|
||||
cri_valor_texto: Optional[str] = _text()
|
||||
cri_unidad: Optional[str] = _text()
|
||||
cri_bajo: Optional[float] = _float() # out of range below this
|
||||
cri_alto: Optional[float] = _float() # out of range above this
|
||||
cri_decisivo: Optional[int] = _int() # this check alone can make the EEG not valid
|
||||
cri_anormal: Optional[int] = _int()
|
||||
|
||||
|
||||
class EegMetrica(TeaModel, table=True):
|
||||
@@ -170,6 +199,13 @@ class EegMetrica(TeaModel, table=True):
|
||||
met_eeg_id: Optional[str] = _text()
|
||||
met_codigo: Optional[str] = _text() # MetricaEeg
|
||||
met_valor: Optional[float] = _float()
|
||||
# Against the age baseline at eeg_edad_meses: z, -1/0/+1 below p5 / within / above p95, and the curve there.
|
||||
met_z: Optional[float] = _float()
|
||||
met_fuera: Optional[int] = _int()
|
||||
met_p5: Optional[float] = _float()
|
||||
met_mediana: Optional[float] = _float()
|
||||
met_p95: Optional[float] = _float()
|
||||
met_modelo: Optional[str] = _text() # the baseline's registered model version
|
||||
|
||||
|
||||
class EegMetricaElectrodo(TeaModel, table=True):
|
||||
@@ -181,3 +217,45 @@ class EegMetricaElectrodo(TeaModel, table=True):
|
||||
mel_met_id: Optional[str] = _text()
|
||||
mel_electrodo: Optional[str] = _text()
|
||||
mel_valor: Optional[float] = _float()
|
||||
mel_z: Optional[float] = _float()
|
||||
|
||||
|
||||
class RelacionAdos2(TeaModel, table=True):
|
||||
"""One association of an EEG alteration in a scalp zone with an ADOS-2 outcome, per fitted model version."""
|
||||
|
||||
__tablename__ = "relacion_ados2"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado", name="uq_relacion_ados2"),
|
||||
)
|
||||
|
||||
rel_id: Optional[str] = _id()
|
||||
# Bounded: the natural key the import layer and the tea library merge model rows on is a unique index.
|
||||
rel_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32), index=True))
|
||||
rel_nivel: Optional[str] = _text() # NivelRelacionAdos2: the model's level
|
||||
rel_validado: Optional[int] = _int() # 1 validated by the domain expert, 0 pending
|
||||
rel_n_cohorte: Optional[int] = _int()
|
||||
rel_biomarcador: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # MetricaEeg
|
||||
rel_zona: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # scalp zone code from the tea library
|
||||
rel_tipo: Optional[str] = _text() # NivelRelacionAdos2: the level this association relates
|
||||
rel_resultado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # ADOS-2 item or domain code
|
||||
rel_evento: Optional[str] = _text() # the outcome event, e.g. "score >= 2"
|
||||
rel_or: Optional[float] = _float()
|
||||
rel_ic_inf: Optional[float] = _float()
|
||||
rel_ic_sup: Optional[float] = _float()
|
||||
rel_q: Optional[float] = _float()
|
||||
|
||||
|
||||
class RelacionAdos2Paciente(TeaModel, table=True):
|
||||
"""One patient's z and model probability for an association row: the EEG's metric z mapped through relacion_ados2."""
|
||||
|
||||
__tablename__ = "relacion_ados2_paciente"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint("rap_rel_id", "rap_eeg_id", name="uq_relacion_ados2_paciente"),
|
||||
)
|
||||
|
||||
rap_id: Optional[str] = _id()
|
||||
rap_rel_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
|
||||
rap_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
|
||||
rap_valor_z: Optional[float] = _float()
|
||||
rap_probabilidad: Optional[float] = _float()
|
||||
rap_probabilidad_referencia: Optional[float] = _float()
|
||||
|
||||
+93
-15
@@ -1,12 +1,15 @@
|
||||
# Diccionario de datos y reglas de validación — Proyecto TEA
|
||||
|
||||
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,
|
||||
neuropediatría y EEG), más los pacientes y las órdenes, y las dos del modelo de asociación con el ADOS-2
|
||||
(`relacion_ados2` y `relacion_ados2_paciente`). 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.
|
||||
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG (la biblioteca `tea`) a partir del EDF
|
||||
guardado: veredicto, criterios de calidad, canales, duración, sueño, métricas y valores por electrodo. Las dos
|
||||
tablas de asociación con el ADOS-2 las escribe el modelo de asociación (también la biblioteca `tea`), y mientras
|
||||
este llega la API de importación carga renglones de desarrollo igual que el resto del staging.
|
||||
|
||||
---
|
||||
|
||||
@@ -88,19 +91,46 @@ Los subtotales por dominio y el total no se guardan: son sumas de los puntajes d
|
||||
| `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_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0: la mediana del ruido de la línea eléctrica en el cuero cabelludo. **(análisis del EEG)** | — |
|
||||
| `eeg_estudio` | BLOB (LONGBLOB en MySQL) | — | El archivo EDF. | — |
|
||||
| `eeg_valido` | INTEGER | — | 1 válido, 0 no válido; nulo: sin analizar. **(análisis del EEG)** | — |
|
||||
| `eeg_nivel` | TEXT | — | Nivel de triaje: `completo`, `sin_referencia_auricular`, `parcial` o `no_analizable`. **(análisis del EEG)** | — |
|
||||
| `eeg_fraccion_limpia` | FLOAT | fracción | Entre 0 y 1: la parte del registro en ventanas limpias. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_malos` | INTEGER | canales | Mayor o igual que 0. **(análisis del EEG)** | — |
|
||||
| `eeg_edad_meses` | FLOAT | meses | La edad a la fecha del estudio con que se compararon las métricas; nula sin fecha de nacimiento. **(análisis del EEG)** | — |
|
||||
| `eeg_plan_hash` | VARCHAR(16) | — | El plan de preprocesamiento con que se analizó. **(análisis del EEG)** | — |
|
||||
| `eeg_versiones` | TEXT | — | Las versiones de los módulos del análisis (`nombre=versión;…`). **(análisis del EEG)** | — |
|
||||
| `eeg_analizado_en` | DATETIME | — | Cuándo se analizó. **(análisis del EEG)** | — |
|
||||
| `eeg_error` | TEXT | — | Por qué el análisis no terminó; nulo si terminó. **(análisis del EEG)** | — |
|
||||
|
||||
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.
|
||||
Un EEG es válido cuando el análisis lo dice (`eeg_valido` = 1): ninguna regla decisiva de `eeg_criterio` fuera de su
|
||||
umbral y el registro dentro de las condiciones del plan de preprocesamiento. Uno no válido no tiene resultado y sus
|
||||
alteraciones no cuentan.
|
||||
|
||||
---
|
||||
|
||||
## 7. Tabla `eeg_metrica` **(análisis del EEG)**
|
||||
## 7. Tabla `eeg_criterio` **(análisis del EEG)**
|
||||
|
||||
Un renglón por cada regla de calidad que el análisis evaluó sobre un EEG: las del estudio completo y, para cada canal
|
||||
malo, el motivo con su electrodo.
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `cri_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `cri_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
|
||||
| `cri_codigo` | TEXT | — | Catálogo `CriterioEeg`: del estudio `file, clean-windows, internal-coverage, bad-scalp-triage, usable-scalp, triage-level, line-noise`; de un canal `dead-channel, frozen, saturated, inf-values, own-gaps, bridge, amplitude, aux-amplitude, does-not-correlate, intermittent-contact, intermittent-bursts`. | — |
|
||||
| `cri_electrodo` | TEXT | — | El canal del motivo; nulo en las reglas del estudio. | — |
|
||||
| `cri_valor` | FLOAT | `cri_unidad` | El valor medido, si es un número. | — |
|
||||
| `cri_valor_texto` | TEXT | — | El valor o el motivo, si es un texto (por ejemplo, el nivel de triaje). | — |
|
||||
| `cri_unidad` | TEXT | — | `%`, `fraction`, `electrodes` o `dB`. | — |
|
||||
| `cri_bajo` | FLOAT | `cri_unidad` | Fuera de rango por debajo de este valor. | — |
|
||||
| `cri_alto` | FLOAT | `cri_unidad` | Fuera de rango por encima de este valor. | — |
|
||||
| `cri_decisivo` | INTEGER | — | 0 o 1: la regla basta, por sí sola, para que el EEG no sea válido. | — |
|
||||
| `cri_anormal` | INTEGER | — | 0 o 1. | — |
|
||||
|
||||
---
|
||||
|
||||
## 8. Tabla `eeg_metrica` **(análisis del EEG)**
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
@@ -108,16 +138,64 @@ sus alteraciones no cuentan.
|
||||
| `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). | — |
|
||||
|
||||
Solo se guarda el valor medido: el puntaje z y el estado salen de los rangos de referencia por grupo de edad.
|
||||
| `met_z` | FLOAT | puntaje z | Contra la curva de referencia de la métrica a `eeg_edad_meses`; nulo si la edad no está cubierta. | — |
|
||||
| `met_fuera` | INTEGER | — | -1 debajo del percentil 5, 0 dentro, +1 arriba del percentil 95. | — |
|
||||
| `met_p5` | FLOAT | la de la métrica | El percentil 5 de la curva a esa edad. | — |
|
||||
| `met_mediana` | FLOAT | la de la métrica | La mediana de la curva a esa edad. | — |
|
||||
| `met_p95` | FLOAT | la de la métrica | El percentil 95 de la curva a esa edad. | — |
|
||||
| `met_modelo` | TEXT | — | La versión registrada de la curva de referencia. | — |
|
||||
|
||||
---
|
||||
|
||||
## 8. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
|
||||
## 9. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `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 | — | — |
|
||||
| `mel_valor` | FLOAT | la de la métrica | — | — |
|
||||
| `mel_z` | FLOAT | puntaje z | Contra la curva de referencia del electrodo a `eeg_edad_meses`. | — |
|
||||
|
||||
---
|
||||
|
||||
## 10. Tabla `relacion_ados2`
|
||||
|
||||
Un renglón por versión del modelo y asociación: la razón de momios, en la cohorte, de una alteración del EEG en una
|
||||
zona del cuero cabelludo contra el desenlace de un reactivo o dominio del ADOS-2. La llave natural
|
||||
(`rel_version`, `rel_biomarcador`, `rel_zona`, `rel_resultado`) es única: es con la que la API de importación y la
|
||||
biblioteca `tea` unen renglones al cargar una versión del modelo.
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `rel_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `rel_version` | VARCHAR(32), indexado | — | La versión del modelo ajustado. | — |
|
||||
| `rel_nivel` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel del modelo. | — |
|
||||
| `rel_validado` | INTEGER | — | 0 o 1: validado por el experto de dominio. | — |
|
||||
| `rel_n_cohorte` | INTEGER | pacientes | Mayor que 0: el tamaño de la cohorte con que se ajustó el modelo. | — |
|
||||
| `rel_biomarcador` | VARCHAR(32) | — | Catálogo `MetricaEeg`: la métrica del EEG asociada. | — |
|
||||
| `rel_zona` | VARCHAR(32) | — | El código de la zona del cuero cabelludo, el de la biblioteca `tea`. | — |
|
||||
| `rel_tipo` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel que relaciona esta asociación. | — |
|
||||
| `rel_resultado` | VARCHAR(32) | — | El código del reactivo del ADOS-2 (los de `ADOS2_ITEMS`) o del dominio. | — |
|
||||
| `rel_evento` | TEXT | — | El evento de desenlace como umbral legible por máquina sobre el puntaje del desenlace: `>=2` (el puntaje del reactivo, o el total del algoritmo del dominio). | — |
|
||||
| `rel_or` | FLOAT | razón de momios | Mayor que 0. | — |
|
||||
| `rel_ic_inf` | FLOAT | razón de momios | El límite inferior del intervalo de confianza; menor o igual que `rel_ic_sup`. | — |
|
||||
| `rel_ic_sup` | FLOAT | razón de momios | El límite superior del intervalo de confianza. | — |
|
||||
| `rel_q` | FLOAT | — | Entre 0 y 1: el valor q del ajuste por comparaciones múltiples. | — |
|
||||
|
||||
---
|
||||
|
||||
## 11. Tabla `relacion_ados2_paciente`
|
||||
|
||||
Un renglón por EEG y renglón del modelo: el z del paciente para la asociación y la probabilidad que el modelo le
|
||||
asigna. La pareja (`rap_rel_id`, `rap_eeg_id`) es única. El desenlace observado no se guarda: se lee del ADOS-2 del
|
||||
paciente (`ados2`).
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `rap_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `rap_rel_id` | VARCHAR(36), indexado | — | — | → `relacion_ados2.rel_id` |
|
||||
| `rap_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
|
||||
| `rap_valor_z` | FLOAT | puntaje z | El z del paciente en la asociación. | — |
|
||||
| `rap_probabilidad` | FLOAT | probabilidad | Entre 0 y 1: la probabilidad que da el modelo. | — |
|
||||
| `rap_probabilidad_referencia` | FLOAT | probabilidad | Entre 0 y 1: la probabilidad de referencia. | — |
|
||||
|
||||
@@ -23,6 +23,8 @@ INDICADORES_KIT_CDM = {
|
||||
"cat_estudio",
|
||||
"cat_resultado",
|
||||
"cat_valor",
|
||||
"cat_sistema_fuente",
|
||||
"cat_mapeo",
|
||||
"procedimiento",
|
||||
"observacion_clinica",
|
||||
"cat_measure",
|
||||
@@ -81,6 +83,9 @@ def test_tea_tables_registered():
|
||||
"eeg",
|
||||
"eeg_metrica",
|
||||
"eeg_metrica_electrodo",
|
||||
"eeg_criterio",
|
||||
"relacion_ados2",
|
||||
"relacion_ados2_paciente",
|
||||
# indicadores_kit CDM, built from staging by the webapi.orquestacion graph.
|
||||
*INDICADORES_KIT_CDM,
|
||||
}
|
||||
@@ -101,3 +106,26 @@ 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}
|
||||
|
||||
|
||||
def test_relacion_ados2_keeps_its_natural_keys_in_the_schema():
|
||||
"""Pins down: the import merge and the `tea` library upsert one `relacion_ados2` row per
|
||||
(rel_version, rel_biomarcador, rel_zona, rel_resultado), and one `relacion_ados2_paciente` row per
|
||||
(rap_rel_id, rap_eeg_id). Fails if either unique constraint is dropped, which would let two imports of
|
||||
the same model row or two probabilities for the same EEG and association both land."""
|
||||
from core.tea.models import RelacionAdos2, RelacionAdos2Paciente
|
||||
|
||||
assert "uq_relacion_ados2" in {c.name for c in RelacionAdos2.__table__.constraints}
|
||||
assert "uq_relacion_ados2_paciente" in {c.name for c in RelacionAdos2Paciente.__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"),
|
||||
@@ -135,7 +135,7 @@ CLINICAL_TERMS: dict[str, dict[str, object]] = {
|
||||
|
||||
# Columns worth looking for anywhere in the narrative, not only after a caption.
|
||||
FREE_TEXT_FIELDS = frozenset(
|
||||
{"cit_vph_resultado", "cit_celulas_escamosas", "bx_cin_grado", "bx_grado_histologico", "mast_birads", "nm_cie_codigo"}
|
||||
{"cit_vph_resultado", "cit_celulas_escamosas", "cit_celulas_glandulares", "bx_cin_grado", "bx_grado_histologico", "mast_birads", "nm_cie_codigo"}
|
||||
)
|
||||
|
||||
# Shape of a valid value.
|
||||
@@ -156,7 +156,251 @@ 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", "no especial")
|
||||
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",
|
||||
})
|
||||
# Glandular cells in cytology: atypical glandular cells (AGC) and adenocarcinoma.
|
||||
# Adenocarcinoma in situ has no catalog value and is deliberately not listed.
|
||||
CLINICAL_TERMS["cit_celulas_glandulares"] = {
|
||||
"CELULAS GLANDULARES ATIPICAS": "AGC", "ATIPIA DE CELULAS GLANDULARES": "AGC",
|
||||
"ATIPIA EN CELULAS GLANDULARES": "AGC", "AGC": "AGC", "ACG": "AGC",
|
||||
"ADENOCARCINOMA": "ADENOCARCINOMA", "ADENOCARCINOMA ENDOCERVICAL": "ADENOCARCINOMA",
|
||||
"ADENOCARCINOMA ENDOMETRIAL": "ADENOCARCINOMA",
|
||||
}
|
||||
SEVERITY["cit_celulas_glandulares"] = ("AGC", "ADENOCARCINOMA")
|
||||
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)
|
||||
@@ -3,6 +3,7 @@ from datetime import date
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.nlp import FieldKind, FieldSpec, RecordExtractor, SegmentLine
|
||||
from extraction.nlp.text import find_date, find_decimal, find_integer, fold
|
||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, SEVERITY, labels_for
|
||||
|
||||
SEXO = FieldSpec("pac_sexo", FieldKind.CHOICE, labels=("sexo",), choices={"F": "Femenino", "FEMENINO": "Femenino", "M": "Masculino"})
|
||||
NACIMIENTO = FieldSpec("pac_fecha_nacimiento", FieldKind.DATE, labels=("fecha de nacimiento", "f. nac"))
|
||||
@@ -23,6 +24,14 @@ CIN = FieldSpec(
|
||||
scan_free_text=True,
|
||||
)
|
||||
OBSERVACIONES = FieldSpec("cit_observaciones", FieldKind.TEXT, labels=("observaciones",), multiline=True)
|
||||
GLANDULARES = FieldSpec(
|
||||
"cit_celulas_glandulares",
|
||||
FieldKind.CHOICE,
|
||||
labels=labels_for("cit_celulas_glandulares"),
|
||||
choices=CLINICAL_TERMS["cit_celulas_glandulares"],
|
||||
scan_free_text=True,
|
||||
severity=SEVERITY["cit_celulas_glandulares"],
|
||||
)
|
||||
|
||||
|
||||
def lines(*texts: str, confidence: float = 1.0) -> list[SegmentLine]:
|
||||
@@ -103,3 +112,15 @@ def test_low_ocr_confidence_lowers_value_confidence():
|
||||
clean = RecordExtractor([SEXO]).extract(lines("Sexo: F"))["pac_sexo"].confidence
|
||||
noisy = RecordExtractor([SEXO]).extract(lines("Sexo: F", confidence=0.6))["pac_sexo"].confidence
|
||||
assert noisy < clean
|
||||
|
||||
|
||||
def test_glandular_atypical_cells_wording_maps_to_agc():
|
||||
"""Pins down that a cytology line naming atypical glandular cells maps to the catalog value AGC, using the vocabulary's glandular CLINICAL_TERMS as the field's choices. Fails if those terms are missing from the vocabulary, not built into the field, or mapped to another value."""
|
||||
found = RecordExtractor([GLANDULARES]).extract(lines("Células glandulares: células glandulares atípicas"))
|
||||
assert found["cit_celulas_glandulares"].value == "AGC"
|
||||
|
||||
|
||||
def test_adenocarcinoma_endocervical_wording_maps_to_adenocarcinoma():
|
||||
"""Pins down that a cytology line naming endocervical adenocarcinoma maps to the catalog value ADENOCARCINOMA through the vocabulary's glandular CLINICAL_TERMS. Fails if the term is missing from the vocabulary or mapped to AGC or to nothing."""
|
||||
found = RecordExtractor([GLANDULARES]).extract(lines("Células glandulares: adenocarcinoma endocervical"))
|
||||
assert found["cit_celulas_glandulares"].value == "ADENOCARCINOMA"
|
||||
|
||||
@@ -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"}]
|
||||
@@ -2,7 +2,9 @@ from core.cacu.indicadores.models import (
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CatEstudio,
|
||||
CatMapeo,
|
||||
CatResultado,
|
||||
CatSistemaFuente,
|
||||
CatValor,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
@@ -55,6 +57,7 @@ from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
SourceMappingRepository,
|
||||
TimelineRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
@@ -102,6 +105,7 @@ observacion_repository = Repository(get_cacu_session, Observacion)
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(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,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""risk index date
|
||||
|
||||
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
|
||||
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
|
||||
the batch's build, the one their horizons were counted from; then the column is required.
|
||||
|
||||
Revision ID: a1d4e7c20b31
|
||||
Revises: c3d8f5a20b47
|
||||
Create Date: 2026-11-20 21:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'a1d4e7c20b31'
|
||||
down_revision = 'c3d8f5a20b47'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
|
||||
op.execute(
|
||||
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
|
||||
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
|
||||
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
|
||||
)
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.drop_column('fecha_indice')
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""date of death
|
||||
|
||||
The patient's date of death, survival's outcome and a competing risk: `paciente.pac_fecha_defuncion`
|
||||
as it arrives and `persona.fecha_defuncion` in silver. Both nullable: null while she is alive or the
|
||||
date is unknown.
|
||||
|
||||
Revision ID: c3d8f5a20b47
|
||||
Revises: f89e1f081998
|
||||
Create Date: 2026-11-20 10:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c3d8f5a20b47'
|
||||
down_revision = 'f89e1f081998'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column('paciente', sa.Column('pac_fecha_defuncion', sa.Date(), nullable=True))
|
||||
op.add_column('persona', sa.Column('fecha_defuncion', sa.Date(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Batch mode: SQLite drops a column by rebuilding its table.
|
||||
with op.batch_alter_table('persona') as batch:
|
||||
batch.drop_column('fecha_defuncion')
|
||||
with op.batch_alter_table('paciente') as batch:
|
||||
batch.drop_column('pac_fecha_defuncion')
|
||||
@@ -0,0 +1,25 @@
|
||||
"""cacu heads joined
|
||||
|
||||
The date of death (`pac_fecha_defuncion`, `fecha_defuncion`) and the index date of each risk
|
||||
(`evaluacion_riesgo.fecha_indice`) 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: e5b8d2a47c19
|
||||
Revises: c3d8f5a20b47, a1d4e7c20b31
|
||||
Create Date: 2026-11-21 02:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'e5b8d2a47c19'
|
||||
down_revision = ('c3d8f5a20b47', 'a1d4e7c20b31')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -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,
|
||||
@@ -55,6 +57,7 @@ from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
SourceMappingRepository,
|
||||
TimelineRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
@@ -102,6 +105,7 @@ observacion_repository = Repository(get_cama_session, Observacion)
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(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,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""date of death
|
||||
|
||||
The patient's date of death, survival's outcome: `paciente.pac_fecha_defuncion` as it arrives and
|
||||
`persona.fecha_defuncion` in silver. Both nullable: null while she is alive or the date is unknown.
|
||||
|
||||
Revision ID: a9c4e2f17d38
|
||||
Revises: f82b64f43abd
|
||||
Create Date: 2026-11-18 19:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'a9c4e2f17d38'
|
||||
down_revision = 'f82b64f43abd'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column('paciente', sa.Column('pac_fecha_defuncion', sa.Date(), nullable=True))
|
||||
op.add_column('persona', sa.Column('fecha_defuncion', sa.Date(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Batch mode: SQLite drops a column by rebuilding its table.
|
||||
with op.batch_alter_table('persona') as batch:
|
||||
batch.drop_column('fecha_defuncion')
|
||||
with op.batch_alter_table('paciente') as batch:
|
||||
batch.drop_column('pac_fecha_defuncion')
|
||||
@@ -0,0 +1,37 @@
|
||||
"""risk index date
|
||||
|
||||
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
|
||||
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
|
||||
the batch's build, the one their horizons were counted from; then the column is required.
|
||||
|
||||
Revision ID: b2e5f8d31c42
|
||||
Revises: a9c4e2f17d38
|
||||
Create Date: 2026-11-20 21:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b2e5f8d31c42'
|
||||
down_revision = 'a9c4e2f17d38'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
|
||||
op.execute(
|
||||
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
|
||||
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
|
||||
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
|
||||
)
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.drop_column('fecha_indice')
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""cama heads joined
|
||||
|
||||
The date of death (`pac_fecha_defuncion`, `fecha_defuncion`) and the index date of each risk
|
||||
(`evaluacion_riesgo.fecha_indice`) 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: d4a7c1e93b58
|
||||
Revises: a9c4e2f17d38, b2e5f8d31c42
|
||||
Create Date: 2026-11-21 00:30:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd4a7c1e93b58'
|
||||
down_revision = ('a9c4e2f17d38', 'b2e5f8d31c42')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -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')
|
||||
@@ -14,6 +14,7 @@ from persistance.edges.gold.cohorts import (
|
||||
CohortMember,
|
||||
PatientMembership,
|
||||
PatientRisk,
|
||||
PendingBatch,
|
||||
RiskOutsideCohort,
|
||||
RiskHorizon,
|
||||
change_state_in,
|
||||
@@ -34,6 +35,7 @@ __all__ = [
|
||||
"MeasureReportRepository",
|
||||
"PatientMembership",
|
||||
"PatientRisk",
|
||||
"PendingBatch",
|
||||
"PublicationRepository",
|
||||
"ReferenceRepository",
|
||||
"RiskOutsideCohort",
|
||||
|
||||
@@ -114,6 +114,22 @@ class CohortRepository(Repository):
|
||||
{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;
|
||||
@@ -133,7 +149,7 @@ class CohortRepository(Repository):
|
||||
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])
|
||||
for r in rows], rows[0].fecha_indice if rows else None, batch.desenlace)
|
||||
return None
|
||||
|
||||
|
||||
@@ -159,6 +175,18 @@ class RiskHorizon:
|
||||
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."""
|
||||
@@ -169,6 +197,8 @@ class PatientRisk:
|
||||
evaluado_en: datetime
|
||||
estado_lote: str
|
||||
horizontes: list[RiskHorizon]
|
||||
fecha_indice: date | None = None # the model's index date for the patient, which the horizons count from
|
||||
desenlace: str | None = None # the batch's outcome (FHIR `RiskAssessment.prediction.outcome`)
|
||||
|
||||
|
||||
def _latest_versions(sesion: Session, e, lote_id: int):
|
||||
@@ -256,12 +286,14 @@ def save_batch_in(
|
||||
armado_id: int,
|
||||
procedencia: dict,
|
||||
desenlace: str,
|
||||
riesgos: list[tuple[int, float, float, float | None, float | None]],
|
||||
riesgos: list[tuple[int, date, float, float, float | None, float | None]],
|
||||
*,
|
||||
cohortes: TablasCohorte,
|
||||
ahora: datetime | None = None,
|
||||
) -> tuple[int, bool]:
|
||||
"""Guarda los riesgos `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve (`lote_id`, nuevo).
|
||||
"""Guarda los riesgos `(pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve
|
||||
(`lote_id`, nuevo). `fecha_indice` es el punto de decisión del modelo para esa paciente: una por paciente en el
|
||||
lote, la misma en todos sus horizontes.
|
||||
|
||||
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á.
|
||||
@@ -274,8 +306,15 @@ def save_batch_in(
|
||||
ajenos = sorted({pac for pac, *_ in riesgos} - miembros)
|
||||
if ajenos:
|
||||
raise RiskOutsideCohort(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
|
||||
fechas: dict[int, set] = {}
|
||||
for pac, fecha, *_ in riesgos:
|
||||
if fecha is None:
|
||||
raise ValueError("Un riesgo sin `fecha_indice`: el modelo debe decir desde cuándo predice.")
|
||||
fechas.setdefault(pac, set()).add(fecha)
|
||||
if varias := sorted(pac for pac, f in fechas.items() if len(f) > 1):
|
||||
raise ValueError(f"Más de una `fecha_indice` por paciente en el lote: {len(varias)} pacientes.")
|
||||
huella = _json_sha({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROVENANCE},
|
||||
"riesgos": sorted(riesgos)})
|
||||
"riesgos": sorted((pac, str(f), h, p, bajo, alto) for pac, f, h, p, bajo, alto in riesgos)})
|
||||
lote = cohortes.EvaluacionRiesgoLote
|
||||
previo = sesion.exec(select(lote).where(lote.huella == huella)).first()
|
||||
if previo is not None:
|
||||
@@ -287,9 +326,10 @@ def save_batch_in(
|
||||
sesion.add(fila)
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, horizonte_anios=float(h), probabilidad=float(p),
|
||||
ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR, registrado_en=momento)
|
||||
for pac, h, p, bajo, alto in riesgos
|
||||
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, fecha_indice=fecha, horizonte_anios=float(h),
|
||||
probabilidad=float(p), ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR,
|
||||
registrado_en=momento)
|
||||
for pac, fecha, h, p, bajo, alto in riesgos
|
||||
)
|
||||
sesion.commit()
|
||||
except Exception:
|
||||
@@ -319,7 +359,8 @@ def change_state_in(
|
||||
momento = ahora or datetime.now(timezone.utc)
|
||||
try:
|
||||
sesion.add_all(
|
||||
e(lote_id=lote_id, pac_id=v.pac_id, horizonte_anios=v.horizonte_anios, probabilidad=v.probabilidad,
|
||||
e(lote_id=lote_id, pac_id=v.pac_id, fecha_indice=v.fecha_indice, horizonte_anios=v.horizonte_anios,
|
||||
probabilidad=v.probabilidad,
|
||||
ic_bajo=v.ic_bajo, ic_alto=v.ic_alto, version=v.version + 1, estado=estado, motivo=motivo,
|
||||
registrado_en=momento)
|
||||
for v in vigentes
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""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."""
|
||||
"""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,
|
||||
@@ -7,6 +7,7 @@ from persistance.edges.silver.loads import (
|
||||
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 (
|
||||
@@ -22,6 +23,7 @@ from persistance.edges.silver.views import ViewsRepository
|
||||
__all__ = [
|
||||
"LoadRepository",
|
||||
"CatalogRepository",
|
||||
"SourceMappingRepository",
|
||||
"ObservationRepository",
|
||||
"TIMELINE_COLUMNS",
|
||||
"TimelineContractError",
|
||||
|
||||
@@ -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)
|
||||
@@ -2,7 +2,9 @@ from core.tea.indicadores.models import (
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CatEstudio,
|
||||
CatMapeo,
|
||||
CatResultado,
|
||||
CatSistemaFuente,
|
||||
CatValor,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
@@ -32,11 +34,14 @@ from core.tea.models import (
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegCriterio,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
RelacionAdos2,
|
||||
RelacionAdos2Paciente,
|
||||
)
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
@@ -56,6 +61,7 @@ from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
SourceMappingRepository,
|
||||
TimelineRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
@@ -71,6 +77,9 @@ evaluacion_neuropediatrica_repository = Repository(get_tea_session, EvaluacionNe
|
||||
eeg_repository = Repository(get_tea_session, Eeg)
|
||||
eeg_metrica_repository = Repository(get_tea_session, EegMetrica)
|
||||
eeg_metrica_electrodo_repository = Repository(get_tea_session, EegMetricaElectrodo)
|
||||
eeg_criterio_repository = Repository(get_tea_session, EegCriterio)
|
||||
relacion_ados2_repository = Repository(get_tea_session, RelacionAdos2)
|
||||
relacion_ados2_paciente_repository = Repository(get_tea_session, RelacionAdos2Paciente)
|
||||
|
||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
||||
@@ -104,6 +113,7 @@ observacion_repository = Repository(get_tea_session, Observacion)
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(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,
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""tea eeg analysis
|
||||
|
||||
What the EEG analysis writes from the stored EDF: its verdict, triage level, clean fraction, bad channels, the age it
|
||||
compared the metrics at and what produced it, on `eeg`; one row per quality check in `eeg_criterio`; each metric's
|
||||
z, -1/0/+1 against the age baseline and the baseline's p5/median/p95 there, on `eeg_metrica`; each electrode's z, on
|
||||
`eeg_metrica_electrodo`. Only additions: nothing existing changes.
|
||||
|
||||
Revision ID: 16bf0b0ee3e4
|
||||
Revises: b9e4d2c71a05
|
||||
Create Date: 2026-11-19 13:14:08.006494
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '16bf0b0ee3e4'
|
||||
down_revision = 'b9e4d2c71a05'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('eeg_criterio',
|
||||
sa.Column('cri_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('cri_eeg_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('cri_codigo', sa.Text(), nullable=True),
|
||||
sa.Column('cri_electrodo', sa.Text(), nullable=True),
|
||||
sa.Column('cri_valor', sa.Float(), nullable=True),
|
||||
sa.Column('cri_valor_texto', sa.Text(), nullable=True),
|
||||
sa.Column('cri_unidad', sa.Text(), nullable=True),
|
||||
sa.Column('cri_bajo', sa.Float(), nullable=True),
|
||||
sa.Column('cri_alto', sa.Float(), nullable=True),
|
||||
sa.Column('cri_decisivo', sa.Integer(), nullable=True),
|
||||
sa.Column('cri_anormal', sa.Integer(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('cri_id')
|
||||
)
|
||||
with op.batch_alter_table('eeg_criterio', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_eeg_criterio_cri_eeg_id'), ['cri_eeg_id'], unique=False)
|
||||
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('eeg_valido', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_nivel', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_fraccion_limpia', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_canales_malos', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_edad_meses', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_plan_hash', sa.String(length=16), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_versiones', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_analizado_en', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_error', sa.Text(), nullable=True))
|
||||
|
||||
with op.batch_alter_table('eeg_metrica', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('met_z', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_fuera', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_p5', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_mediana', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_p95', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_modelo', sa.Text(), nullable=True))
|
||||
|
||||
with op.batch_alter_table('eeg_metrica_electrodo', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('mel_z', sa.Float(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('eeg_metrica_electrodo', schema=None) as batch_op:
|
||||
batch_op.drop_column('mel_z')
|
||||
|
||||
with op.batch_alter_table('eeg_metrica', schema=None) as batch_op:
|
||||
batch_op.drop_column('met_modelo')
|
||||
batch_op.drop_column('met_p95')
|
||||
batch_op.drop_column('met_mediana')
|
||||
batch_op.drop_column('met_p5')
|
||||
batch_op.drop_column('met_fuera')
|
||||
batch_op.drop_column('met_z')
|
||||
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
batch_op.drop_column('eeg_error')
|
||||
batch_op.drop_column('eeg_analizado_en')
|
||||
batch_op.drop_column('eeg_versiones')
|
||||
batch_op.drop_column('eeg_plan_hash')
|
||||
batch_op.drop_column('eeg_edad_meses')
|
||||
batch_op.drop_column('eeg_canales_malos')
|
||||
batch_op.drop_column('eeg_fraccion_limpia')
|
||||
batch_op.drop_column('eeg_nivel')
|
||||
batch_op.drop_column('eeg_valido')
|
||||
|
||||
with op.batch_alter_table('eeg_criterio', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_eeg_criterio_cri_eeg_id'))
|
||||
|
||||
op.drop_table('eeg_criterio')
|
||||
@@ -0,0 +1,70 @@
|
||||
"""tea ados2 association
|
||||
|
||||
What the ADOS-2 association model writes: one row per model version and association in `relacion_ados2`, the cohort
|
||||
odds ratio of an EEG alteration in a scalp zone against an ADOS-2 item or domain outcome, with its confidence
|
||||
interval and q value; one row per EEG and association in `relacion_ados2_paciente`, the patient's z and the
|
||||
probability the model gives them (the observed outcome stays in `ados2`, never stored here). Only additions:
|
||||
nothing existing changes.
|
||||
|
||||
Revision ID: 41694156d3a1
|
||||
Revises: c4306f438b3a
|
||||
Create Date: 2026-11-21 01:49:39.884071
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '41694156d3a1'
|
||||
down_revision = 'c4306f438b3a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('relacion_ados2',
|
||||
sa.Column('rel_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('rel_version', sa.String(length=32), nullable=True),
|
||||
sa.Column('rel_nivel', sa.Text(), nullable=True),
|
||||
sa.Column('rel_validado', sa.Integer(), nullable=True),
|
||||
sa.Column('rel_n_cohorte', sa.Integer(), nullable=True),
|
||||
sa.Column('rel_biomarcador', sa.String(length=32), nullable=True),
|
||||
sa.Column('rel_zona', sa.String(length=32), nullable=True),
|
||||
sa.Column('rel_tipo', sa.Text(), nullable=True),
|
||||
sa.Column('rel_resultado', sa.String(length=32), nullable=True),
|
||||
sa.Column('rel_evento', sa.Text(), nullable=True),
|
||||
sa.Column('rel_or', sa.Float(), nullable=True),
|
||||
sa.Column('rel_ic_inf', sa.Float(), nullable=True),
|
||||
sa.Column('rel_ic_sup', sa.Float(), nullable=True),
|
||||
sa.Column('rel_q', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('rel_id'),
|
||||
sa.UniqueConstraint('rel_version', 'rel_biomarcador', 'rel_zona', 'rel_resultado', name='uq_relacion_ados2')
|
||||
)
|
||||
with op.batch_alter_table('relacion_ados2', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_relacion_ados2_rel_version'), ['rel_version'], unique=False)
|
||||
|
||||
op.create_table('relacion_ados2_paciente',
|
||||
sa.Column('rap_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('rap_rel_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('rap_eeg_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('rap_valor_z', sa.Float(), nullable=True),
|
||||
sa.Column('rap_probabilidad', sa.Float(), nullable=True),
|
||||
sa.Column('rap_probabilidad_referencia', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('rap_id'),
|
||||
sa.UniqueConstraint('rap_rel_id', 'rap_eeg_id', name='uq_relacion_ados2_paciente')
|
||||
)
|
||||
with op.batch_alter_table('relacion_ados2_paciente', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_relacion_ados2_paciente_rap_eeg_id'), ['rap_eeg_id'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_relacion_ados2_paciente_rap_rel_id'), ['rap_rel_id'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('relacion_ados2_paciente', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_relacion_ados2_paciente_rap_rel_id'))
|
||||
batch_op.drop_index(batch_op.f('ix_relacion_ados2_paciente_rap_eeg_id'))
|
||||
|
||||
op.drop_table('relacion_ados2_paciente')
|
||||
with op.batch_alter_table('relacion_ados2', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_relacion_ados2_rel_version'))
|
||||
|
||||
op.drop_table('relacion_ados2')
|
||||
@@ -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,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,37 @@
|
||||
"""risk index date
|
||||
|
||||
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
|
||||
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
|
||||
the batch's build, the one their horizons were counted from; then the column is required.
|
||||
|
||||
Revision ID: c3f6a9e42d53
|
||||
Revises: c4306f438b3a
|
||||
Create Date: 2026-11-20 21:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c3f6a9e42d53'
|
||||
down_revision = 'c4306f438b3a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
|
||||
op.execute(
|
||||
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
|
||||
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
|
||||
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
|
||||
)
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.drop_column('fecha_indice')
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
"""tea eeg criteria columns dropped
|
||||
|
||||
The EEG analysis writes each quality check as a row of `eeg_criterio`, so the four fixed criterion columns of `eeg`
|
||||
go. Downgrade brings them back empty: the counts they held aren't kept anywhere else.
|
||||
|
||||
Revision ID: c4306f438b3a
|
||||
Revises: 16bf0b0ee3e4
|
||||
Create Date: 2026-11-19 14:09:04.196709
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c4306f438b3a'
|
||||
down_revision = '16bf0b0ee3e4'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
COLUMNS = ('eeg_canales_amplitud', 'eeg_canales_alta_frecuencia', 'eeg_canales_correlacion', 'eeg_canales_sin_senal')
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
for column in COLUMNS:
|
||||
batch_op.drop_column(column)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
for column in COLUMNS:
|
||||
batch_op.add_column(sa.Column(column, sa.Integer(), nullable=True))
|
||||
@@ -0,0 +1,24 @@
|
||||
"""tea heads joined
|
||||
|
||||
The risk's index date (`evaluacion_riesgo.fecha_indice`) and the ADOS-2 association columns 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: e8c2a5d47f13
|
||||
Revises: 41694156d3a1, c3f6a9e42d53
|
||||
Create Date: 2026-11-21 14:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'e8c2a5d47f13'
|
||||
down_revision = ('41694156d3a1', 'c3f6a9e42d53')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -15,7 +15,7 @@ from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, Cohor
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from persistance.edges.gold import CohortRepository, RiskHorizon
|
||||
from persistance.edges.gold import CohortRepository, PendingBatch, RiskHorizon
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
@@ -46,6 +46,9 @@ def repository():
|
||||
return CohortRepository(lambda: Session(engine), TABLES)
|
||||
|
||||
|
||||
D = date(2026, 3, 15) # the model's index date for patient 10, not her member's (2025-01-02)
|
||||
|
||||
|
||||
def _batch(repository, version, risks, armado_id=2):
|
||||
return repository.save_batch(armado_id, {**PROVENANCE, "modelo_version": version}, "cin2_12m", risks)[0]
|
||||
|
||||
@@ -63,7 +66,7 @@ def test_membership_is_in_the_latest_build_with_its_variables(repository):
|
||||
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)])
|
||||
_batch(repository, "1", [(10, D, 1.0, 0.2, None, None)])
|
||||
|
||||
assert repository.current_risk(10) is None
|
||||
|
||||
@@ -72,21 +75,53 @@ def test_the_current_batch_is_the_newest_confirmed_one_with_its_horizons(reposit
|
||||
"""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)])
|
||||
first = _batch(repository, "1", [(10, D, 3.0, 0.3, None, None), (10, D, 1.0, 0.1, 0.05, 0.2)])
|
||||
repository.change_state(first, "final", "revisado")
|
||||
_batch(repository, "2", [(10, 1.0, 0.9, None, None)])
|
||||
_batch(repository, "2", [(10, D, 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.lote_id, risk.modelo_version, risk.estado_lote, risk.fecha_indice) == (first, "1", "final", D)
|
||||
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)])
|
||||
first = _batch(repository, "1", [(10, D, 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, D, 1.0, 0.1, None, None)])
|
||||
second = _batch(repository, "2", [(10, D, 1.0, 0.2, None, None)])
|
||||
third = _batch(repository, "3", [(10, D, 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]
|
||||
|
||||
|
||||
def test_a_risk_needs_one_index_date_per_patient(repository):
|
||||
"""Pins down: each risk carries the model's index date for its patient, kept through a change of state, and a
|
||||
batch with no date or two dates for one patient is refused. Fails if the horizons could count from different dates
|
||||
or from none."""
|
||||
with pytest.raises(ValueError, match="sin `fecha_indice`"):
|
||||
_batch(repository, "1", [(10, None, 1.0, 0.1, None, None)])
|
||||
with pytest.raises(ValueError, match="Más de una"):
|
||||
_batch(repository, "1", [(10, D, 1.0, 0.1, None, None), (10, date(2026, 1, 1), 3.0, 0.3, None, None)])
|
||||
lote = _batch(repository, "1", [(10, D, 1.0, 0.1, None, None)])
|
||||
repository.change_state(lote, "final", "revisado")
|
||||
|
||||
assert repository.current_risk(10).fecha_indice == D
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""What this module covers: the TEA Alembic chain in `persistance/tea/alembic`, applied through
|
||||
`alembic.command` to a throwaway SQLite file: the deployed schema has the ADOS-2 association tables with
|
||||
their natural keys, downgrading the association revision removes exactly those tables, and the migrated
|
||||
schema never drifts from `core.tea.models`.
|
||||
|
||||
Fixtures: `url_tea` points `settings.tea_database_url` at a temp file and runs `upgrade head`, so a broken
|
||||
migration fails the suite instead of the tests silently building the schema with `create_all`; it restores
|
||||
the original URL and clears the cached engine afterwards (`persistance.db` caches engines per URL).
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from sqlalchemy import create_engine, inspect
|
||||
|
||||
import persistance
|
||||
from persistance import db as persistance_db
|
||||
from persistance.settings import settings
|
||||
|
||||
|
||||
def _config() -> Config:
|
||||
ini = Path(persistance.__file__).parent / "tea" / "alembic.ini"
|
||||
return Config(str(ini))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def url_tea(tmp_path):
|
||||
"""A temp SQLite file whose schema the migrations built, stamped at `head`."""
|
||||
url_original = settings.tea_database_url
|
||||
url = f"sqlite:///{tmp_path / 'tea.db'}"
|
||||
settings.tea_database_url = url
|
||||
persistance_db.get_tea_engine.cache_clear()
|
||||
command.upgrade(_config(), "head")
|
||||
yield url
|
||||
persistance_db.get_tea_engine.cache_clear()
|
||||
settings.tea_database_url = url_original
|
||||
|
||||
|
||||
def test_association_tables_deployed_with_their_natural_keys(url_tea):
|
||||
"""Pins down: `relacion_ados2` exists with the unique (rel_version, rel_biomarcador, rel_zona,
|
||||
rel_resultado) that the import merge and the `tea` library upsert on, and `relacion_ados2_paciente`
|
||||
with one row per (rap_rel_id, rap_eeg_id). Fails if the migration creating the tables is dropped or
|
||||
loses a constraint."""
|
||||
inspector = inspect(create_engine(url_tea))
|
||||
assert {"relacion_ados2", "relacion_ados2_paciente"} <= set(inspector.get_table_names())
|
||||
|
||||
uniques = {tuple(c["column_names"]) for c in inspector.get_unique_constraints("relacion_ados2")}
|
||||
assert ("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado") in uniques
|
||||
uniques_paciente = {tuple(c["column_names"])
|
||||
for c in inspector.get_unique_constraints("relacion_ados2_paciente")}
|
||||
assert ("rap_rel_id", "rap_eeg_id") in uniques_paciente
|
||||
|
||||
|
||||
def test_downgrade_of_the_association_revision_drops_only_the_association_tables(url_tea):
|
||||
"""Pins down: `downgrade -1` removes `relacion_ados2` and `relacion_ados2_paciente` and nothing the
|
||||
hospital source loaded. Fails if the downgrade stops dropping them, or starts dropping other tables."""
|
||||
command.downgrade(_config(), "-1")
|
||||
names = set(inspect(create_engine(url_tea)).get_table_names())
|
||||
assert "relacion_ados2" not in names
|
||||
assert "relacion_ados2_paciente" not in names
|
||||
assert {"pacientes", "ordenes_estudio", "mchat", "ados2", "eeg", "eeg_metrica",
|
||||
"eeg_criterio", "eeg_metrica_electrodo"} <= names
|
||||
|
||||
|
||||
def test_migrated_schema_matches_the_models(url_tea):
|
||||
"""Pins down: `alembic check` sees no difference between the migrated schema and `core.tea.models`,
|
||||
so a model change can never land without its migration. Fails if the metadata and the chain drift."""
|
||||
command.check(_config())
|
||||
@@ -19,7 +19,6 @@ operación, en [`dist/MANUAL.md`](dist/MANUAL.md).
|
||||
| `WebApp/` (submódulo) | Interfaz en Angular y Angular Material. |
|
||||
| `models/` (submódulo) | Registro de modelos en MLflow, predicciones y trabajos de OCR de reportes. |
|
||||
| `Transformation/` | dbt: los modelos sobre la plata genérica y las definiciones de los indicadores (capa semántica). |
|
||||
| `indicadores_kit/` (submódulo) | Ya sin código: sus indicadores están en `Transformation/`, su carga, referencias y lista de seguimiento en `WebApi/`, y sus cohortes en `models/`. |
|
||||
| `dist/` | Paquete de instalación: `docker-compose.yml`, scripts y manual. |
|
||||
|
||||
Cambiar de motor de base de datos (SQLite, MySQL/MariaDB, PostgreSQL o SQL
|
||||
|
||||
@@ -53,15 +53,46 @@ vars:
|
||||
"C508", "C509"]
|
||||
cie_antecedente: ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505",
|
||||
"C506", "C508", "C509"]
|
||||
# Each patient's clinical scenario (models/cama/silver/cama_procedimientos_inferidos.sql), one of two: a patient
|
||||
# is in post-treatment from her first evidence of a kind `postratamiento_evidencias` names, and under observation
|
||||
# ("en observación") otherwise. The timeline keeps that evidence as an `escenario_postratamiento` fact with its
|
||||
# kind in `valor_codigo`; being under observation has no fact.
|
||||
# egreso a note of one of `tipos_nota_egreso` with one of `cie_tumor_maligno`, or on or after her diagnosis
|
||||
# nota a note with one of `cie_tumor_maligno` by one of `tratamiento_especialidades`, after her diagnosis
|
||||
# Her diagnosis is her first evidence of a kind `diagnostico_evidencias` names. cie: a note with one of
|
||||
# `cie_tumor_maligno` (an in situ carcinoma isn't one), whoever wrote it; biopsia: a report of one of
|
||||
# `grados_malignos`.
|
||||
escenarios:
|
||||
postratamiento_evidencias: ["egreso"]
|
||||
tipos_nota_egreso: ["EGRESO"]
|
||||
tratamiento_especialidades: ["CIRUGIA_ONCOLOGICA", "ONCOLOGIA_MEDICA"]
|
||||
diagnostico_evidencias: ["cie"]
|
||||
cie_tumor_maligno: ["C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509"]
|
||||
grados_malignos: ["CARCINOMA_INVASOR"]
|
||||
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. `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"]
|
||||
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.
|
||||
# Whether an EEG is valid, and whether a metric is altered (outside its age baseline's p5-p95), is the EEG
|
||||
# analysis's: the baselines are the trained models in production, which the domain expert validates.
|
||||
tea:
|
||||
edad_min_meses: 16
|
||||
edad_max_meses: 36
|
||||
@@ -96,12 +127,56 @@ vars:
|
||||
- ["gradiente_anteroposterior", "16_23", 2.0, 3.5]
|
||||
- ["gradiente_anteroposterior", "24_29", 1.75, 3.25]
|
||||
- ["gradiente_anteroposterior", "30_36", 1.5, 3.0]
|
||||
# CaMa's survival cohort (models/cama/cohorts/survival): the surgeries that are its procedure of interest
|
||||
# (ESCISIONAL includes a lumpectomy). Provisional, to be decided with the domain expert.
|
||||
survival_cohort:
|
||||
recruitment_start: "2018-01-01"
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-12-31"
|
||||
surgeries: ["ESCISIONAL", "SEGMENTECTOMIA", "MASTECTOMIA_TOTAL", "MASTECTOMIA_RADICAL_MODIFICADA"]
|
||||
# The surveillance cohort's rules (models/cacu/cohorts/surveillance).
|
||||
# CaCu's recruitment window and cut-off, once: every CaCu cohort takes them (YAML merge key), so the post-colposcopy
|
||||
# and total cohorts (and the scenarios indexed in their pipelines) recruit as the surveillance cohort does.
|
||||
cacu_window: &cacu_window
|
||||
recruitment_start: "2024-01-01"
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-12-31"
|
||||
surveillance_cohort:
|
||||
<<: *cacu_window
|
||||
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
# The post-colposcopy cohorts (models/cacu/cohorts/post_colposcopy, one per visit k; KPNC's post-colposcopy
|
||||
# tables, Cheung et al. 2020): indexed at the first colposcopy's result (k = 0) or at the k-th surveillance visit
|
||||
# after it, stratified by the result that referred the patient (within `referral_lookback_days` before the
|
||||
# colposcopy; provisional). `hysterectomy_cie`: provisional, ICD-10 Z90.7 is the absence of any genital organ.
|
||||
post_colposcopy_cohort:
|
||||
<<: *cacu_window
|
||||
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
referral_lookback_days: 365
|
||||
hysterectomy_cie: ["Z907"]
|
||||
# The total cohort (models/cacu/cohorts/total): every patient with an event up to the cut-off, with no rules, for
|
||||
# models that apply their own; its recruitment window is carried in its parameters for their index.
|
||||
total_cohort:
|
||||
<<: *cacu_window
|
||||
# CaMa's recruitment window and cut-off, once (YAML merge key), and its total cohort (models/cama/cohorts/total):
|
||||
# every patient with a clinical event up to the cut-off, with no rules, for the scenarios that index and filter in
|
||||
# their own pipeline. The window is the one the scenarios take for their index; the cut-off is where follow-up ends
|
||||
# (provisional: the synthetic hospital's reference date).
|
||||
cama_window: &cama_window
|
||||
recruitment_start: "2018-01-01"
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-01-01"
|
||||
cama_total_cohort:
|
||||
<<: *cama_window
|
||||
# The post-treatment cohort (models/cacu/cohorts/post_treatment; KPNC's post-treatment tables): the first cytology
|
||||
# more than `index_after_days` after the first treatment, stratified by the biopsy before it (within
|
||||
# `pretreatment_lookback_days`).
|
||||
post_treatment_cohort:
|
||||
recruitment_start: "2024-01-01"
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-12-31"
|
||||
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
index_after_days: 90
|
||||
pretreatment_lookback_days: 365
|
||||
# models/<project>/silver: what dbt derives from silver's procedimiento and observacion_clinica, compiled as
|
||||
# CTEs inside the models that use them (no objects in the database), except the timeline, a view.
|
||||
# models/<project>/gold/<family>: one view per indicator, a folder per family as in the kit.
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
{#
|
||||
The post-colposcopy cohorts, one per visit k (KPNC's post-colposcopy tables; Cheung et al. 2020,
|
||||
doi:10.1097/LGT.0000000000000528): k = 0 is the colposcopy's result (below CIN2), k ≥ 1 the k-th surveillance visit
|
||||
after it. Every cohort has the same rules; only the index changes. A new visit is a folder `visit_<k>` whose models
|
||||
call these macros with its k (see models/cacu/cohorts/post_colposcopy/README.md).
|
||||
Parameters: the `post_colposcopy_cohort` var.
|
||||
#}
|
||||
|
||||
{# The index of visit k: the colposcopy's result (k = 0) or visit k, if it falls in the recruitment window. #}
|
||||
{% macro cacu_post_colposcopy_index(k) -%}
|
||||
{%- set p = var('post_colposcopy_cohort') -%}
|
||||
{%- if k == 0 %}
|
||||
select pac_id, fecha_resultado as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id,
|
||||
fecha_colposcopia, fecha_resultado, ordenes_sin_resultado
|
||||
from {{ ref('cacu_post_colposcopy_episode') }}
|
||||
where fecha_resultado >= '{{ p.recruitment_start }}' and fecha_resultado < '{{ p.recruitment_end }}'
|
||||
{%- else %}
|
||||
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id,
|
||||
fecha_colposcopia, fecha_resultado, ordenes_sin_resultado
|
||||
from {{ ref('cacu_post_colposcopy_visits') }}
|
||||
where numero = {{ k }} and fecha >= '{{ p.recruitment_start }}' and fecha < '{{ p.recruitment_end }}'
|
||||
{%- endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
{# Every patient of the domain: where the cohort's attrition starts. #}
|
||||
{% macro cacu_post_colposcopy_population() -%}
|
||||
select pac_id from {{ source('silver', 'persona') }}
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
{#
|
||||
One exclusion rule over the cohort's index model `index` (a model name). Each reads only the index and the data.
|
||||
- biopsia_sin_resultado a biopsy ordered at the colposcopy has no report: its result is unknown
|
||||
- cin2_hasta_el_indice a biopsy with the outcome up to the index (the colposcopy found it, or it came before)
|
||||
- antecedente_cacu a note with a cervical cancer ICD-10 up to the index (`antecedente`)
|
||||
- histerectomia a note with an ICD-10 of `hysterectomy_cie` up to the index
|
||||
- tratamiento_previo treated up to the index: she belongs to the post-treatment cohort
|
||||
- sin_referencia no cytology or HPV result in the `referral_lookback_days` up to the colposcopy
|
||||
- sin_cotest the index sample lacks an HPV result or a cytology result (squamous or glandular)
|
||||
#}
|
||||
{% macro cacu_post_colposcopy_exclusion(rule, index) -%}
|
||||
{%- set p = var('post_colposcopy_cohort') -%}
|
||||
{%- if rule == 'biopsia_sin_resultado' %}
|
||||
select pac_id from {{ ref(index) }} where ordenes_sin_resultado > 0
|
||||
{%- elif rule in ('cin2_hasta_el_indice', 'antecedente_cacu', 'histerectomia', 'tratamiento_previo') %}
|
||||
select distinct c.pac_id
|
||||
from {{ ref(index) }} as c
|
||||
join {{ ref('cacu_linea_de_tiempo') }} as e on e.pac_id = c.pac_id
|
||||
where e.fecha <= c.fecha_indice
|
||||
{%- if rule == 'cin2_hasta_el_indice' %}
|
||||
and e.tipo = 'biopsia' and e.valor_codigo in ('{{ p.event_grades | join("', '") }}')
|
||||
{%- elif rule == 'antecedente_cacu' %}
|
||||
and e.tipo = 'antecedente'
|
||||
{%- elif rule == 'histerectomia' %}
|
||||
and e.tipo = 'nota_medica' and e.valor_codigo in ('{{ p.hysterectomy_cie | join("', '") }}')
|
||||
{%- else %}
|
||||
and e.tipo = 'tratamiento'
|
||||
{%- endif %}
|
||||
{%- elif rule == 'sin_referencia' %}
|
||||
select c.pac_id
|
||||
from {{ ref(index) }} as c
|
||||
join {{ source('silver', 'dim_fecha') }} as dc on dc.fecha = c.fecha_colposcopia
|
||||
where not exists (
|
||||
select 1
|
||||
from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
join {{ source('silver', 'dim_fecha') }} as de on de.fecha = e.fecha
|
||||
where e.pac_id = c.pac_id
|
||||
and e.tipo in ('bethesda', 'glandular', 'vph')
|
||||
and e.valor_codigo is not null
|
||||
and de.dia_num <= dc.dia_num
|
||||
and dc.dia_num - de.dia_num <= {{ p.referral_lookback_days }}
|
||||
)
|
||||
{%- elif rule == 'sin_cotest' %}
|
||||
select c.pac_id
|
||||
from {{ ref(index) }} as c
|
||||
where not exists (
|
||||
select 1 from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
where e.pac_id = c.pac_id and e.fuente_tabla = c.indice_fuente_tabla and e.fuente_id = c.indice_fuente_id
|
||||
and e.tipo = 'vph' and e.valor_codigo is not null and e.fecha <= '{{ p.cutoff }}'
|
||||
)
|
||||
or not exists (
|
||||
select 1 from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
where e.pac_id = c.pac_id and e.fuente_tabla = c.indice_fuente_tabla and e.fuente_id = c.indice_fuente_id
|
||||
and e.tipo in ('bethesda', 'glandular') and e.valor_codigo is not null and e.fecha <= '{{ p.cutoff }}'
|
||||
)
|
||||
{%- else %}
|
||||
{{ exceptions.raise_compiler_error("unknown post-colposcopy rule: " ~ rule) }}
|
||||
{%- endif %}
|
||||
{%- endmacro %}
|
||||
@@ -31,9 +31,20 @@
|
||||
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] }})
|
||||
{# The EEG's metrics and quality checks as the catalog names them: `eeg.<metric>`, `eeg.calidad_<check>`. The checks
|
||||
are the EEG analysis's: study-wide ones on the recording, channel ones on a `parte` per bad channel. #}
|
||||
{% macro tea_metricas() -%}
|
||||
{{ return(['ritmo_posterior', 'husos_sueno_n2', 'husos_sueno_n3', 'picos_paroxisticos', 'gradiente_anteroposterior']) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro tea_criterios_estudio() -%}
|
||||
{{ return(['clean_windows', 'internal_coverage', 'bad_scalp_triage', 'usable_scalp', 'triage_level', 'line_noise',
|
||||
'file']) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro tea_criterios_canal() -%}
|
||||
{{ return(['dead_channel', 'frozen', 'saturated', 'inf_values', 'own_gaps', 'bridge', 'amplitude', 'aux_amplitude',
|
||||
'does_not_correlate', 'intermittent_contact', 'intermittent_bursts']) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{# The later of two values when both are known, else null: a step reached after the previous one is dated by the
|
||||
|
||||
@@ -10,3 +10,21 @@
|
||||
('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u')] -%}
|
||||
upper({% for _ in pares %}replace({% endfor %}{{ columna }}{% for con, sin in pares %}, '{{ con }}', '{{ sin }}'){% endfor %})
|
||||
{%- endmacro %}
|
||||
|
||||
{# Texts joined into one, portable: `||` on SQLite and PostgreSQL, CONCAT on MySQL, + on SQL Server. A null part
|
||||
nulls the whole on SQL Server, where the join then simply doesn't match; the parts are never null there. #}
|
||||
{% macro concatena() -%}
|
||||
{{ return(adapter.dispatch('concatena', 'isssteleon')(varargs)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__concatena(campos) -%}
|
||||
{{ campos | join(' || ') }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro mysql__concatena(campos) -%}
|
||||
concat({{ campos | join(', ') }})
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro sqlserver__concatena(campos) -%}
|
||||
{{ campos | join(' + ') }}
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -13,6 +13,16 @@ 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
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
version: 2
|
||||
|
||||
# The post-colposcopy cohorts (KPNC's post-colposcopy tables; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528):
|
||||
# one per visit k in `visit_<k>/`, read as the surveillance cohort's are (`models cohorts build` chains the
|
||||
# exclusions in `order`; each reads only the index date and the data). The two models here are shared by all of them
|
||||
# and belong to no cohort. Rules: macros/cacu_post_colposcopy.sql. Parameters: the `post_colposcopy_cohort` var.
|
||||
models:
|
||||
- name: cacu_post_colposcopy_episode
|
||||
description: >
|
||||
The patient's first colposcopy and when its result is known (the last report of the biopsies ordered that day,
|
||||
or the colposcopy's date with none ordered: provisionally taken as below CIN2), and how many of those orders
|
||||
have no report.
|
||||
config: {materialized: ephemeral}
|
||||
- name: cacu_post_colposcopy_visits
|
||||
description: >
|
||||
The surveillance visits (cytology samples) after the first colposcopy's result is known and before any later
|
||||
colposcopy, numbered from 1.
|
||||
config: {materialized: ephemeral}
|
||||
|
||||
unit_tests:
|
||||
- name: the_colposcopy_result_is_the_last_report_of_its_biopsies
|
||||
description: >
|
||||
Pins down: patient 1's result date is the later of the two reports of the biopsies ordered on her first
|
||||
colposcopy's day; the biopsy of her second colposcopy doesn't count. Patient 2 had no biopsy ordered, so her
|
||||
result date is the colposcopy's (provisionally below CIN2). Patient 3's order has no report, so it is counted
|
||||
as unknown. Fails if the episode takes a later colposcopy, a biopsy of another day, or stops counting the
|
||||
unreported orders.
|
||||
model: cacu_post_colposcopy_episode
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha, 'colposcopia' as tipo, null as valor_codigo, 'n' as fuente_tabla, 'c1' as fuente_id
|
||||
union all select 1, '2025-01-10', 'orden_biopsia', null, 'b', 'o1'
|
||||
union all select 1, '2025-01-10', 'orden_biopsia', null, 'b', 'o2'
|
||||
union all select 1, '2025-01-20', 'biopsia', 'LIEBG', 'b', 'o1'
|
||||
union all select 1, '2025-01-31', 'biopsia', 'NEGATIVO', 'b', 'o2'
|
||||
union all select 1, '2025-06-01', 'colposcopia', null, 'n', 'c2'
|
||||
union all select 1, '2025-06-01', 'orden_biopsia', null, 'b', 'o3'
|
||||
union all select 1, '2025-06-20', 'biopsia', 'LIEBG', 'b', 'o3'
|
||||
union all select 2, '2025-03-01', 'colposcopia', null, 'n', 'c3'
|
||||
union all select 3, '2025-04-01', 'colposcopia', null, 'n', 'c4'
|
||||
union all select 3, '2025-04-01', 'orden_biopsia', null, 'b', 'o4'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
union all select 2, '2025-03-01', 'n', 'c3', '2025-03-01', 0
|
||||
union all select 3, '2025-04-01', 'n', 'c4', '2025-04-01', 1
|
||||
|
||||
- name: visits_follow_the_result_and_stop_at_the_next_colposcopy
|
||||
description: >
|
||||
Pins down: patient 1's sample on the colposcopy's day and the one before her result date aren't visits; the
|
||||
two after it are visits 1 and 2; the one after her second colposcopy is not a visit. Fails if visits start
|
||||
before the result is known or continue after a re-referral to colposcopy.
|
||||
model: cacu_post_colposcopy_visits
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha, 'colposcopia' as tipo, 'n' as fuente_tabla, 'c1' as fuente_id
|
||||
union all select 1, '2025-01-10', 'citologia', 'm', 'a'
|
||||
union all select 1, '2025-01-20', 'citologia', 'm', 'b'
|
||||
union all select 1, '2025-07-01', 'citologia', 'm', 'c'
|
||||
union all select 1, '2026-01-15', 'citologia', 'm', 'd'
|
||||
union all select 1, '2026-03-01', 'colposcopia', 'n', 'c2'
|
||||
union all select 1, '2026-09-01', 'citologia', 'm', 'e'
|
||||
- input: ref('cacu_post_colposcopy_episode')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha, 'm' as fuente_tabla, 'c' as fuente_id, '2025-01-10' as fecha_colposcopia,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado, 1 as numero
|
||||
union all select 1, '2026-01-15', 'm', 'd', '2025-01-10', '2025-01-31', 0, 2
|
||||
|
||||
- name: visit_1_index_is_the_first_visit_in_the_window
|
||||
description: >
|
||||
Pins down: patient 1's index is her visit 1; patient 2's visit 1 falls after the recruitment window, so she has
|
||||
no index even though her visit 2 would. Fails if the cohort of visit 1 takes another visit or ignores the window.
|
||||
model: cacu_post_colposcopy_v1_index_date
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_visits')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha, 'm' as fuente_tabla, 'c' as fuente_id, '2025-01-10' as fecha_colposcopia,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado, 1 as numero
|
||||
union all select 1, '2025-12-01', 'm', 'd', '2025-01-10', '2025-01-31', 0, 2
|
||||
union all select 2, '2026-02-01', 'm', 'f', '2025-06-01', '2025-06-01', 0, 1
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha_indice, 'm' as indice_fuente_tabla, 'c' as indice_fuente_id,
|
||||
'2025-01-10' as fecha_colposcopia, '2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
|
||||
- name: visit_0_index_is_the_colposcopy_result
|
||||
description: >
|
||||
Pins down: the cohort of visit 0 is indexed at the date the colposcopy's result is known, in the window.
|
||||
Fails if it takes the colposcopy's date when a biopsy was reported later.
|
||||
model: cacu_post_colposcopy_v0_index_date
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_episode')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
union all select 2, '2024-12-20', 'n', 'c2', '2024-12-30', 0
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-31' as fecha_indice, 'n' as indice_fuente_tabla, 'c1' as indice_fuente_id,
|
||||
'2025-01-10' as fecha_colposcopia, '2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
|
||||
- name: sin_cotest_needs_hpv_and_cytology_of_the_index_sample
|
||||
description: >
|
||||
Pins down: patient 1's index sample has an HPV and a Bethesda result, so she stays; patient 2's has only HPV and
|
||||
patient 3's only cytology, so both are flagged; patient 4's HPV belongs to another sample, so she is flagged.
|
||||
Fails if a result of another sample, or either result alone, counts as a cotest.
|
||||
model: cacu_post_colposcopy_v1_excl_sin_cotest
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_v1_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha_indice, 'm' as indice_fuente_tabla, 'a' as indice_fuente_id
|
||||
union all select 2, '2025-07-01', 'm', 'b'
|
||||
union all select 3, '2025-07-01', 'm', 'c'
|
||||
union all select 4, '2025-07-01', 'm', 'd'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-10' as fecha, 'vph' as tipo, 'NEGATIVO' as valor_codigo, 'm' as fuente_tabla, 'a' as fuente_id
|
||||
union all select 1, '2025-07-12', 'bethesda', 'NORMAL', 'm', 'a'
|
||||
union all select 2, '2025-07-10', 'vph', 'POSITIVO', 'm', 'b'
|
||||
union all select 3, '2025-07-12', 'bethesda', 'ASC-US', 'm', 'c'
|
||||
union all select 4, '2025-07-12', 'bethesda', 'NORMAL', 'm', 'd'
|
||||
union all select 4, '2025-03-10', 'vph', 'POSITIVO', 'm', 'z'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 2 as pac_id union all select 3 union all select 4
|
||||
|
||||
- name: cin2_counts_up_to_the_index_date
|
||||
description: >
|
||||
Pins down: a CIN2+ biopsy reported on the index date (visit 0: the colposcopy found it) excludes patient 1;
|
||||
patient 2's LIEAG comes after her index, so she stays. Fails if `cin2_hasta_el_indice` stops including the
|
||||
index date or reads biopsies after it.
|
||||
model: cacu_post_colposcopy_v0_excl_cin2_hasta_el_indice
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_v0_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-31' as fecha_indice union all select 2, '2025-01-31'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-31' as fecha, 'biopsia' as tipo, 'LIEAG' as valor_codigo
|
||||
union all select 2, '2025-08-01', 'biopsia', 'LIEAG'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id
|
||||
|
||||
- name: histerectomia_reads_the_configured_icd10
|
||||
description: >
|
||||
Pins down: patient 1's note with Z907 before her index excludes her; patient 2's note has another code and
|
||||
patient 3's Z907 comes after her index, so both stay. Fails if the rule ignores `hysterectomy_cie` or the date.
|
||||
model: cacu_post_colposcopy_v1_excl_histerectomia
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_v1_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha_indice union all select 2, '2025-07-01' union all select 3, '2025-07-01'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2024-05-01' as fecha, 'nota_medica' as tipo, 'Z907' as valor_codigo
|
||||
union all select 2, '2024-05-01', 'nota_medica', 'N871'
|
||||
union all select 3, '2025-09-01', 'nota_medica', 'Z907'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id
|
||||
|
||||
- name: sin_referencia_looks_back_from_the_colposcopy
|
||||
description: >
|
||||
Pins down: patient 1's HPV result 100 days before her colposcopy is her referral, so she stays. Patient 2's
|
||||
only result is 400 days before (past the lookback) and patient 3's is after the colposcopy, so both are
|
||||
flagged. Fails if the lookback, its direction or the result types change.
|
||||
model: cacu_post_colposcopy_v1_excl_sin_referencia
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_v1_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-12-01' as fecha_colposcopia union all select 2, '2025-12-01'
|
||||
union all select 3, '2025-12-01'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-08-23' as fecha, 'vph' as tipo, 'POSITIVO' as valor_codigo
|
||||
union all select 2, '2024-10-27', 'bethesda', 'ASC-US'
|
||||
union all select 3, '2025-12-20', 'bethesda', 'LIEBG'
|
||||
- input: source('silver', 'dim_fecha')
|
||||
format: sql
|
||||
rows: |
|
||||
select '2025-12-01' as fecha, 400 as dia_num union all select '2025-08-23', 300
|
||||
union all select '2024-10-27', 0 union all select '2025-12-20', 419
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 2 as pac_id union all select 3
|
||||
@@ -0,0 +1,40 @@
|
||||
{#
|
||||
The patient's first colposcopy and when its result is known: one row per patient with a colposcopy up to the
|
||||
cut-off. Only the first one opens the post-colposcopy sequence (Cheung et al. 2020: referred to colposcopy for the
|
||||
first time). Its biopsies are the orders on the colposcopy's day (a reported biopsy shares its order's source row).
|
||||
|
||||
- `fecha_resultado`: the last report of those biopsies; with no biopsy ordered, the colposcopy's own date.
|
||||
PROVISIONAL: a colposcopy without a biopsy order is taken as below CIN2 (normal impression), which assumes the
|
||||
colposcopic impression misses no CIN2+.
|
||||
- `ordenes_sin_resultado`: orders of the episode with no report up to the cut-off (result unknown).
|
||||
#}
|
||||
{% set p = var('post_colposcopy_cohort') %}
|
||||
with eventos as (
|
||||
select pac_id, fecha, tipo, valor_codigo, fuente_tabla, fuente_id
|
||||
from {{ ref('cacu_linea_de_tiempo') }}
|
||||
where fecha <= '{{ p.cutoff }}'
|
||||
),
|
||||
colposcopias as (
|
||||
select pac_id, fecha, fuente_tabla, fuente_id,
|
||||
row_number() over (partition by pac_id order by fecha, fuente_tabla, fuente_id) as posicion
|
||||
from eventos
|
||||
where tipo = 'colposcopia'
|
||||
),
|
||||
primera as (
|
||||
select pac_id, fecha as fecha_colposcopia, fuente_tabla, fuente_id from colposcopias where posicion = 1
|
||||
),
|
||||
ordenes as (
|
||||
select o.pac_id, o.fuente_tabla, o.fuente_id, max(b.fecha) as fecha_reporte
|
||||
from eventos as o
|
||||
join primera as c on c.pac_id = o.pac_id and o.fecha = c.fecha_colposcopia
|
||||
left join eventos as b
|
||||
on b.tipo = 'biopsia' and b.pac_id = o.pac_id and b.fuente_tabla = o.fuente_tabla and b.fuente_id = o.fuente_id
|
||||
where o.tipo = 'orden_biopsia'
|
||||
group by o.pac_id, o.fuente_tabla, o.fuente_id
|
||||
)
|
||||
select
|
||||
c.pac_id, c.fecha_colposcopia, c.fuente_tabla, c.fuente_id,
|
||||
coalesce((select max(o.fecha_reporte) from ordenes as o where o.pac_id = c.pac_id), c.fecha_colposcopia)
|
||||
as fecha_resultado,
|
||||
(select count(*) from ordenes as o where o.pac_id = c.pac_id and o.fecha_reporte is null) as ordenes_sin_resultado
|
||||
from primera as c
|
||||
@@ -0,0 +1,31 @@
|
||||
{#
|
||||
The surveillance visits after the first colposcopy, numbered 1, 2, … per patient: every cytology sample (an HPV
|
||||
result shares its sample's source row) after the colposcopy's result is known and before any later colposcopy,
|
||||
which closes the sequence (a re-referral; Cheung et al. 2020 model only the first). The post-colposcopy cohort of
|
||||
visit k takes visit k as its index (`cacu_post_colposcopy_index`).
|
||||
#}
|
||||
{% set p = var('post_colposcopy_cohort') %}
|
||||
with eventos as (
|
||||
select pac_id, fecha, tipo, fuente_tabla, fuente_id
|
||||
from {{ ref('cacu_linea_de_tiempo') }}
|
||||
where fecha <= '{{ p.cutoff }}'
|
||||
),
|
||||
episodio as (
|
||||
select * from {{ ref('cacu_post_colposcopy_episode') }}
|
||||
),
|
||||
cierre as (
|
||||
select ep.pac_id, min(e.fecha) as fecha
|
||||
from episodio as ep
|
||||
join eventos as e on e.pac_id = ep.pac_id and e.tipo = 'colposcopia' and e.fecha > ep.fecha_resultado
|
||||
group by ep.pac_id
|
||||
)
|
||||
select
|
||||
t.pac_id, t.fecha, t.fuente_tabla, t.fuente_id,
|
||||
ep.fecha_colposcopia, ep.fecha_resultado, ep.ordenes_sin_resultado,
|
||||
row_number() over (partition by t.pac_id order by t.fecha, t.fuente_id) as numero
|
||||
from eventos as t
|
||||
join episodio as ep on ep.pac_id = t.pac_id
|
||||
left join cierre on cierre.pac_id = t.pac_id
|
||||
where t.tipo = 'citologia'
|
||||
and t.fecha > ep.fecha_resultado
|
||||
and (cierre.fecha is null or t.fecha < cierre.fecha)
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
version: 2
|
||||
|
||||
# Post-colposcopy cohort of visit 0 (macros/cacu_post_colposcopy.sql). Parameters: the `post_colposcopy_cohort` var.
|
||||
models:
|
||||
- name: cacu_post_colposcopy_v0_population
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cacu/cohorte_post_colposcopia_visita_0
|
||||
kind: population
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.2.0"
|
||||
cutoff: "{{ var('post_colposcopy_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('post_colposcopy_cohort') | tojson }}"
|
||||
- name: cacu_post_colposcopy_v0_index_date
|
||||
description: "The colposcopy's result (below CIN2): the last report of the biopsies ordered at the patient's first colposcopy, or the colposcopy itself if none was ordered, if it falls in the recruitment window."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: index}}
|
||||
- name: cacu_post_colposcopy_v0_excl_biopsia_sin_resultado
|
||||
description: "A biopsy ordered at the colposcopy has no report up to the cut-off: the colposcopy's result is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: biopsia_sin_resultado, order: 1}}
|
||||
- name: cacu_post_colposcopy_v0_excl_cin2_hasta_el_indice
|
||||
description: "A biopsy with the outcome up to the index date: the colposcopy found CIN2+, or it came before."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: cin2_hasta_el_indice, order: 2}}
|
||||
- name: cacu_post_colposcopy_v0_excl_antecedente_cacu
|
||||
description: "A note with a cervical cancer ICD-10 (antecedente) up to the index date: a known history of CIN2+."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: antecedente_cacu, order: 3}}
|
||||
- name: cacu_post_colposcopy_v0_excl_histerectomia
|
||||
description: "A note with an ICD-10 of hysterectomy_cie up to the index date (Cheung et al. 2020 exclude hysterectomy)."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: histerectomia, order: 4}}
|
||||
- name: cacu_post_colposcopy_v0_excl_tratamiento_previo
|
||||
description: "Treated up to the index date: she belongs to the post-treatment cohort."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: tratamiento_previo, order: 5}}
|
||||
- name: cacu_post_colposcopy_v0_excl_sin_referencia
|
||||
description: "No cytology or HPV result in the referral_lookback_days up to the colposcopy: the referral grade is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: sin_referencia, order: 6}}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('antecedente_cacu', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('biopsia_sin_resultado', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('cin2_hasta_el_indice', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('histerectomia', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('sin_referencia', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('tratamiento_previo', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_index(0) }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_population() }}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
version: 2
|
||||
|
||||
# Post-colposcopy cohort of visit 1 (macros/cacu_post_colposcopy.sql). Parameters: the `post_colposcopy_cohort` var.
|
||||
models:
|
||||
- name: cacu_post_colposcopy_v1_population
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cacu/cohorte_post_colposcopia_visita_1
|
||||
kind: population
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.2.0"
|
||||
cutoff: "{{ var('post_colposcopy_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('post_colposcopy_cohort') | tojson }}"
|
||||
- name: cacu_post_colposcopy_v1_index_date
|
||||
description: "The first surveillance visit (cytology sample) after the first colposcopy's result is known, before any later colposcopy, if it falls in the recruitment window."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: index}}
|
||||
- name: cacu_post_colposcopy_v1_excl_biopsia_sin_resultado
|
||||
description: "A biopsy ordered at the colposcopy has no report up to the cut-off: the colposcopy's result is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: biopsia_sin_resultado, order: 1}}
|
||||
- name: cacu_post_colposcopy_v1_excl_cin2_hasta_el_indice
|
||||
description: "A biopsy with the outcome up to the index date: the colposcopy found CIN2+, or it came before."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: cin2_hasta_el_indice, order: 2}}
|
||||
- name: cacu_post_colposcopy_v1_excl_antecedente_cacu
|
||||
description: "A note with a cervical cancer ICD-10 (antecedente) up to the index date: a known history of CIN2+."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: antecedente_cacu, order: 3}}
|
||||
- name: cacu_post_colposcopy_v1_excl_histerectomia
|
||||
description: "A note with an ICD-10 of hysterectomy_cie up to the index date (Cheung et al. 2020 exclude hysterectomy)."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: histerectomia, order: 4}}
|
||||
- name: cacu_post_colposcopy_v1_excl_tratamiento_previo
|
||||
description: "Treated up to the index date: she belongs to the post-treatment cohort."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: tratamiento_previo, order: 5}}
|
||||
- name: cacu_post_colposcopy_v1_excl_sin_referencia
|
||||
description: "No cytology or HPV result in the referral_lookback_days up to the colposcopy: the referral grade is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: sin_referencia, order: 6}}
|
||||
- name: cacu_post_colposcopy_v1_excl_sin_cotest
|
||||
description: "The index sample lacks an HPV result or a cytology result (squamous or glandular): KPNC's current result is a cotest."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: sin_cotest, order: 7}}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('antecedente_cacu', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('biopsia_sin_resultado', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('cin2_hasta_el_indice', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('histerectomia', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('sin_cotest', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('sin_referencia', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('tratamiento_previo', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_index(1) }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_population() }}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user