Compare commits

...

32 Commits

Author SHA1 Message Date
Roberto Treviño Cervantes 9737b5a67f The follow-up list identifies each patient by the platform's pac_id, the key the risk route takes; TEA keeps its salted pseudonym 2026-11-15 05:40:08 -06:00
Roberto Treviño Cervantes 854a2e9c55 The recomputation worker estimates with the models in production and wakes on the marker directory; the scanned test form carries a birth date 2026-11-15 05:37:50 -06:00
Roberto Treviño Cervantes b8045e7481 dbt's manifest compiled at start-up for the deployment's engine; the image carries the dbt environments 2026-11-15 00:47:38 -06:00
Roberto Treviño Cervantes 6dce665d93 Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/kit-exit-integration
# Conflicts:
#	Dockerfile
#	README.md
#	tests/staging/cama.py
#	tests/test_fhir_measures.py
#	tests/test_fhir_tea.py
#	tests/test_orquestacion_oro.py
#	tests/test_orquestacion_plata.py
#	uv.lock
#	webapi/__init__.py
#	webapi/fhir/__init__.py
#	webapi/fhir/measures.py
#	webapi/follow_up/routes.py
#	webapi/imports/schemas/tea/ordenes_estudio.py
#	webapi/metrics.py
#	webapi/orchestration/cycle.py
#	webapi/orchestration/reference/catalogs.py
#	webapi/orchestration/repositories.py
#	webapi/orchestration/silver/cama.py
#	webapi/orchestration/silver/orders_and_notes.py
2026-11-15 00:44:31 -06:00
rockdrigo 461d651805 TEA FHIR: an episode's _include brings its ADOS-2 observation 2026-11-13 17:03:23 -06:00
alberto 790879513b The image compiles dbt's manifest and sets DBT_MANIFEST, so the measure and FHIR routes are served 2026-11-13 15:31:29 -06:00
rockdrigo 73cbf0cfb8 The catalog step seeds each domain's mappings, and a mapping is written only if the function still holds
How: `catalog_rows` turns the TOML's study codes, captions and each value's code, label and aliases into the
`catalogo` system's rows; the `catalogs` step adds the system and the forms with no row yet
(`mapeos_nuevos`). `register` normalizes the form and adds the row through `SourceMappingRepository.add`
with `check_stored`, which runs `check_function` on the stored rows of the same form; captions aren't
checked, since one caption may introduce several results. `ctx.repos.silver.mappings` is the domain's
repository.

Implications: the database keeps every mapping across deploys; a person's change is never overwritten, and
a second code for a form in force is refused before it's written. Loads still read the TOML's aliases.
2026-11-13 15:31:21 -06:00
rockdrigo 64d3d721e3 Source forms as a partial, non-injective function into the catalog's codes, checked on the catalog
How: `reference.source_mapping` keys a mapping by source system, result, normalized form and validity;
`check_function` rejects a form that gives two codes while both mappings are in force, and `resolve` gives
the code in force on a date, or none when nothing or two disagreeing mappings match. The catalog's own
check of spellings (`_claves_de_extraccion`) now runs `check_function` on each result's codes, labels and
aliases.

Implications: the same rule serves the TOML today and any store of mappings with systems and dates; every
catalog passes it.
2026-11-13 15:29:52 -06:00
rockdrigo cea74e1566 uv.lock with models' dependencies on dev
How: `uv lock` after the rebase onto dev, whose models adds the notebook and governance requirements.

Implications: `uv sync` installs what the governance routes import (`models.io.storage.build_file` and the notebook runner).
2026-11-13 15:24:02 -06:00
rockdrigo 113b792a7b The import's catalog matching and commit read the WebApi's catalog, silver batch and table maps; add_resultado moves here
How: `catalog_matching`, `catalog_commit_service` and the imports blueprint import `Catalogo`,
`catalogo_desde_toml`, `ruta_de_catalogo`, `CatalogoInvalido`, `LotePlata`, `valor_de_observacion` and
`tablas_de` from `webapi.orchestration`; the commit writes through `carga_repository.save_load` and
`catalog_repository.sync`. `add_resultado` and its tests come over unchanged from the indicator kit.

Implications: the import path no longer needs the indicator kit, which isn't a dependency.
2026-11-13 15:24:02 -06:00
rockdrigo f183e495fb A timeline stratum read by the event cut-off, and labels for a timeline stratum's values
How: `linea_de_tiempo_al_corte` is `linea_de_tiempo_al_inicio_del_periodo` with what the timeline held by the
question's event cut-off (all of it without one) instead of before the period's start. FHIR's `_label` reads a
timeline stratum's labels from its `valores` entries and `resto_etiqueta`. Tests cover CaMa's tumour stratifiers:
the facts dbt derives, the surrogate subtype's rules, CAMA_BIRADS_CANCER_INVASOR broken down by them, and the
cut-off.

Implications: a patient's characteristic learned after the fact that put her in the period (a cancer's stage or
subtype, written after its biopsy) can stratify a measure, and stays reproducible through the cut-offs. CaMa
publishes eight measures and five strata.
2026-11-13 15:14:46 -06:00
rockdrigo 9775a22c57 CaMa's silver load reads results from the reports' text, mapped by the catalog
How: `silver.extracted.DesdeTexto` turns the catalog's `etiquetas_fuente` and each value's `alias` into
Extraction's field specs and into derived columns of a `DeStaging`. CaMa reads density and lesion size from the
mammography interpretation, histology, grade, receptors, HER2 and Ki-67 from the pathology PDF's text layer (no
OCR at load time), and the clinical stage from the note's texts. `resultados_extraibles` reads and checks the new
keys: captions are a non-empty list, aliases need captions, and no spelling names two values.

Implications: a code comes with the spelling it matched as `valor_fuente`; an unknown spelling is kept as
`valor_fuente` with no code, counted as out of catalog, and becomes a code on the next load once its alias is in
the catalog. Nothing is renamed in the stored data and no table or column changes. The synthetic CaMa staging
gains a mammography text, a pathology PDF and a note with a stage.
2026-11-13 15:14:46 -06:00
alberto 7d5c79f520 TEA: an answer as of a knowledge cut-off reads each child's version known then, and the measures waiting for a validation stay hidden outside FHIR too 2026-11-13 15:14:46 -06:00
edgar e224b8b2aa TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary 2026-11-13 15:14:46 -06:00
edgar 205bc214fa Every stratum value an answer writes is in the stratum-value catalog 2026-11-13 15:14:29 -06:00
edgar 4fc822d5c7 The kit's silver load, reference tables, table maps and follow-up list move into the WebApi; the kit is no longer a dependency 2026-11-13 15:14:29 -06:00
edgar 73b1db1121 English names: orchestration (cycle, context, runner, repositories), its steps, fields and CLI, recomputation, follow_up and reports 2026-11-13 15:13:52 -06:00
edgar ea228da7b4 CaCu's and CaMa's measures answered on request from dbt's semantic layer as FHIR MeasureReports, with the period and both cut-offs in the question; the route is /<domain>/indicadores 2026-11-13 15:13:27 -06:00
alberto e19121bc42 TEA: an order carries its study's report as a PDF through the import 2026-11-13 15:03:02 -06:00
Roberto Treviño Cervantes 8f84253205 updating nlp policies; more robust recognition beyond rules 2026-11-13 11:52:36 -06:00
Roberto Treviño Cervantes ce67de17bc fix governance reqs; allow for sandboxed jupyter notebooks for testing 2026-11-13 11:52:36 -06:00
Roberto Treviño Cervantes e41a2b7127 improve ingestion system to match isssteleon setup 2026-11-13 11:52:36 -06:00
Roberto Treviño Cervantes 59fe94ad97 Parse pasted server addresses and carry SQL columns as document fields 2026-11-12 01:13:34 -06:00
Roberto Treviño Cervantes edd12df144 Merge staging into dev 2026-11-12 01:11:24 -06:00
Roberto Treviño Cervantes 96a29cfb19 import files in columns 2026-11-11 11:09:48 -06:00
Roberto Treviño Cervantes 7d0213eda7 Fold repeated captions before writing catalog-matching observations 2026-11-11 08:33:08 -06:00
Roberto Treviño Cervantes 1710cd5ca2 Merge import files in columns into staging 2026-11-11 07:26:52 -06:00
Roberto Treviño Cervantes 3c28a43cb1 Merge dev into staging 2026-11-11 07:26:52 -06:00
Roberto Treviño Cervantes 21e6533dab import files in columns 2026-11-11 07:19:29 -06:00
edgar b9adedbf6f Merge pull request 'Follow-up list and patient risk routes are always registered; en_dev() is deprecated' (#11) from fix/dev-only-routes into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/11
2026-11-09 11:34:00 -06:00
edgar 0cbe390b25 Follow-up list and patient risk routes are always registered; en_dev() is deprecated 2026-11-09 11:30:28 -06:00
edgar 0f00a975fa Merge pull request 'GET /cacu/pacientes/<pac_id>/riesgo in DEV; uv.lock with models' dependencies' (#10) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/10
2026-11-06 15:05:59 +00:00
63 changed files with 5193 additions and 282 deletions
+23 -1
View File
@@ -1,6 +1,22 @@
# Build context is the repo root (see docker-compose.yml) so the sibling
# packages Core/, Persistance/, Extraction/ and models/
# can be copied.
# can be copied, and Transformation/ compiled.
# dbt's manifest: the measures' definitions and the compiled SQL of their event
# models. The API serves the measures from it and the indicator cycle creates
# the views. The manifest built here is SQLite's, the image's default engine;
# the same environments compile it again at start-up against MySQL/MariaDB,
# PostgreSQL or SQL Server when *_DATABASE_URL points there (docker-entrypoint.sh),
# because those adapters open a connection to compile. dbt-mysql needs an
# older dbt-core, so it gets an environment of its own.
FROM python:3.12-slim AS manifest
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
WORKDIR /app/Transformation
COPY Transformation/ ./
RUN uv sync --group sqlite --group sqlserver --group postgres \
&& UV_PROJECT_ENVIRONMENT=.venv-mysql uv sync --only-group mysql \
&& uv run --no-sync dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect
FROM python:3.12-slim
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary.
@@ -34,6 +50,12 @@ ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true
ENV WEBAPI_REPORT_DIR=/data/reportes
ENV INDICADORES_DIR=/data/indicadores
ENV MLFLOW_DISABLE_AGENT_HINT=1
# Without it the measure routes (/<domain>/indicadores, /<domain>/fhir) aren't
# registered. The entrypoint replaces it with one compiled against the
# deployment's engine when that engine isn't SQLite (webapi.dbt_manifest).
COPY --from=manifest /app/Transformation /app/Transformation
ENV DBT_MANIFEST=/app/Transformation/target/manifest.json
ENV TRANSFORMATION_DIR=/app/Transformation
RUN chmod +x /app/WebApi/docker-entrypoint.sh
+23 -3
View File
@@ -18,13 +18,15 @@ webapi/
│ ├── data.py /data: lectura paginada de cada tabla importable
│ ├── cacu.py, cama.py, tea.py /<dominio>/indicadores
│ ├── reportes.py /reportes: bitácora de importaciones y estado del recálculo
│ └── governance.py /governance: versiones de modelos y cola de OCR
│ └── governance.py /governance: versiones de modelos, notebooks y cola de OCR
├── imports/
│ ├── connectors/ una clase por tipo de fuente (@register_connector)
│ ├── schemas/ un esquema pydantic por tabla destino; registry.py los enlista
│ ├── mapping/ sugerencia de mapeo de columnas
│ ├── services/ validación, combinación de fuentes, enlace de llaves y escritura
│ ├── services/ validación, combinación de fuentes, enlace de llaves, escritura
│ │ y aprendizaje de las correcciones de documentos (review_learning.py)
│ └── audit.py bitácora agregada (sin datos de pacientes)
├── nlp.py python -m webapi.nlp evaluate|train: extracción contra una clave de respuestas
├── indicadores.py rutas de indicadores (del equipo de indicadores)
├── recomputation.py cola y servicio que recalcula indicadores tras cada carga
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
@@ -45,7 +47,7 @@ y una entrada en `imports/schemas/registry.py`.
| `/data/<dominio>.<Tabla>` | Filas de una tabla importable, paginadas (`limit`, `offset`) |
| `/<dominio>/indicadores` | Catálogo de indicadores y, por indicador, `/periodos`, `/datos`, `/metadatos` y `/figuras/<figura>` |
| `/reportes` | `GET /reportes/importaciones` (resumen y últimos intentos), `/importaciones/descarga`, `GET /reportes/indicadores`, `POST /reportes/indicadores/<dominio>/recalcular` |
| `/governance` | Versiones de modelos en MLflow (registro, revisión, promoción, retiro) y cola de revisión de OCR |
| `/governance` | Versiones de modelos en MLflow (registro, revisión, promoción, retiro, descarga de sus archivos), notebooks corridos sobre una cohorte exportada (`/governance/experiments`, `/governance/cohort-files`) y cola de revisión de OCR |
| `/health` | Verificación de vida |
Los errores de la solicitud se responden con `{"error": "..."}` y código 400
@@ -69,6 +71,15 @@ Los errores de la solicitud se responden con `{"error": "..."}` y código 400
| `INDICADORES_INTERVALO_S` | `20` | Cada cuánto revisa la cola |
| `INDICADORES_AL_INICIAR` | `1` | Recalcular los tres dominios al arrancar |
| `PORT`, `WEBAPI_WORKERS`, `WEBAPI_TIMEOUT` | `5000`, `2`, `600` | gunicorn en el contenedor |
| `NOTEBOOK_JOBS_DIR` | sin carpeta | Carpeta compartida con el servicio `notebooks`; con ella los notebooks corren aislados en ese contenedor |
| `NOTEBOOK_EXECUTOR` | `contenedor` con `NOTEBOOK_JOBS_DIR`, si no `local` | Dónde corren los notebooks; `local` es en el propio proceso, sin aislar (desarrollo) |
| `NOTEBOOK_RUNNER_UID` | ninguno | Usuario del contenedor `notebooks`, dueño de cada carpeta de trabajo |
| `NOTEBOOK_JOB_TIMEOUT`, `NOTEBOOK_CELL_TIMEOUT` | `21600`, `1800` | Segundos que espera un notebook completo y una celda |
| `NOTEBOOK_MAX_IMPORT_MB` | `500` | Tope de archivos que se importan de lo que entrenó un notebook |
| `WEBAPI_NOTEBOOK_WORKERS` | `1` | Notebooks a la vez por proceso de la API |
| `EXTRACTION_RANKER` | `auto` | Ranker de extracción de documentos: `auto` (el de producción, si no el último), `produccion` (solo el de producción) o `ninguno` |
| `EXTRACTION_LEARNING` | `1` | `0` deja de aprender de las correcciones hechas al revisar documentos |
| `NOTEBOOK_RENDERER` | `quarto` si está instalado, si no `jupyter` | Con qué se corre y se arma la página |
## Ejecución
@@ -83,6 +94,15 @@ uv run python main.py # http://localhost:5050
uv run python -m webapi.recomputation # recálculo de indicadores, en otra terminal
```
Medir la extracción de documentos contra una clave de respuestas (por documento y
destino, el valor correcto de cada campo revisado; `null` si debe quedar vacío)
y entrenar con ella el ranker del dominio (`Extraction/README.md`):
```bash
uv run python -m webapi.nlp evaluate --documents carpeta/ --key clave.json [--with-values] [--no-ranker]
uv run python -m webapi.nlp train --documents carpeta/ --key clave.json
```
Con Docker, desde la raíz del repositorio: `docker compose up --build`. La
imagen se construye con `WebApi/Dockerfile` (contexto: la raíz, para copiar
los paquetes hermanos); `docker-entrypoint.sh` aplica las migraciones y
+25 -2
View File
@@ -1,6 +1,12 @@
#!/bin/sh
set -e
# The notebook runner shares the image but runs with no network, a read-only
# system and only the jobs folder (models.io.notebook_jobs): it never touches /data.
if [ "$1" = "notebooks" ]; then
exec /app/WebApi/.venv/bin/python -m models notebooks serve
fi
mkdir -p /data
# SQLite won't create a missing parent directory for its database file.
@@ -10,14 +16,31 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER
esac
done
cd /app/WebApi
# dbt's manifest for the deployment's engine: the image's is SQLite's; on
# another engine it's compiled now, against the configured databases, into
# /data (webapi.dbt_manifest prints the path to use, or nothing to keep the
# image's).
if compiled="$(uv run --no-sync python -m webapi.dbt_manifest)"; then
[ -n "$compiled" ] && export DBT_MANIFEST="$compiled"
else
echo "dbt manifest: compilation failed; the measure routes will stay unregistered" >&2
fi
# The live indicator worker (webapi.recomputation) shares the image; the
# API container runs the migrations, so the worker starts after it.
if [ "$1" = "indicadores" ]; then
cd /app/WebApi
exec uv run --no-sync python -m webapi.recomputation
fi
cd /app/WebApi
# One-shot training of the CaCu model on the loaded data (compose profile
# `entrenar`): the trained version goes into production and the worker's next
# cycle estimates with it.
if [ "$1" = "entrenar" ]; then
exec uv run --no-sync python -m models run cacu cin2_logistic --export --train --promote
fi
# --no-sync: the environment was synced at build time; syncing at startup
# would try to reach the package index (and pull dev deps).
for domain in cacu cama tea governance; do
+2 -1
View File
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
dependencies = [
"flask>=3.0",
"persistance",
"models[export]",
"models[notebooks]",
"extraction",
"apache-hamilton>=1.90",
"pandas>=2.0",
@@ -20,6 +20,7 @@ dependencies = [
"gunicorn>=23.0",
"sqlglot>=25.0",
"rapidfuzz>=3.9",
"watchdog>=6.0",
]
[project.optional-dependencies]
+4
View File
@@ -31,6 +31,10 @@ os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postg
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
os.environ.setdefault("INDICADORES_DIR", os.path.join(_STATE_DIR, "indicadores"))
# Extraction ranks by confidence and learns nothing unless a test sets up a
# model registry of its own (test_review_learning.py).
os.environ.setdefault("EXTRACTION_RANKER", "ninguno")
os.environ.setdefault("EXTRACTION_LEARNING", "0")
ANIO = 2025
+43 -1
View File
@@ -20,12 +20,18 @@ reporte y grado, y una solicitada que todavía no lo tiene.
Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
Texts the silver load reads results from (`TEXTOS`, `INFORME_DE_PATOLOGIA`, `DIAGNOSTICO_DE_NOTA`):
H-003's B4A carries density C and a 14 mm lesion, its biopsy a PDF with an invasive ductal carcinoma, grade 2,
ER+ 90 %, PR- 0 %, HER2 3+ and Ki-67 25 %, and its oncology note stage IIA. H-101's first mammography says
density "tipo E", which the catalog doesn't know: it stays as source text, out of catalog.
H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`:
lo único común entre los dos sistemas es `pac_id_hospital`.
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
"""
import io
from datetime import date, timedelta
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
@@ -69,6 +75,39 @@ NOTAS = (
("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta
)
# Index in MASTOGRAFIAS -> the radiologist's interpretation.
TEXTOS = {
0: "Densidad mamaria: tipo E\nSin hallazgos.",
4: "Densidad mamaria: heterogéneamente densas (C).\nNódulo irregular en CSE.\nTamaño de la lesión: 14 mm.",
}
# Index in BIOPSIAS -> the lines of its pathology report, as a PDF with a text layer.
INFORME_DE_PATOLOGIA = {
1: (
"DIAGNÓSTICO: Carcinoma ductal infiltrante",
"Grado histológico: 2 (moderadamente diferenciado)",
"Receptores de estrógeno: Positivo (90%)",
"Receptores de progesterona: Negativo (0%)",
"HER2: 3+",
"Ki-67: 25%",
),
}
# Patient -> the diagnosis text of their note.
DIAGNOSTICO_DE_NOTA = {"H-003": "Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)"}
def pdf_de(lineas) -> bytes:
"""A one-page PDF with these lines as its text layer."""
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
buffer = io.BytesIO()
hoja = canvas.Canvas(buffer, pagesize=letter)
for i, linea in enumerate(lineas):
hoja.drawString(72, 720 - 18 * i, linea)
hoja.save()
return buffer.getvalue()
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
# La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía.
ORDENES = (
@@ -141,11 +180,12 @@ def insertar(sesion: Session) -> None:
mast_calidad_imagen=calidad,
mast_birads=birads,
mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7),
mast_interpretacion=TEXTOS.get(indice),
)
)
sesion.add_all(mastografias)
sesion.flush()
for indice, solicitud, reporte, grado in BIOPSIAS:
for numero, (indice, solicitud, reporte, grado) in enumerate(BIOPSIAS):
mastografia = mastografias[indice]
sesion.add(
BiopsiaMama(
@@ -155,6 +195,7 @@ def insertar(sesion: Session) -> None:
bx_fecha_solicitud=solicitud,
bx_fecha_reporte=reporte,
bx_grado_histologico=grado,
bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[numero]) if numero in INFORME_DE_PATOLOGIA else None,
)
)
sesion.add_all(
@@ -165,6 +206,7 @@ def insertar(sesion: Session) -> None:
nm_fecha=fecha,
nm_cie_codigo=cie,
nm_especialidad=especialidad,
nm_diagnostico_texto=DIAGNOSTICO_DE_NOTA.get(hospital) if especialidad == ONCOLOGIA else None,
)
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
)
+116
View File
@@ -0,0 +1,116 @@
"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata.
dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as
timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the
labels a timeline stratum's values carry into FHIR.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on
2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA.
"""
import os
from dataclasses import replace
from datetime import date
from pathlib import Path
import pytest
from conftest import base_de
from sqlalchemy import text
from webapi.compositions import answer_composition, composition_definitions
from webapi.fhir.measures import _label
from webapi.metrics import Question
URL = "cama/CAMA_BIRADS_CANCER_INVASOR"
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
@pytest.fixture
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
@pytest.fixture
def base(tmp_path, sin_supresion, manifest):
base = base_de("cama", tmp_path)
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
base.motor.dispose()
def answered(base, manifest, period: str, event_cutoff: date | None = None):
d = base.dominio
definition = composition_definitions(manifest)[URL]
return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff),
parameters=d.def_parametro_repository, periods=d.dim_periodo_repository,
history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True)
def stratifiers(base) -> set[str]:
with base.motor.connect() as con:
return set(con.execute(text("select tipo from cama_estratificadores")).scalars())
def test_the_stratifiers_come_from_h003_s_reports(base):
"""Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology
report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in
`vars.cama.estratos` or a timeline `tipo` it reads changes."""
assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"}
def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest):
"""Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to
it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the
category or a stratum's values drift."""
assert answered(base, manifest, "2025-S1").categories == {}
result = answered(base, manifest, "2025-S2")
assert result.categories == {"B4A": 1}
assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}},
"etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}},
"tamano": {"T1": {"B4A": 1}}}
def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest):
"""Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype
(report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's
start (H-003 would have nothing) or ignores the cut-off (she'd have her stage)."""
strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata
assert strata["clasificacion"] == {"HER2": {"B4A": 1}}
assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}}
SUBTIPOS = [
({"her2": "H3"}, "subtipo_her2"),
({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"),
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"),
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"),
({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"),
({"her2": "H0", "ki67_pct": None}, None),
({"her2": "H2"}, None),
]
@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS)
def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo):
"""Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both
receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and
progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's
report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise.
Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes."""
valores = {"receptor_progesterona": "POSITIVO", **cambios}
with base.motor.begin() as con:
for nombre, valor in valores.items():
columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id"
con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"),
{"v": valor, "r": f"biopsia.{nombre}"})
assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set())
def test_a_timeline_stratum_s_values_carry_their_labels():
"""Pins down: FHIR labels a timeline stratum's value from its entry in `valores`, and its `resto` from
`resto_etiqueta`. Fails if `_label` reads labels only from a map."""
spec = {"valores": [{"valor": "II", "etiqueta": "Estadio II", "si": []}], "resto": "SIN_DATO",
"resto_etiqueta": "Sin dato"}
assert (_label(spec, "II"), _label(spec, "SIN_DATO"), _label(spec, "IV")) == ("Estadio II", "Sin dato", None)
+117
View File
@@ -0,0 +1,117 @@
"""`commit_discovered_fields`: writes captions no known field claims
straight into `procedimiento`/`observacion`, tagged apart from every
staging-derived row with `FUENTE_CATALOGO_ABIERTO`. Fails if a known
patient's discovered fields stop landing there, or if an unmatched one
stops growing the catalog instead of being silently dropped.
"""
from datetime import date
import pytest
from sqlmodel import select
from webapi.orchestration.reference import catalogs as catalogos
from webapi.orchestration.tables import tablas_de
from extraction import ExtractedRecord
from extraction.nlp import DiscoveredField, Evidence
from webapi.imports.services.catalog_commit_service import FUENTE_CATALOGO_ABIERTO, commit_discovered_fields
EVIDENCE = Evidence("fila.pdf", 1, "")
def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
return ExtractedRecord(
values={}, sources=[], key=key, discovered=[DiscoveredField(c, v, EVIDENCE) for c, v in pairs]
)
@pytest.fixture
def cacu_catalog(tmp_path, monkeypatch):
"""`add_resultado`/`sync` write real rows and a real file:
kept off the checked-in `cacu.toml` and off any other domain's data."""
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
(tmp_path / "cacu.toml").write_text(
'[citologia]\netiqueta = "Citología cervical"\n\n'
'[citologia.resultados.calidad_muestra]\netiqueta = "Calidad de la muestra"\ntipo_valor = "texto"\n',
encoding="utf-8",
)
return tmp_path / "cacu.toml"
@pytest.fixture
def known_patient(wire_domain):
wire_domain("cacu")
from core.cacu.paciente.model import Paciente
from persistance.cacu import paciente_repository
paciente_repository.create(Paciente(pac_id_hospital="DOC-FB-1", pac_fecha_nacimiento=date(1990, 1, 1)))
return "DOC-FB-1"
def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, known_patient):
result = commit_discovered_fields(
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria")])], proyecto="cacu", estudio_id="citologia"
)
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
from persistance.cacu import carga_repository
with carga_repository.open_session() as sesion:
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
assert observacion.resultado_id == "citologia.calidad_muestra"
assert observacion.valor_texto == "Insatisfactoria"
[procedimiento] = sesion.exec(select(carga_repository.procedimiento)).all()
assert procedimiento.fuente_tabla == FUENTE_CATALOGO_ABIERTO
assert procedimiento.fuente_id == known_patient
def test_an_unmatched_field_is_counted_and_the_catalog_left_untouched(cacu_catalog, known_patient):
"""A caption the catalog doesn't know is counted, not written, and the
catalog file isn't edited: it's versioned with the code. Fails if the
import path mints catalog entries again."""
before = cacu_catalog.read_text(encoding="utf-8")
result = commit_discovered_fields(
[_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia"
)
assert (result.records_written, result.fields_minted, result.fields_unmatched) == (0, 0, 1)
assert cacu_catalog.read_text(encoding="utf-8") == before
from persistance.cacu import carga_repository
with carga_repository.open_session() as sesion:
assert sesion.exec(select(carga_repository.observacion)).all() == []
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
result = commit_discovered_fields(
[_record("NOT-A-PATIENT", [("Calidad de muestra", "x")])], proyecto="cacu", estudio_id="citologia"
)
assert (result.records_written, result.records_without_patient) == (0, 1)
def test_a_record_without_discovered_fields_is_ignored(cacu_catalog, known_patient):
result = commit_discovered_fields([_record(known_patient, [])], proyecto="cacu", estudio_id="citologia")
assert result.records_written == 0
def test_a_repeated_caption_is_folded_not_written_twice(cacu_catalog, known_patient):
"""A static label printed on several pages of the same document (a date,
a signature line) discovers as one `DiscoveredField` per occurrence,
on purpose (`discover_captions`'s docstring). Fails if this stops
folding repeats before writing: `observacion` has one row per
`(procedimiento, resultado_id)`, so a second occurrence of the same
resultado_id raises `IntegrityError` and the whole record's fields —
including the ones that weren't duplicated — are lost."""
result = commit_discovered_fields(
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria"), ("Calidad de muestra", "Satisfactoria")])],
proyecto="cacu",
estudio_id="citologia",
)
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
from persistance.cacu import carga_repository
with carga_repository.open_session() as sesion:
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
assert observacion.resultado_id == "citologia.calidad_muestra"
assert observacion.valor_texto == "Insatisfactoria"
+90
View File
@@ -0,0 +1,90 @@
"""`catalog_matching.match_or_mint`: fails if it stops reusing an existing
catalog field for an OCR caption that's clearly the same thing worded
differently, or if an unmatched caption stops being added to the catalog
and silently drops its value instead.
"""
from datetime import date
import pytest
from webapi.orchestration.reference import catalogs as catalogos
from webapi.orchestration.reference.catalogs import Catalogo
from webapi.orchestration.tables import tablas_de
from extraction.nlp import DiscoveredField, Evidence
from webapi.imports.schemas.catalog_matching import match_or_mint
EVIDENCE = Evidence("fila.pdf", 1, "")
def _field(caption: str, value: str) -> DiscoveredField:
return DiscoveredField(caption, value, EVIDENCE)
@pytest.fixture
def catalogo() -> Catalogo:
tablas = tablas_de("cacu")
return Catalogo(
estudios=[tablas.CatEstudio(estudio_id="citologia", etiqueta="Citología cervical")],
resultados=[
tablas.CatResultado(
resultado_id="citologia.calidad_muestra", estudio_id="citologia",
etiqueta="Calidad de la muestra", tipo_valor="codigo",
),
tablas.CatResultado(
resultado_id="citologia.celulas_glandulares", estudio_id="citologia",
etiqueta="Células glandulares", tipo_valor="texto",
),
],
valores=[
tablas.CatValor(
resultado_id="citologia.calidad_muestra", valor_id="SATISFACTORIO",
etiqueta="Satisfactoria", orden=1, estado="vigente",
),
],
)
@pytest.fixture
def catalogo_toml(tmp_path, monkeypatch):
"""`add_resultado` writes to disk; keep it off the real `cacu.toml`."""
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
(tmp_path / "cacu.toml").write_text("", encoding="utf-8")
return tmp_path / "cacu.toml"
def test_a_worded_differently_caption_reuses_the_existing_resultado(catalogo, catalogo_toml):
[matched] = match_or_mint(
[_field("Calidad de muestra", "SATISFACTORIO")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
)
assert matched.resultado_id == "citologia.calidad_muestra" and not matched.is_new
assert matched.observacion["valor_id"] == "SATISFACTORIO"
assert catalogo_toml.read_text(encoding="utf-8") == "" # nothing minted
def test_an_unmatched_caption_in_a_known_estudio_is_minted_there(catalogo, catalogo_toml):
[matched] = match_or_mint(
[_field("Tipo de fijador", "Formol")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
)
assert matched.is_new and matched.resultado_id.startswith("citologia.")
assert matched.observacion["valor_texto"] == "Formol"
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
assert matched.resultado_id in {r.resultado_id for r in sincronizado.resultados}
def test_an_unmatched_caption_with_no_estudio_falls_back_to_documento_externo(catalogo, catalogo_toml):
[matched] = match_or_mint([_field("Observación suelta", "algo")], proyecto="cacu", catalogo=catalogo)
assert matched.resultado_id == "documento_externo." + matched.resultado_id.split(".", 1)[1]
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
assert "documento_externo" in {e.estudio_id for e in sincronizado.estudios}
def test_the_inferred_tipo_valor_follows_the_value_shape(catalogo, catalogo_toml):
fecha, numero, texto = match_or_mint(
[_field("Fecha de algo", "15/01/2024"), _field("Cuenta de algo", "12.5"), _field("Nota libre", "ninguna")],
proyecto="cacu", catalogo=catalogo, estudio_id="citologia",
)
assert fecha.observacion["valor_fecha"] == date(2024, 1, 15)
assert numero.observacion["valor_numerico"] == 12.5
assert texto.observacion["valor_texto"] == "ninguna"
+77
View File
@@ -0,0 +1,77 @@
"""`add_resultado`: adds a new field to a project's catalog TOML file on
disk, for a caller (`webapi.imports.schemas.catalog_matching`) that found a
field no catalog entry matches closely enough. Each test pins down one
rule of that append; fails if any of them regresses into losing data or
duplicating an entry that's already there.
"""
import pytest
from webapi.orchestration.reference import catalogs as catalogos
@pytest.fixture
def catalogo_file(tmp_path, monkeypatch):
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
def escribir(contenido: str) -> None:
(tmp_path / "prueba.toml").write_text(contenido, encoding="utf-8")
return escribir
def test_a_new_resultado_is_appended_under_its_existing_estudio(catalogo_file):
catalogo_file('[citologia]\netiqueta = "Citología"\n')
resultado_id = catalogos.add_resultado(
"prueba", estudio_id="citologia", nombre="nuevo_campo", etiqueta="Nuevo campo", tipo_valor="texto"
)
assert resultado_id == "citologia.nuevo_campo"
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
assert leido["citologia"]["etiqueta"] == "Citología" # what was already there survives
assert leido["citologia"]["resultados"]["nuevo_campo"] == {"etiqueta": "Nuevo campo", "tipo_valor": "texto"}
def test_a_resultado_of_an_unknown_estudio_also_creates_the_estudio(catalogo_file):
catalogo_file("")
catalogos.add_resultado(
"prueba",
estudio_id="documento_externo",
nombre="campo",
etiqueta="Campo",
tipo_valor="fecha",
estudio_etiqueta="Documento externo",
)
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
assert leido["documento_externo"]["etiqueta"] == "Documento externo"
assert leido["documento_externo"]["resultados"]["campo"]["tipo_valor"] == "fecha"
def test_adding_the_same_resultado_twice_does_not_touch_the_file(catalogo_file):
"""Fails if re-discovering the same field on a later row duplicates it
or rewrites what a human already edited in the file."""
original = '[citologia]\netiqueta = "Citología"\n\n[citologia.resultados.campo]\netiqueta = "Campo"\ntipo_valor = "texto"\n'
catalogo_file(original)
catalogos.add_resultado("prueba", estudio_id="citologia", nombre="campo", etiqueta="Otra cosa", tipo_valor="numero")
assert catalogos.ruta_de_catalogo("prueba").read_text(encoding="utf-8") == original
def test_an_unknown_tipo_valor_is_rejected(catalogo_file):
catalogo_file("")
with pytest.raises(catalogos.CatalogoInvalido):
catalogos.add_resultado("prueba", estudio_id="x", nombre="y", etiqueta="Y", tipo_valor="no_existe")
def test_a_quote_in_a_label_does_not_break_the_file(catalogo_file):
"""Fails if a caption or label read off a document (arbitrary text)
produces TOML the next `catalogo_desde_toml` can't parse."""
catalogo_file("")
catalogos.add_resultado(
"prueba", estudio_id="nota", nombre="campo", etiqueta='Dx: "sospechoso"', tipo_valor="texto"
)
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
assert leido["nota"]["resultados"]["campo"]["etiqueta"] == 'Dx: "sospechoso"'
+53
View File
@@ -0,0 +1,53 @@
"""The dbt target and environment derived from the deployment's database URLs (`webapi.dbt_manifest`).
No dbt runs here: only the mapping the entrypoint relies on to compile the manifest against the right engine.
No fixtures."""
import pytest
from webapi.dbt_manifest import dbt_executable, environment, target_of
URLS_MSSQL = {
"cacu": "mssql+pymssql://usuario:clave@servidor:1433/isss_cacu",
"cama": "mssql+pymssql://usuario:clave@servidor:1433/isss_cama",
"tea": "mssql+pymssql://usuario:clave@servidor:1433/isss_tea",
}
def test_sqlite_urls_keep_the_image_manifest():
"""SQLite URLs give the `sqlite` target, which the entrypoint treats as "keep the image's manifest". Fails if
`target_of` stops recognising SQLite or maps it elsewhere."""
urls = {d: f"sqlite:////data/{d}.db" for d in ("cacu", "cama", "tea")}
assert target_of(urls) == "sqlite"
assert environment(urls, "sqlite")["TEA_DB_PATH"] == "/data/tea.db"
@pytest.mark.parametrize("scheme, target", [("mssql+pymssql", "sqlserver"), ("postgresql+psycopg2", "postgres"),
("mysql+pymysql", "mysql"), ("mariadb+pymysql", "mysql")])
def test_each_engine_maps_to_its_dbt_target(scheme, target):
"""Every engine the platform runs on has a dbt target. Fails if a backend name is dropped from `TARGETS`."""
urls = {d: f"{scheme}://u:p@h:1/{d}" for d in ("cacu", "cama", "tea")}
assert target_of(urls) == target
def test_mixed_engines_are_refused():
"""One manifest serves the three domains, so their databases must share an engine. Fails if `target_of`
silently picks one of several engines."""
urls = {**URLS_MSSQL, "tea": "sqlite:////data/tea.db"}
with pytest.raises(ValueError, match="one engine"):
target_of(urls)
def test_environment_feeds_profiles_yml():
"""The server, port, credentials and each domain's database name reach dbt through the variables
`Transformation/profiles.yml` reads. Fails if a variable name changes on either side."""
env = environment(URLS_MSSQL, "sqlserver")
assert env == {"CACU_DBT_DATABASE": "isss_cacu", "CAMA_DBT_DATABASE": "isss_cama", "TEA_DBT_DATABASE": "isss_tea",
"DBT_HOST": "servidor", "DBT_PORT": "1433", "DBT_USER": "usuario", "DBT_PASSWORD": "clave"}
def test_mysql_has_its_own_environment(tmp_path):
"""dbt-mysql pins an older dbt-core, so the image keeps it in `.venv-mysql`. Fails if the executable lookup
stops distinguishing MySQL."""
assert dbt_executable(tmp_path, "mysql") == tmp_path / ".venv-mysql" / "bin" / "dbt"
assert dbt_executable(tmp_path, "sqlserver") == tmp_path / ".venv" / "bin" / "dbt"
+180
View File
@@ -0,0 +1,180 @@
"""Options that let one document source cope with however its rows are
stored: columns carried through as field values, a column grouping rows
into records, filters that pick which documents feed a target, documents
kept as hex or base64 text, unreadable rows, and queries that a derived
table can't hold as written.
Fixtures: `client` (the app wired to a fresh CaCu database) and
`documents_table`, a SQLite table built per test whose rows carry two
reports of one order, a third report of the same patient under another
order, and an unrelated kind of report.
"""
import base64
import pytest
from sqlalchemy import create_engine, text
from extraction.testing import text_pdf
from webapi.imports.connectors.document import document_bytes
from webapi.imports.connectors.sql import SqlConnector, _without_trailing_order_by
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
@pytest.fixture
def documents_table(tmp_path):
"""Rows 1 and 2 are two reports of order 10 of patient P-1, row 3 is
a report of order 11 of the same patient, and row 4 is a report of a
kind the CaCu cytology target doesn't take. No body prints the
patient id the structured columns hold."""
url = f"sqlite:///{tmp_path / 'docs.db'}"
rows = [
(1, "P-1", 10, "Prueba de VPH\nVPH alto riesgo: POSITIVO"),
(2, "P-1", 10, "Prueba de VPH\nGenotipo 18: DETECTADO"),
(3, "P-1", 11, "Prueba de VPH\nVPH alto riesgo: NEGATIVO"),
(4, "P-1", 12, "Informe de otra especialidad\nSin datos de VPH"),
]
with create_engine(url).begin() as conn:
conn.execute(text("CREATE TABLE docs (row_id INTEGER, patient INTEGER, order_ref INTEGER, body TEXT)"))
for row in rows:
conn.execute(text("INSERT INTO docs VALUES (:a, :b, :c, :d)"), dict(zip("abcd", row)))
return url
def _payload(url: str, **sql) -> dict:
base = {"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"}
return {"sql": {**base, **sql}, "target": "cacu.CitologiaCervical"}
def _extract(client, payload: dict) -> dict:
response = client.post("/imports/sources/document/extract", json=payload)
assert response.status_code == 200, response.get_json()
return response.get_json()
def test_group_column_keeps_orders_apart_and_merges_within_one(client, documents_table):
"""Rows sharing `group_column` become one record; the same patient's
other order stays its own record. Fails if `group_column` stops
reaching `record_keys`."""
body = _extract(
client,
_payload(
documents_table,
fields={"pac_id_hospital": "patient", "ord_numero_hospital": "order_ref"},
group_column="order_ref",
)
| {"exclude_pattern": "otra especialidad"},
)
by_key = {record["key"]: record for record in body["records"]}
assert set(by_key) == {"10", "11"}
assert by_key["10"]["fields"]["cit_vph_genotipo_18"]["value"] == 1
assert by_key["11"]["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
assert by_key["10"]["fields"]["pac_id_hospital"]["value"] == "P-1"
def test_filters_leave_out_other_kinds_of_report_and_say_so(client, documents_table):
"""`include_pattern` keeps only matching documents, matched without
regard to case or accents, and the rest are listed as skipped. Fails
if the filters stop applying or `skipped` stops reporting them."""
body = _extract(
client,
_payload(documents_table, fields={"pac_id_hospital": "patient"}) | {"include_pattern": "prueba de vph"},
)
assert [skipped["document"] for skipped in body["skipped"]] == ["4"]
def test_a_filter_that_matches_nothing_is_an_error(client, documents_table):
"""Filtering out every document is reported instead of returning an
empty import. Fails if `_extract` stops refusing an empty selection."""
response = client.post(
"/imports/sources/document/extract", json=_payload(documents_table) | {"include_pattern": "no aparece"}
)
assert response.status_code == 400
def test_an_invalid_filter_is_a_bad_request(client, documents_table):
"""A filter that isn't a valid regular expression is rejected with a
message naming it. Fails if `_compile_filter` lets `re.error` through."""
response = client.post("/imports/sources/document/extract", json=_payload(documents_table) | {"exclude_pattern": "("})
assert response.status_code == 400 and "exclude_pattern" in response.get_json()["error"]
def test_documents_stored_as_hex_or_base64_text_are_decoded():
"""A PDF kept in a text column as hex (with or without `0x`) or base64
reaches the readers as the PDF itself, and ordinary text stays text.
Fails if `document_bytes` stops recognizing either encoding."""
pdf = text_pdf([["Expediente: X-1"]])
assert document_bytes("0x" + pdf.hex()) == pdf
assert document_bytes(pdf.hex().upper()) == pdf
assert document_bytes(base64.b64encode(pdf).decode()) == pdf
assert document_bytes("Expediente: X-1") == b"Expediente: X-1"
def test_an_unreadable_row_is_skipped_not_fatal(client, tmp_path):
"""One corrupt document among readable ones is listed as skipped while
the rest are extracted. Fails if a single unreadable row aborts the
whole source again."""
url = f"sqlite:///{tmp_path / 'mixed.db'}"
with create_engine(url).begin() as conn:
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body BLOB)"))
conn.execute(text("INSERT INTO docs VALUES (1, :b)"), {"b": b"%PDF-1.4 truncated"})
conn.execute(text("INSERT INTO docs VALUES (2, :b)"), {"b": text_pdf([["Expediente: X-2", "VPH alto riesgo: POSITIVO"]])})
body = _extract(client, _payload(url))
assert [record["key"] for record in body["records"]] == ["X-2"]
assert [skipped["document"] for skipped in body["skipped"]] == ["1"]
def test_repeated_key_column_values_still_name_rows_apart(tmp_path):
"""Two rows with the same `key_column` value get distinct names, so
neither one's fields or pages overwrite the other's. Fails if
`_files_from_sql` stops suffixing repeated names."""
from webapi.imports.connectors.document import _files_from_sql
url = f"sqlite:///{tmp_path / 'r.db'}"
with create_engine(url).begin() as conn:
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body TEXT)"))
conn.execute(text("INSERT INTO docs VALUES (7, 'uno'), (7, 'dos')"))
documents = _files_from_sql({"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"})
assert [name for name, _ in documents.files] == ["7", "7#2"]
@pytest.mark.parametrize(
"query,kept",
[
("SELECT a FROM t ORDER BY a", "SELECT a FROM t"),
("SELECT TOP 5 a FROM t ORDER BY a", None),
("SELECT a FROM t ORDER BY a OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY", None),
("SELECT a, (SELECT TOP 1 b FROM u ORDER BY b) AS x FROM t", None),
("SELECT 'ORDER BY' AS s FROM t ORDER BY s", "SELECT 'ORDER BY' AS s FROM t"),
],
)
def test_an_unlimited_trailing_order_by_is_dropped_before_wrapping(query, kept):
"""SQL Server refuses `ORDER BY` inside a derived table unless TOP or
OFFSET goes with it, so one that only sorts is dropped; one that picks
rows, or sits inside a subquery or a string, stays. Fails if
`_without_trailing_order_by` drops an `ORDER BY` that chooses rows or
keeps one that would make the wrapped query invalid."""
assert _without_trailing_order_by(query, "mssql") == (kept or query)
def test_a_named_instance_or_embedded_port_reaches_the_driver():
"""`host\\instance` leaves the port unset for the server to resolve,
and `host,port` or `host:port` fill it in. Fails if `server_url` stops
parsing addresses or goes back to forcing the default port on a named
instance."""
named = SqlConnector.server_url({"engine": "mssql", "host": "db.example\\INST", "database": "d"})
assert (named.host, named.port) == ("db.example\\INST", None)
comma = SqlConnector.server_url({"engine": "mssql", "host": "db.example,1500", "database": "d"})
assert (comma.host, comma.port) == ("db.example", 1500)
colon = SqlConnector.server_url({"engine": "postgresql", "host": "db.example:6543", "database": "d"})
assert (colon.host, colon.port) == ("db.example", 6543)
+174
View File
@@ -0,0 +1,174 @@
"""`DocumentConnector` reading its documents from a SQL source instead of
uploaded files: one document per row, read from a column that may hold a
PDF (a binary column) or already be plain text, both without a filesystem
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
plain-text column stops reaching the same field extraction a PDF does.
"""
import base64
import pytest
from sqlalchemy import create_engine, text
from extraction.testing import text_pdf
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
REPORT = text_pdf(
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
)
@pytest.fixture
def sqlite_studies_table(tmp_path):
"""A source table with one row per study, its
report in a binary column, plus a plain-text variant of the same
report in another row, both alongside the row's own key column."""
db_path = tmp_path / "estudios.db"
url = f"sqlite:///{db_path}"
engine = create_engine(url)
with engine.begin() as conn:
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
conn.execute(
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
{"id": "ROW-1", "reporte": REPORT},
)
conn.execute(
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
{
"id": "ROW-2",
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
},
)
return url
def _sql_payload(url: str, **overrides) -> dict:
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
body = client.post(
"/imports/sources/document/extract",
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
).get_json()
[first, second] = body["records"]
assert first["key"] == "SQL-0001"
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
"""Fails if a source whose bundle is a plain string (not binary at
all) stops producing fields, since a source's column may not always
be a PDF (`extraction.readers.TextReader`)."""
body = client.post(
"/imports/sources/document/extract",
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
).get_json()
[_, second] = body["records"]
assert second["key"] == "SQL-0002"
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
source = {
"source_type": "document",
"target": "cacu.CitologiaCervical",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
"payload": {"sql": _sql_payload(sqlite_studies_table)},
"label": "estudios",
}
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.cacu import citologia_cervical_repository
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("SQL-")}
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
response = client.post(
"/imports/sources/document/extract",
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
)
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
payload = _sql_payload(sqlite_studies_table)
del payload["column"]
response = client.post(
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
)
assert response.status_code == 400 and "column" in response.get_json()["error"]
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
"""Mixing sources: a field the import schema doesn't name (`Tipo de
fijador`) but the project's catalog does still reaches the silver
layer through the open-catalog path, alongside the recognized fields
`commit_sources` writes as before, when the source asks for it with
`catalog_fallback`. Fails if `/imports/commit` stops wiring that second
path in, or runs it for a source that didn't ask.
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
the module's other tests sharing this `client`'s database."""
from datetime import date
from sqlalchemy import create_engine, text as sa_text
from sqlmodel import select
from webapi.orchestration.reference import catalogs as catalogos
from core.cacu.paciente.model import Paciente
from persistance.cacu import carga_repository, paciente_repository
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
catalog = (
'[citologia]\netiqueta = "Citología cervical"\n\n'
'[citologia.resultados.tipo_de_fijador]\netiqueta = "Tipo de fijador"\ntipo_valor = "texto"\n'
)
(tmp_path / "cacu.toml").write_text(catalog, encoding="utf-8")
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
with create_engine(db_url).begin() as conn:
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
source = {
"source_type": "document",
"target": "cacu.CitologiaCervical",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
"label": "estudios_extra",
}
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
assert body["results"][0]["created"] == 1, body
assert not [r for r in body.get("catalog_fallback", []) if r["label"] == "estudios_extra"]
body = client.post("/imports/commit", json={"sources": [{**source, "catalog_fallback": True}], "on_conflict": "upsert"}).get_json()
[fallback] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
assert (fallback["records_written"], fallback["fields_matched"], fallback["fields_minted"]) == (1, 1, 0)
assert (tmp_path / "cacu.toml").read_text(encoding="utf-8") == catalog
with carga_repository.open_session() as sesion:
[written] = list(
sesion.exec(select(carga_repository.observacion).where(carga_repository.observacion.pac_id.in_(
select(Paciente.pac_id).where(Paciente.pac_id_hospital == "SQL-EXTRA-1")
)))
)
assert written.resultado_id == "citologia.tipo_de_fijador" and written.valor_texto == "Formol"
+178
View File
@@ -0,0 +1,178 @@
"""What this module covers: catalog results read from a staging row's text (`silver.extracted`). The catalog's
`etiquetas_fuente` and `alias` checked when it's read; a report's text, a PDF's text layer and a note turned into
codes, numbers and their sources; a spelling the catalog doesn't know kept as text and turned into a code by a
catalog change alone; and CaMa's load putting them in silver and dbt's timeline.
Fixtures: `catalogo_en`, a copy of CaMa's catalog in `tmp_path` that the catalog functions read instead of Core's;
`cargada`, the CaMa fixture database (`staging/cama.py`: H-003's texts and pathology PDF, H-101's unknown density)
loaded, with dbt's views when `DBT_MANIFEST` is set.
"""
import os
from types import SimpleNamespace
import pytest
from sqlalchemy import text
from staging.cama import INFORME_DE_PATOLOGIA, pdf_de
from webapi.orchestration.reference import catalogs
from webapi.orchestration.reference.catalogs import CatalogoInvalido, catalogo_desde_toml, ruta_de_catalogo
from webapi.orchestration.silver import cama
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.tables import tablas_de
DENSIDAD = """
[mastografia]
etiqueta = "Mastografía"
[mastografia.resultados.densidad]
etiqueta = "Densidad"
tipo_valor = "codigo"
etiquetas_fuente = ["Densidad mamaria"]
valores = [
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C"] },
{ valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D"] },
]
"""
@pytest.fixture
def catalogo_en(tmp_path, monkeypatch):
"""Writes a catalog for `cama` in `tmp_path` and points the catalog functions at it. Returns a writer."""
ruta = tmp_path / "cama.toml"
monkeypatch.setattr(catalogs, "ruta_de_catalogo", lambda proyecto: ruta)
def escribir(contenido: str):
ruta.write_text(contenido, encoding="utf-8")
return ruta
return escribir
@pytest.fixture
def proyecto():
return "cama"
@pytest.fixture
def cargada(base):
pasos = ("catalogs", "load", "event_models") if os.environ.get("DBT_MANIFEST") else ("catalogs", "load")
base.run(*pasos)
return base
def observaciones(base, resultado_prefijo: str) -> dict[str, tuple]:
"""`resultado_id` -> (valor_id, valor_numerico, valor_fuente) of the observations whose result starts so."""
with base.motor.connect() as con:
filas = con.execute(text(
"SELECT resultado_id, valor_id, valor_numerico, valor_fuente FROM observacion_clinica "
"WHERE resultado_id LIKE :p AND (valor_id IS NOT NULL OR valor_numerico IS NOT NULL OR valor_fuente IS NOT NULL)"
), {"p": resultado_prefijo + "%"}).all()
return {f.resultado_id: (f.valor_id, f.valor_numerico, f.valor_fuente) for f in filas}
# --- the catalog ---
def test_the_catalog_lists_cama_s_extractable_results_as_provisional():
"""Pins down: every CaMa result with captions is extractable and marked provisional, and the catalog still
loads with them. Fails if `resultados_extraibles` drops a result or the new keys break `catalogo_desde_toml`."""
extraibles = catalogs.resultados_extraibles("cama")
assert set(extraibles) >= {"mastografia.densidad", "biopsia.her2", "nota_medica.estadio_clinico"}
assert all(e.provisional for e in extraibles.values())
catalogo = catalogo_desde_toml(ruta_de_catalogo("cama"), tablas=tablas_de("cama"))
assert {r.resultado_id for r in catalogo.resultados} >= set(extraibles)
@pytest.mark.parametrize("cambio, error", [
(('alias = ["Tipo D"]', 'alias = ["Tipo C"]'), "se escribe igual"),
(('etiquetas_fuente = ["Densidad mamaria"]', 'etiquetas_fuente = []'), "lista de textos"),
(('etiquetas_fuente = ["Densidad mamaria"]\n', ''), "solo sirven con etiquetas_fuente"),
])
def test_an_ambiguous_or_incomplete_mapping_is_rejected(catalogo_en, cambio, error):
"""Pins down: one spelling on two values, empty captions, or aliases without captions stop the catalog from
loading. Fails if a check is dropped and an alias could turn into either of two codes."""
ruta = catalogo_en(DENSIDAD.replace(*cambio))
with pytest.raises(CatalogoInvalido, match=error):
catalogo_desde_toml(ruta, tablas=tablas_de("cama"))
# --- reading text ---
def test_a_report_s_text_gives_codes_with_their_spelling_and_numbers():
"""Pins down: a caption followed by a known spelling gives its code and that spelling as source; a number
after its caption gives the number. Fails if the catalog's aliases stop reaching Extraction's field specs."""
leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(
mast_interpretacion="Densidad mamaria: heterogéneamente densas (C).\nTamaño de la lesión: 14 mm."))
assert leido == {"mastografia.densidad": ("C", "heterogéneamente densas"), "mastografia.tamano_lesion_mm": (14.0, None)}
def test_an_unknown_spelling_is_kept_as_its_source_without_a_code():
"""Pins down: what follows a caption that matches no alias is kept as source text, with no code. Fails if it's
dropped (it couldn't be found and mapped later) or forced into a code."""
leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E"))
assert leido["mastografia.densidad"] == (None, "tipo E")
def test_a_stage_is_found_in_a_note_without_a_caption():
"""Pins down: a result marked `buscar_en_texto` is found as a mention in narrative text. Fails if the flag
stops reaching `scan_free_text`."""
leido = cama.DE_LA_NOTA.leer(SimpleNamespace(
nm_diagnostico_texto="Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)", nm_pronostico=None))
assert leido["nota_medica.estadio_clinico"] == ("EIIA", "estadio clínico IIA")
def test_a_pathology_pdf_s_text_layer_gives_its_results():
"""Pins down: a PDF's text layer is read without OCR and every result on it comes out. Fails if bytes stop
going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor."""
leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1])))
assert {r: v for r, (v, _) in leido.items()} == {
"biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2",
"biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0,
"biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0,
"biopsia.her2": "H3", "biopsia.ki67_pct": 25.0,
}
def test_no_text_gives_no_values():
"""Pins down: a row without text (or a PDF that can't be read) gives every result empty. Fails if an empty
text or broken bytes raise during a load."""
assert set(cama.DE_LA_NOTA.leer(SimpleNamespace(nm_diagnostico_texto=None, nm_pronostico=None)).values()) == {(None, None)}
assert set(cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=b"not a pdf")).values()) == {(None, None)}
def test_adding_an_alias_maps_the_same_text_on_the_next_read(catalogo_en):
"""Pins down: an unknown spelling becomes a code by adding it to the catalog, with nothing else changed. Fails
if the mapping is cached across catalog reads or lives anywhere but the catalog."""
fila = SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E")
catalogo_en(DENSIDAD)
antes = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila)
catalogo_en(DENSIDAD.replace('alias = ["Tipo D"]', 'alias = ["Tipo D", "Tipo E"]'))
despues = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila)
assert antes["mastografia.densidad"] == (None, "tipo E")
assert despues["mastografia.densidad"] == ("D", "tipo E")
# --- the load ---
def test_the_load_puts_the_extracted_results_in_silver(cargada):
"""Pins down: CaMa's load writes the results read from the interpretation, the pathology PDF and the note, and
an unknown spelling as an out-of-catalog source. Fails if `cama.DESDE_STAGING` stops wiring a `DesdeTexto`."""
with cargada.motor.connect() as con:
densidades = sorted(con.execute(text(
"SELECT coalesce(valor_id, '?') || ':' || valor_fuente FROM observacion_clinica "
"WHERE resultado_id = 'mastografia.densidad' AND valor_fuente IS NOT NULL")).scalars())
assert densidades == ["?:tipo E", "C:heterogéneamente densas"]
assert observaciones(cargada, "biopsia.her2") == {"biopsia.her2": ("H3", None, "3+")}
assert observaciones(cargada, "biopsia.ki67_pct") == {"biopsia.ki67_pct": (None, 25.0, None)}
assert observaciones(cargada, "nota_medica.estadio_clinico") == {
"nota_medica.estadio_clinico": ("EIIA", None, "estadio clínico IIA")}
def test_the_timeline_carries_the_extracted_results(cargada):
"""Pins down: the timeline declares the new results, so H-003's stage, receptors and density are rows of it.
Fails if a source line is missing from `cama_linea_de_tiempo.yml`."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
filas = cargada.ctx.repos.silver.timeline.read()
valores = {(f["tipo"], f["valor_codigo"] or f["valor_numerico"]) for f in filas}
assert {("estadio_clinico", "EIIA"), ("her2", "H3"), ("receptor_estrogeno_pct", 90.0),
("densidad_mamaria", "C"), ("densidad_mamaria", "tipo E")} <= valores
+1 -1
View File
@@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
domain, client = domain_client
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
assert measures["total"] == 7
assert measures["total"] == {"cacu": 7, "cama": 8}[domain]
for item in measures["entry"]:
response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1")
assert response.status_code in (200, 409), response.get_json()
+5 -2
View File
@@ -167,8 +167,9 @@ def test_the_follow_up_filters(client, query, n):
def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
"""Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT,
confirmed diagnosis and study EEG as a DiagnosticReport with its quality observations; no metric observation while
the alterations are hidden. Fails if an included resource drops out or the alterations leak."""
ADOS-2 (the list shows its CSS and module), confirmed diagnosis and study EEG as a DiagnosticReport with its quality
observations; no metric observation while the alterations are hidden. Fails if an included resource drops out or
the alterations leak."""
body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*")
included = resources(body, mode="include")
kinds = {r["resourceType"] for r in included}
@@ -177,6 +178,8 @@ def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
reports = [r for r in included if r["resourceType"] == "DiagnosticReport"]
assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"}
assert all(len(r["result"]) == 5 for r in reports)
ados2 = [r for r in included if r["resourceType"] == "Observation" and r["code"]["coding"][0]["code"] == "ados2"]
assert ados2 and all(any(c["code"]["coding"][0]["code"] == "ados2.css" for c in r["component"]) for r in ados2)
def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch):
+145 -25
View File
@@ -1,8 +1,18 @@
"""Endpoint tests for `/governance/*`."""
"""Endpoint tests for `/governance/*`: model versions and their promotion, downloading what a version's run stored,
notebooks run on a cohort build, and the OCR review queue.
Fixtures: `client`, the app over a CaCu and a governance database with one patient and a SQLite-backed MLflow in a
temporary folder (module scope); `notebooks`, a cohort build's file under a `COHORTS_DIR`, the Jupyter renderer and
notebooks run in the request instead of in the background. `_trained` registers a version the way training does: a run
that records each routine and saves its model.
"""
import io
import json
import os
import tempfile
from datetime import date
import mlflow.pyfunc
import pytest
@@ -81,42 +91,70 @@ def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict:
return response.get_json()
def _upload(client, domain: str, scenario: str, version: str, kind: str = "BALANCE_CLASES", name: str = "smote.json", data: bytes = b"{}"):
files = {"file": (__import__("io").BytesIO(data), name), "kind": kind}
return client.post(f"/governance/model-versions/{domain}/{scenario}/{version}/artifacts", data=files, content_type="multipart/form-data")
class Echo(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
return model_input
def _trained(tag: str, scenario: str, **reports) -> str:
"""A PROD version as training leaves it: every routine recorded and the model saved."""
from models.io.registry import registry
from models.io.tracking import ROUTINE_KINDS, TrainingRun
run = TrainingRun(domain="cacu", scenario=scenario, environment="PROD", cohorte_armado_id=_armado(tag))
for kind in ROUTINE_KINDS:
run.log_routine(kind, {"method": "prueba"})
run.log_model(Echo())
return registry.register_run(run.finish(metrics={"auc": 0.8}), **reports)
REPORTS = {"technical_validation_report_uri": "docs/tecnica.pdf", "clinical_validation_report_uri": "docs/clinica.pdf",
"interpretability_report_uri": "docs/interpretabilidad.html"}
def test_model_version_lifecycle_over_http(client):
first = _register(client, "v1", scenario="lifecycle")
assert first["status"] == "candidata"
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{first['version']}/checks").get_json()
"""A version registered over HTTP carries no routine records or model, so it can't be promoted; trained ones can,
and promoting the second retires the first. Fails if the ML-01a/ML-01b checks start trusting what's declared
over the API, or promotion stops retiring the previous version."""
declared = _register(client, "v0", scenario="lifecycle")
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/checks").get_json()
assert checks["ready"] is False
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01b"]
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote")
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01a", "ML-01b"]
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/promote")
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
uploaded = _upload(client, "cacu", "lifecycle", first["version"])
assert uploaded.status_code == 201
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote").get_json()["status"] == "produccion"
second = _register(client, "v2", scenario="lifecycle", metrics={"auc": 0.86})
_upload(client, "cacu", "lifecycle", second["version"])
client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/promote")
first = _trained("v1", "lifecycle", **REPORTS)
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first}/promote").get_json()["status"] == "produccion"
second = _trained("v2", "lifecycle", **REPORTS)
client.post(f"/governance/model-versions/cacu/lifecycle/{second}/promote")
listed = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "lifecycle"}).get_json()
statuses = {v["version"]: v["status"] for v in listed["model_versions"]}
assert statuses[first["version"]] == "retirada" and statuses[second["version"]] == "produccion"
assert statuses[first] == "retirada" and statuses[second] == "produccion"
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second['version']}/lineage").get_json()
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second}/lineage").get_json()
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
assert lineage["cohorte_armado"]["datos_as_of"] == "2025-12-31"
assert lineage["cohorte_exclusiones"] == [{"orden": 1, "paso": "candidatas", "n": 5}]
assert lineage["artifacts"]
assert lineage["routines"]["MUESTREO"] == {"method": "prueba"}
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/retire").get_json()
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second}/retire").get_json()
assert retired["status"] == "retirada"
def test_a_versions_files_download(client):
"""ML-01b: a routine record downloads as itself, the model folder as a zip, and a path the run doesn't hold is 404.
Fails if the endpoint stops going through `registry.artifact`."""
version = _trained("v-desc", "descargas")
base = f"/governance/model-versions/cacu/descargas/{version}/artifacts"
record = client.get(f"{base}/rutinas/MUESTREO.json")
assert record.status_code == 200 and record.get_json(force=True) == {"method": "prueba"}
assert "attachment" in record.headers["Content-Disposition"]
model = client.get(f"{base}/model")
assert model.status_code == 200 and 'model.zip' in model.headers["Content-Disposition"]
assert client.get(f"{base}/../../mlflow.db").status_code == 404
assert client.get(f"{base}/rutinas/OTRO.json").status_code == 404
def test_reports_can_be_attached_later(client):
version = _register(client, "v3", scenario="reportes", clinical_validation_report_uri=None)
response = client.patch(
@@ -127,11 +165,8 @@ def test_reports_can_be_attached_later(client):
assert client.patch(f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"metrics": "{}"}).status_code == 400
def test_bad_registrations_and_uploads_are_rejected(client):
def test_bad_registrations_are_rejected(client):
assert client.post("/governance/model-versions", json={"domain": "cacu"}).status_code == 400
dev = client.post("/governance/model-versions", json={"domain": "cacu", "scenario": "malas-subidas", "environment": "DEV"}).get_json()
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="NOPE").status_code == 400
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="ONNX_CHECKPOINT", name="m.onnx", data=b"junk").status_code == 400
def test_model_version_not_found(client):
@@ -241,3 +276,88 @@ def test_ocr_correct_rejects_unknown_column(client):
def test_ocr_blob_not_found_for_unknown_row(client):
assert client.get("/governance/ocr/cacu/citologia_cervical/999999/blob").status_code == 404
def _notebook(*sources: str) -> bytes:
cells = [{"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": s} for s in sources]
return json.dumps({"cells": cells, "metadata": {}, "nbformat": 4, "nbformat_minor": 5}).encode()
@pytest.fixture
def notebooks(tmp_path, monkeypatch):
"""Build 4 of dbt's `cacu/cohorte_vigilancia` under `COHORTS_DIR`, the Jupyter renderer, and `submit` running the
notebook before the request answers."""
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from datetime import datetime, timezone
from models.io.contracts import COHORT_SCHEMA
from webapi.blueprints import governance
row = {"pac_id": 1, "fecha_indice": date(2025, 1, 1), "fecha": date(2025, 1, 1),
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "citologiacervical",
"fuente_id": "S1"}
table = pa.Table.from_pandas(pd.DataFrame([row], columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA, preserve_index=False)
path = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "4.parquet"
path.parent.mkdir(parents=True)
metadata = {"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": "4", "datos_as_of": "2025-12-31",
"n_members": "1"}
pq.write_table(table.replace_schema_metadata(metadata), path)
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
monkeypatch.setenv("NOTEBOOK_RENDERER", "jupyter")
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
monkeypatch.setattr(governance, "submit", lambda job, *args: job(*args))
def _run(client, notebook: bytes, *, scenario="exploracion", **fields):
form = {"file": (io.BytesIO(notebook), "analisis.ipynb"), "domain": "cacu", "scenario": scenario,
"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": "4", **fields}
return client.post("/governance/experiments", data=form, content_type="multipart/form-data")
def test_the_builds_a_notebook_can_run_on_are_listed(client, notebooks):
"""Fails if `/cohort-files` stops listing exported builds from their files."""
builds = client.get("/governance/cohort-files", query_string={"domain": "cacu"}).get_json()["builds"]
assert builds == [{"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": 4, "datos_as_of": "2025-12-31",
"n_members": "1"}]
def test_an_uploaded_notebook_runs_on_the_build_and_its_page_is_sandboxed(client, notebooks):
"""The upload answers 202 with the run; the notebook reads the build through `models.notebook`; its page is served
with a sandbox policy and its files download. Fails if the endpoint stops handing the build to the run or serves
the notebook's page as part of the app's origin."""
started = _run(client, _notebook("from models.notebook import experiment\n"
"print('miembros', experiment().cohort().pac_id.nunique())"))
assert started.status_code == 202, started.get_json()
run_id = started.get_json()["run_id"]
run = client.get(f"/governance/experiments/{run_id}").get_json()
assert run["status"] == "terminado" and run["cohort"]["build"] == "4" and run["notebook"] == "analisis"
page = client.get(f"/governance/experiments/{run_id}/page")
assert "miembros 1" in page.get_data(as_text=True) and "sandbox" in page.headers["Content-Security-Policy"]
source = client.get(f"/governance/experiments/{run_id}/artifacts/notebook/analisis.ipynb")
assert source.status_code == 200 and "attachment" in source.headers["Content-Disposition"]
listed = client.get("/governance/experiments", query_string={"domain": "cacu", "scenario": "exploracion"}).get_json()
assert run_id in [r["run_id"] for r in listed["experiments"]]
def test_a_failing_notebook_reports_its_error(client, notebooks):
"""Fails if a notebook whose cell raises is reported as finished or without its error."""
run_id = _run(client, _notebook("raise ValueError('sin datos')")).get_json()["run_id"]
run = client.get(f"/governance/experiments/{run_id}").get_json()
assert run["status"] == "fallido" and "sin datos" in run["error"]
@pytest.mark.parametrize("fields, notebook", [
({"build": "99"}, None),
({"url": "tea/otra"}, None),
({"build": "x"}, None),
({"version": "999"}, None),
({}, b"no es json"),
({}, b'{"cells": [], "nbformat": 3}'),
])
def test_bad_notebook_runs_are_refused(client, notebooks, fields, notebook):
"""A build that isn't exported, a cohort of another domain, an unknown version, or a file that isn't a notebook is
refused before anything runs. Fails if `/experiments` stops checking any of them."""
response = _run(client, notebook or _notebook("1"), **fields)
assert response.status_code in (400, 404)
+9 -5
View File
@@ -76,14 +76,16 @@ def _font(size: int = 34):
return ImageFont.load_default()
def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
"""A scanned-like page with two text blocks at known pixel positions and
no text layer, so only the OCR/region path applies."""
def _build_scanned_form_pdf(id_hospital: str, sexo: str, nacimiento: str = "1980-05-17") -> bytes:
"""A scanned-like page with three text blocks on one line at known pixel
positions and no text layer, so only the OCR/region path applies. The birth
date is there because a patient row is not valid without it."""
img = Image.new("RGB", (_IMG_W, _IMG_H), "white")
draw = ImageDraw.Draw(img)
font = _font()
draw.text((40, 100), id_hospital, fill="black", font=font)
draw.text((400, 100), sexo, fill="black", font=font)
draw.text((560, 100), nacimiento, fill="black", font=font)
buffer = io.BytesIO()
c = canvas.Canvas(buffer, pagesize=letter)
@@ -99,6 +101,7 @@ def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
_ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H)
_SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H)
_NACIMIENTO_BBOX = (540 / _IMG_W, 60 / _IMG_H, 880 / _IMG_W, 180 / _IMG_H)
# ---------------------------------------------------------------------
@@ -229,6 +232,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
regions = [
{"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)},
{"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)},
{"target_field": "pac_fecha_nacimiento", "page_numbers": [1], "bbox": list(_NACIMIENTO_BBOX)},
]
extract_response = client.post(
"/imports/sources/pdf/regions/extract",
@@ -236,13 +240,13 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
)
assert extract_response.status_code == 200
extract_body = extract_response.get_json()
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F"}]
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1980-05-17"}]
assert extract_body["warnings"] == []
source = {
"source_type": "pdf",
"target": "cacu.Paciente",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo", "pac_fecha_nacimiento": "pac_fecha_nacimiento"},
"payload": {
"file_base64": base64.b64encode(pdf_bytes).decode(),
"mode": "regions",
+58
View File
@@ -0,0 +1,58 @@
"""The live estimators the recomputation worker hands the cycle (`webapi.orchestration.estimators`,
`webapi.recomputation`).
Fixtures: `base` (conftest) gives a migrated CaCu database with the synthetic staging; the registry and the live
estimators are stubbed so no MLflow store or model is needed. The stub estimator is the cycle tests' `EstimadorFijo`.
"""
import pytest
from sqlalchemy import text
from webapi.orchestration import estimators
from webapi.recomputation import RecomputationQueue
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
def test_only_cacu_has_a_live_estimator():
"""CaMa and TEA have no registered model, so their cycles estimate nothing. Fails if a domain without a model
gets an estimator that would then fail resolving a version."""
assert estimators.live_estimators("cama") == {}
assert estimators.live_estimators("tea") == {}
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
Fails if `live_estimators` stops catching the registry's `LookupError`."""
from models.io.registry import registry
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
assert estimators.live_estimators("cacu") == {}
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
from models.io.registry import registry
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
live = estimators.live_estimators("cacu")
assert list(live) == [URL]
estimator = live[URL]
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
with pytest.raises(RuntimeError):
estimator.procedencia()
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monkeypatch):
"""After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator.
Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written
as anything but `preliminary`."""
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()})
result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025)
assert result["estado"] == "ok", result
assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"]
with base.motor.connect() as con:
assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo_lote")).scalar_one() == 1
assert con.execute(text("SELECT MIN(estado) FROM evaluacion_riesgo")).scalar_one() == "preliminary"
assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo")).scalar_one() > 0
+284
View File
@@ -0,0 +1,284 @@
"""Derived fields and document columns inside an ordinary mapping: target
fields computed from several source columns (joined, split, picked, read
out of a longer text or translated), files kept in a column of a CSV or
SQL source read for the fields the plain mapping left empty, and the
captions nothing used, as the import report lists them.
Fixtures: `client` (the app wired to a fresh CaCu database). Sources are
built inline: CSV text through `_csv`, SQLite tables under `tmp_path`.
"""
import base64
import pytest
from sqlalchemy import create_engine, text
from extraction.testing import text_pdf
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.mapping.derived import build_derivation, parse_derived
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
def _b64(raw: bytes) -> str:
return base64.b64encode(raw).decode()
def _csv(content: str, **source) -> dict:
return {"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": _b64(content.encode())}, **source}
ROW = {"nombre": " ana maría ", "paterno": "Pérez", "materno": "", "completo": "Ana María Pérez López", "dir": "Calle 5, CP 64000"}
@pytest.mark.parametrize(
"rule,expected",
[
({"op": "concat", "columns": ["nombre", "paterno", "materno"]}, "ana maría Pérez"),
({"op": "concat", "columns": ["paterno", "nombre"], "separator": ", ", "case": "upper"}, "PÉREZ, ANA MARÍA"),
({"op": "template", "template": "{paterno} {materno} / {nombre}"}, "Pérez / ana maría"),
({"op": "split", "column": "completo", "start": 0, "stop": -2}, "Ana María"),
({"op": "split", "column": "completo", "start": -2, "stop": -1}, "Pérez"),
({"op": "coalesce", "columns": ["materno", "paterno"]}, "Pérez"),
({"op": "extract", "column": "dir", "pattern": r"CP\s*(\d{5})", "group": 1}, "64000"),
({"op": "map", "column": "paterno", "values": {"pérez": "P"}}, "P"),
({"op": "map", "column": "nombre", "values": {"x": "y"}, "keep_unmatched": False}, None),
({"op": "column", "column": "paterno"}, "Pérez"),
],
)
def test_each_operation_computes_its_value(rule, expected):
"""Pins what every registered operation returns for one row, blanks
skipped and spaces collapsed. Fails if an operation's semantics change
(`start`/`stop` counting, separators, `case`, unmatched values)."""
assert build_derivation(rule).apply(ROW) == expected
def test_rules_are_checked_before_any_row_is_read():
"""Unknown operations, missing parameters, bad patterns and fields the
target lacks are refused up front. Fails if `parse_derived` lets a
malformed rule through to fail row by row."""
for bad in ({"op": "nope"}, {"op": "concat"}, {"op": "extract", "column": "a", "pattern": "("}, {"op": "split", "column": "a", "case": "x"}):
with pytest.raises(ConnectorError):
build_derivation(bad)
with pytest.raises(ConnectorError):
parse_derived({"no_such_field": "a"}, {"pac_sexo"})
def test_short_forms_name_a_column_or_join_several():
"""A rule given as a column name reads it; a list of columns joins them.
Fails if `rule_from` stops accepting the short forms."""
rules = parse_derived({"a": "paterno", "b": ["nombre", "paterno"]}, {"a", "b"})
assert rules["a"].apply(ROW) == "Pérez" and rules["b"].apply(ROW) == "ana maría Pérez"
def test_derived_fields_reach_validation_and_the_mapped_preview(client):
"""A source whose id is split over two columns and whose sex comes
coded validates cleanly once `derived` joins and translates them, and
`/imports/mapped-preview` shows the rows as they would be written.
Fails if `ImportSource.rows` stops applying `derived`."""
source = _csv(
"serie,numero,sx,cp,nac\nA,001,1,64000,1980-01-02\nB,002,2,64100,1975-03-04\n",
column_mapping={"cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
derived={
"pac_id_hospital": {"op": "concat", "columns": ["serie", "numero"], "separator": "-"},
"pac_sexo": {"op": "map", "column": "sx", "values": {"1": "F", "2": "M"}},
},
)
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
assert [(r["pac_id_hospital"], r["pac_sexo"]) for r in rows] == [("A-001", "F"), ("B-002", "M")]
result = client.post("/imports/validate", json={"source": source}).get_json()
assert result["error_count"] == 0, result["errors"]
def test_a_field_cannot_be_both_mapped_and_derived(client):
"""Fails if a field fed twice (mapping and `derived`) stops being refused."""
source = _csv("a\n1\n", column_mapping={"a": "pac_id_hospital"}, derived={"pac_id_hospital": "a"})
assert client.post("/imports/validate", json={"source": source}).status_code == 400
def test_the_operations_are_listed_for_clients(client):
"""`/imports/derivations` lists every operation with its parameters, so
the import screen builds its forms from the server. Fails if an
operation is registered without being described."""
body = client.get("/imports/derivations").get_json()
ops = {d["op"]: d for d in body["derivations"]}
assert {"column", "concat", "template", "split", "coalesce", "extract", "map"} <= set(ops)
assert [p["name"] for p in ops["split"]["params"]] == ["column", "separator", "start", "stop"]
assert body["cases"] == ["upper", "lower", "title"]
def _documents_table(tmp_path) -> str:
"""Two rows of one order of patient P-7, one with its report as a PDF
and one as base64 text, and a third row with no document."""
url = f"sqlite:///{tmp_path / 'docs.db'}"
report = text_pdf([["VPH alto riesgo: POSITIVO"]])
with create_engine(url).begin() as conn:
conn.execute(text("CREATE TABLE t (pid TEXT, orden INTEGER, archivo BLOB, texto TEXT)"))
conn.execute(text("INSERT INTO t VALUES ('P-7', 5, :f, NULL)"), {"f": report})
conn.execute(
text("INSERT INTO t VALUES ('P-7', 5, NULL, :t)"), {"t": _b64(text_pdf([["Genotipo 16: DETECTADO"]]))}
)
conn.execute(text("INSERT INTO t VALUES ('P-8', 6, NULL, NULL)"))
return url
def _sql_source(url: str, **extra) -> dict:
return {
"source_type": "sql",
"target": "cacu.CitologiaCervical",
"payload": {"connection_string": url, "table": "t"},
"column_mapping": {"pid": "pac_id_hospital", "orden": "ord_numero_hospital"},
**extra,
}
def test_a_sql_preview_flags_the_columns_that_hold_documents(client, tmp_path):
"""Binary files and files written as base64 text are both flagged;
plain values aren't. Fails if `document_columns` stops reaching the
preview."""
url = _documents_table(tmp_path)
body = client.post("/imports/sources/sql/preview", json={"connection_string": url, "table": "t"}).get_json()
assert set(body["document_columns"]) == {"archivo", "texto"}
def test_document_columns_fill_what_the_mapping_leaves_empty(client, tmp_path):
"""The mapped id and order are kept; the documents of both rows of the
order add the fields they print; a row without documents passes
through mapped. Fails if `documents` stops reading cells of an
ordinary mapping, or loses the rows that have none."""
source = _sql_source(_documents_table(tmp_path), documents={"columns": ["archivo", "texto"], "group_by": "orden"})
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
by_patient = {row["pac_id_hospital"]: row for row in rows}
assert by_patient["P-7"]["ord_numero_hospital"] == 5
assert by_patient["P-7"]["cit_vph_resultado"] == "POSITIVO"
assert by_patient["P-7"]["cit_vph_genotipo_16"] == 1
assert by_patient["P-8"]["ord_numero_hospital"] == 6
def test_documents_of_a_mapping_can_be_reviewed_and_committed(client, tmp_path):
"""`/imports/sources/document/extract` with `{source}` reviews the same
records the commit writes, with the record's pages in `file_field`.
Fails if the review and the commit read document columns differently."""
source = _sql_source(
_documents_table(tmp_path),
documents={"columns": "archivo", "group_by": "orden", "file_field": "cit_pdf_blob"},
label="t",
)
report = client.post("/imports/sources/document/extract", json={"source": source}).get_json()
[record] = report["records"]
assert record["fields"]["pac_id_hospital"]["method"] == "columna_fuente"
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.cacu import citologia_cervical_repository
stored = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100)}
assert stored["P-7"].cit_vph_resultado == "POSITIVO"
assert stored["P-7"].cit_pdf_blob.startswith(b"%PDF")
def test_a_csv_column_of_base64_documents_is_read_like_a_sql_one(client):
"""Document columns are not tied to SQL: a CSV whose column carries
base64 PDFs feeds the same extraction. Fails if `documents` only works
for one kind of source."""
report = _b64(text_pdf([["VPH alto riesgo: NEGATIVO"]]))
source = _csv(
f"exp,doc\nC-1,{report}\n",
target="cacu.CitologiaCervical",
column_mapping={"exp": "pac_id_hospital"},
documents={"columns": "doc"},
)
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
assert row["pac_id_hospital"] == "C-1" and row["cit_vph_resultado"] == "NEGATIVO"
def _id_and_file_table(tmp_path) -> str:
"""Each row has only an id and a file; every other value is printed
in the file under captions no target field knows."""
url = f"sqlite:///{tmp_path / 'files.db'}"
report = text_pdf([["Tipo de persona: Mujer", "Domicilio actual: Calle 5, C.P. 64000", "Nacida el: 02/01/1980"]])
with create_engine(url).begin() as conn:
conn.execute(text("CREATE TABLE t (pid TEXT, archivo BLOB)"))
conn.execute(text("INSERT INTO t VALUES ('Q-1', :f)"), {"f": report})
return url
def _paciente_from_file(url: str, **extra) -> dict:
return {
"source_type": "sql",
"target": "cacu.Paciente",
"payload": {"connection_string": url, "table": "t"},
"documents": {"columns": "archivo"},
**extra,
}
def test_captions_printed_in_documents_are_offered_as_columns(client, tmp_path):
"""`/imports/sources/document/columns` lists the source's own columns
and every caption its documents print, with their values. Fails if
discovered captions stop becoming columns of the source."""
body = client.post(
"/imports/sources/document/columns", json={"source": _paciente_from_file(_id_and_file_table(tmp_path))}
).get_json()
names = [column["name"] for column in body["columns"]]
assert {"pid", "Tipo de persona", "Domicilio actual", "Nacida el"} <= set(names)
[row] = body["sample_rows"]
assert row["Tipo de persona"] == "Mujer"
def test_mapping_and_rules_reach_what_the_documents_print(client, tmp_path):
"""A caption maps onto a field like a column does, and derived rules
translate or cut values read from the page. Fails if the mapping and
`derived` stop running over the record's document values."""
source = _paciente_from_file(
_id_and_file_table(tmp_path),
column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"},
derived={
"pac_sexo": {"op": "map", "column": "Tipo de persona", "values": {"mujer": "F", "hombre": "M"}},
"pac_codigo_postal": {"op": "extract", "column": "Domicilio actual", "pattern": r"\d{5}"},
},
)
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
assert (row["pac_id_hospital"], row["pac_sexo"], row["pac_codigo_postal"]) == ("Q-1", "F", "64000")
assert row["pac_fecha_nacimiento"] == "02/01/1980"
result = client.post("/imports/validate", json={"source": source}).get_json()
assert result["error_count"] == 0, result["errors"]
def _last_report() -> dict:
from webapi.imports.audit import default_sink
return default_sink().read()[-1]
def test_the_import_report_lists_unused_captions_never_their_values(client, tmp_path, monkeypatch):
"""Captions the documents print that nothing in the import used are
listed with how many records print them, and none of their values
reaches the report. Below the minimum count they are only counted.
Fails if `unused_captions` stops reaching the audit, lists a caption
the mapping uses, or lets a value through."""
import json
source = _paciente_from_file(
_id_and_file_table(tmp_path), column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"}
)
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "1")
client.post("/imports/validate", json={"source": source})
report = _last_report()["fuentes"][0]
assert report["etiquetas_sin_usar"] == {"Tipo de persona": 1, "Domicilio actual": 1}
text = json.dumps(_last_report(), ensure_ascii=False)
assert "Mujer" not in text and "64000" not in text and "02/01/1980" not in text
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "2")
client.post("/imports/validate", json={"source": source})
report = _last_report()["fuentes"][0]
assert report["etiquetas_sin_usar"] == {} and report["etiquetas_sin_usar_poco_frecuentes"] == 2
+38
View File
@@ -348,3 +348,41 @@ def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
assert "nódulo circunscrito" in row.mast_interpretacion
assert row.mast_dicom_blob.startswith(b"\x89PNG")
def test_a_tea_order_keeps_the_pdf_its_sql_source_carries(client, tmp_path):
"""Pins down: `ord_pdf_blob` travels with the order from a SQL source into `ordenes_estudio`, byte for
byte, and an order without a file stays without one. The source is a SQLite file in `tmp_path` holding a
two-row `ordenes_estudio`. Fails if the import schema drops the field or the commit rewrites the bytes."""
report = text_pdf([["EVALUACION PSICOLOGICA", "ADOS-2 Modulo 2"]])
url = f"sqlite:///{tmp_path / 'hospital.db'}"
table = sa.Table(
"ordenes_estudio", sa.MetaData(),
sa.Column("ord_id", sa.String(36), primary_key=True),
sa.Column("ord_id_hospital", sa.String(64)),
sa.Column("ord_tipo_estudio", sa.Text),
sa.Column("ord_pdf_blob", sa.LargeBinary),
)
engine = sa.create_engine(url)
table.create(engine)
with engine.begin() as connection:
connection.execute(sa.insert(table), [
{"ord_id": "ord-pdf-1", "ord_id_hospital": "ORD-PDF-1", "ord_tipo_estudio": "ADOS2", "ord_pdf_blob": report},
{"ord_id": "ord-pdf-2", "ord_id_hospital": "ORD-PDF-2", "ord_tipo_estudio": "EEG", "ord_pdf_blob": None},
])
engine.dispose()
source = {
"source_type": "sql",
"target": "tea.OrdenesEstudio",
"column_mapping": {column.name: column.name for column in table.columns},
"payload": {"connection_string": url, "table": "ordenes_estudio"},
}
result = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"}).get_json()["results"][0]
assert (result["created"], result["rejected"]) == (2, 0), result
from persistance.tea import ordenes_estudio_repository
assert ordenes_estudio_repository.get("ord-pdf-1").ord_pdf_blob == report
assert ordenes_estudio_repository.get("ord-pdf-2").ord_pdf_blob is None
+4 -4
View File
@@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"]
# CaCu: three strata and its seven measures; CaMa: its seven measures, without strata; TEA: the age group and its
# ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 7, "tea": 11}[base.proyecto]
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers and its eight measures;
# TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 13, "tea": 11}[base.proyecto]
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 7, "tea": 10}[base.proyecto]
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 8, "tea": 10}[base.proyecto]
assert base.run("definitions")["definitions"]["borradas"] == 0
+5 -2
View File
@@ -75,7 +75,9 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base):
del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados),
"valores": len(catalogo.valores)}
assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0}
conteos = base.run("catalogs")["catalogs"]
assert conteos.pop("mapeos_nuevos") > 0
assert conteos == {**del_toml, "retirados": 0}
assert filas_del_catalogo(base) == del_toml
@@ -83,7 +85,8 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base):
base.run("catalogs")
antes = filas_del_catalogo(base)
assert base.run("catalogs")["catalogs"]["retirados"] == 0
conteos = base.run("catalogs")["catalogs"]
assert (conteos["retirados"], conteos["mapeos_nuevos"]) == (0, 0)
assert filas_del_catalogo(base) == antes
+8 -20
View File
@@ -2,9 +2,8 @@
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
there.
Fixtures: `client`, a DEV client over the kit's CaCu demonstration database (`conftest.cliente_de`) plus `seeded`:
a surveillance build with two of its patients, one of them with variables and a confirmed batch; `fuera_de_dev`, the
same app without `DEV_REVISION`.
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
"""
from datetime import date, datetime, timezone
@@ -19,8 +18,9 @@ HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado
@pytest.fixture(scope="module")
def client(tmp_path_factory):
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
with pytest.MonkeyPatch.context() as mp:
mp.setenv("DEV_REVISION", "prueba")
mp.delenv("DEV_REVISION", raising=False)
yield from cliente_de("cacu", tmp_path_factory)
@@ -55,17 +55,11 @@ def seeded(client):
return scored, unscored, outside
@pytest.fixture(scope="module")
def fuera_de_dev(tmp_path_factory):
with pytest.MonkeyPatch.context() as mp:
mp.delenv("DEV_REVISION", raising=False)
yield from cliente_de("cacu", tmp_path_factory)
def test_a_scored_member_has_the_contracts_shape(client, seeded):
"""Pins down: the body has `simulado`, `cohorte` and `riesgo` with exactly the contract's fields, the horizons in
ascending order, probabilities in 0..1 and the date as ISO-8601 UTC. Fails if a field is renamed or dropped, which
would break the WebApp's validation."""
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
the WebApp's validation."""
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
body = response.get_json()
@@ -91,9 +85,3 @@ def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
def test_an_unknown_patient_is_404(client, seeded):
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
def test_outside_dev_the_route_does_not_exist(fuera_de_dev):
"""Pins down: without `DEV_REVISION` the route isn't registered. Fails if patient-level risks are served outside
the simulated DEV deployment."""
assert fuera_de_dev.get("/cacu/pacientes/1/riesgo").status_code == 404
+136
View File
@@ -0,0 +1,136 @@
"""Extraction's ranker in WebApi: the document review reports each field's
alternatives, whether the record is about the target and which extraction
version read it; an import whose records a person corrected teaches the
domain's ranker once it is written (`webapi.imports.services.
review_learning`); and `python -m webapi.nlp` scores and trains against an
answer key.
Fixtures: `client` (the app over fresh CaCu, CaMa and TEA databases),
`registry` (a SQLite MLflow per test with its files in `tmp_path`, the
ranker and learning switched on, and learning run synchronously). Documents are made up inline with
`text_pdf`.
"""
import argparse
import base64
import json
from concurrent.futures import Future
import pytest
from extraction.testing import text_pdf
from webapi import nlp
from webapi.imports.services import review_learning
REPORT = text_pdf([["LABORATORIO DE CITOLOGÍA", "Expediente: RV-0001", "No. de orden: 9001", "Prueba de VPH por PCR: POSITIVO",
"Observaciones: se sugiere colposcopía; en caso de VPH negativo repetir en un año."]])
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
wire_domain("cama")
wire_domain("tea")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
class _Now:
"""An executor that runs each task as it is submitted."""
def submit(self, fn, *args):
future = Future()
future.set_result(fn(*args))
return future
@pytest.fixture
def registry(tmp_path, monkeypatch):
import mlflow
from models.io import extraction_ranker
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
mlflow.set_tracking_uri(uri)
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("EXTRACTION_RANKER", "auto")
monkeypatch.setenv("EXTRACTION_LEARNING", "1")
monkeypatch.setattr(extraction_ranker, "_cache", {})
monkeypatch.setattr(review_learning, "_executor", _Now())
from models.io.registry import registry as models_registry
yield models_registry
def _source(**options) -> dict:
return {
"source_type": "document",
"target": "cacu.CitologiaCervical",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital",
"cit_vph_resultado": "cit_vph_resultado"},
"payload": {"files": [{"name": "r.pdf", "file_base64": base64.b64encode(REPORT).decode()}], **options},
"label": "documentos",
}
def test_the_review_reports_alternatives_topic_and_version(client):
"""Fails if the review loses the other readings a person can pick, the
subject check, or the extraction version that will be stored."""
body = client.post("/imports/sources/document/extract", json={"files": _source()["payload"]["files"], "target": "cacu.CitologiaCervical"}).get_json()
[record] = body["records"]
assert record["on_topic"] is True
assert record["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
assert record["fields"]["cit_vph_resultado"]["assertion"] == "afirmado"
assert body["nlp_version"].startswith("extraction ")
assert all(isinstance(options, list) for options in record["alternatives"].values())
def test_a_corrected_import_teaches_the_ranker(client, registry):
"""Committing a document source with a correction registers a new DEV
version of the domain's ranker, learned from that record. Fails if
`commit_sources` stops calling `learn_from_reviews` or the examples are
lost on the way."""
source = _source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})
result = client.post("/imports/commit", json={"sources": [source]}).get_json()
assert result["ok"], result
[version] = registry.versions("cacu", "extraccion")
assert version["status"] == "desarrollo"
from models.io.extraction_ranker import current
assert current("cacu").examples > 0
def test_imports_without_corrections_or_with_learning_off_teach_nothing(client, registry, monkeypatch):
"""Fails if an untouched import, or one made with
`EXTRACTION_LEARNING=0`, creates ranker versions."""
client.post("/imports/commit", json={"sources": [_source()]})
monkeypatch.setenv("EXTRACTION_LEARNING", "0")
client.post("/imports/commit", json={"sources": [_source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})]})
assert registry.versions("cacu", "extraccion") == []
def test_the_command_scores_and_trains_against_an_answer_key(tmp_path, registry):
"""`evaluate` scores per field and overall without printing values
unless asked; `train` estimates on held-out documents, then registers
a version. Fails if the command's key format or outputs change."""
folder = tmp_path / "documentos"
folder.mkdir()
(folder / "a.pdf").write_bytes(REPORT)
(folder / "b.pdf").write_bytes(text_pdf([["Biopsia cervical dirigida", "Diagnóstico:", "NIC I"]]))
key = {
"a.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": "POSITIVO", "pac_id_hospital": "RV-0001"}},
"b.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": None}, "cacu.BiopsiaCervical": {"bx_cin_grado": "LIEBG"}},
}
(tmp_path / "clave.json").write_text(json.dumps(key))
paths = {"documents": str(folder), "key": str(tmp_path / "clave.json")}
evaluated = nlp.command_evaluate(argparse.Namespace(**paths, with_values=False, no_ranker=True))
assert evaluated["global"]["f1"] == 1.0
assert evaluated["errores"] == []
trained = nlp.command_train(argparse.Namespace(**paths))
assert set(trained) == {"sin_ranker", "estimacion_dejando_uno_fuera", "versiones"}
assert trained["versiones"] == {"cacu": "1"}
+17 -14
View File
@@ -1,32 +1,29 @@
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, solo en DEV y siempre simulada.
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, siempre simulada.
Sobre la base de demostración del kit (`conftest.cliente_de`). La lista en sí se prueba en el kit
(`tests/test_lista_seguimiento.py`); aquí, la ruta: cuándo existe, la forma y los códigos de error.
(`tests/test_lista_seguimiento.py`); aquí, la ruta: que existe sin `DEV_REVISION`, la forma y los códigos
de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostración de CaCu.
"""
import pytest
from conftest import cliente_de
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
"dias_toma_diagnostico", "prioridad"} # fmt: skip
@pytest.fixture(scope="module")
def client(tmp_path_factory):
with pytest.MonkeyPatch.context() as mp:
mp.setenv("DEV_REVISION", "prueba")
yield from cliente_de("cacu", tmp_path_factory)
@pytest.fixture(scope="module")
def fuera_de_dev(tmp_path_factory):
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
with pytest.MonkeyPatch.context() as mp:
mp.delenv("DEV_REVISION", raising=False)
yield from cliente_de("cacu", tmp_path_factory)
def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
"""Fija: sin `DEV_REVISION` la ruta existe, con la forma del contrato y `simulado: true`. Falla si la ruta
vuelve a depender de una variable de entorno o cambia un campo."""
response = client.get("/cacu/seguimiento?corte=2025-12-31")
assert response.status_code == 200 and response.mimetype == "application/json"
@@ -34,7 +31,9 @@ def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True
assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"])
assert all(i["prioridad"] is None for i in cuerpo["items"])
assert "pac_id" not in response.get_data(as_text=True)
# The patient key is the platform's `pac_id`, the one the risk route takes; the hospital's id never leaves.
assert all(i["pac_id"].isdigit() and i["id_seudonimo"] == i["pac_id"] for i in cuerpo["items"])
assert "pac_id_hospital" not in response.get_data(as_text=True)
def test_el_pedido_se_respeta(client):
@@ -63,5 +62,9 @@ def test_una_pagina_de_mas_da_404(client):
assert "error" in response.get_json()
def test_fuera_de_dev_la_ruta_no_existe(fuera_de_dev):
assert fuera_de_dev.get("/cacu/seguimiento").status_code == 404
def test_in_dev_esta_obsoleta():
"""Fija: `in_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso."""
from webapi.follow_up.routes import in_dev
with pytest.warns(DeprecationWarning):
in_dev()
+116
View File
@@ -0,0 +1,116 @@
"""What this module covers: source forms as a function into the catalog's codes (`reference.source_mapping`):
many forms to one code, no code for an unknown form, the same form read per source system and per date, and two
codes for one form rejected when they're in force together; every catalog's TOML passing that check; and, in each
domain's database, the catalog step seeding `cat_mapeo` without touching a stored row and `register` refusing a
mapping that breaks the function.
Fixtures: `base` (conftest), each domain's migrated fixture database; the other tests build their rows.
"""
import tomllib
from datetime import date
import pytest
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
from webapi.orchestration.reference.source_mapping import (
CATALOG, SourceForm, ambiguities, check_function, from_result, normalize, register, resolve,
)
HER2 = "biopsia.her2"
LAB_A = [SourceForm("lab_a", HER2, "3+", "H3", None, date(2026, 12, 31)),
SourceForm("lab_a", HER2, "Positivo", "H3", None, date(2026, 12, 31))]
LAB_B = [SourceForm("lab_b", HER2, "Positivo (score 3)", "H3", date(2027, 1, 1)),
SourceForm("lab_b", HER2, "Positivo", "H2", date(2027, 1, 1))]
def test_many_forms_give_one_code_and_an_unknown_form_none():
"""Pins down: the mapping isn't injective and is partial: several spellings, compared without case, accents or
extra spaces, give the same code; a spelling with no mapping gives None. Fails if `normalize` stops folding or
`resolve` invents a code."""
assert {resolve(LAB_A, "lab_a", HER2, f) for f in ("3+", " positivo ", "POSITIVO")} == {"H3"}
assert resolve(LAB_A, "lab_a", HER2, "Equívoco") is None
assert normalize(" Positívo (score 3) ") == "POSITIVO (SCORE 3)"
def test_a_form_is_read_per_source_system_and_per_date():
"""Pins down: "Positivo" is H3 at lab A and H2 at lab B, and a mapping applies only to documents dated within its
validity. Fails if `resolve` ignores the system or the dates, letting one lab's spelling leak into another's."""
rows = LAB_A + LAB_B
assert resolve(rows, "lab_a", HER2, "Positivo", date(2026, 6, 1)) == "H3"
assert resolve(rows, "lab_b", HER2, "Positivo", date(2027, 2, 1)) == "H2"
assert resolve(rows, "lab_b", HER2, "Positivo", date(2026, 6, 1)) is None
assert ambiguities(rows) == []
def test_two_codes_for_one_form_in_force_together_are_rejected():
"""Pins down: a form mapped to two codes with overlapping validity breaks the function: `check_function` names
it and `resolve` gives None rather than either code. Two codes in validities that don't overlap, or the same
code twice, are fine. Fails if the overlap test or the code comparison is dropped."""
clash = SourceForm("lab_b", HER2, "positivo", "H3", date(2027, 6, 1))
with pytest.raises(ValueError, match="se escribe igual para 'H2' y 'H3'"):
check_function(LAB_B + [clash])
assert resolve(LAB_B + [clash], "lab_b", HER2, "Positivo", date(2027, 7, 1)) is None
corrected = [LAB_B[1]._replace(valid_to=date(2027, 5, 31)), clash]
check_function(corrected)
assert resolve(corrected, "lab_b", HER2, "Positivo", date(2027, 7, 1)) == "H3"
check_function(LAB_B + [LAB_B[0]._replace(form="POSITIVO (SCORE 3)")])
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
def test_every_catalog_s_spellings_are_a_function(proyecto):
"""Pins down: in each domain's TOML, every result's codes, labels and aliases map to one value each. Fails when
an edit to a catalog gives one spelling two values."""
estudios = tomllib.loads(ruta_de_catalogo(proyecto).read_text(encoding="utf-8"))
rows = [row for estudio_id, estudio in estudios.items()
for nombre, resultado in estudio.get("resultados", {}).items()
for row in from_result(f"{estudio_id}.{nombre}", resultado)]
check_function(rows)
# --- the stored mappings, in each domain ---
def a_coded_result(base) -> tuple[str, str, str]:
"""A coded result of the domain's catalog with two values: (resultado_id, first valor_id, second valor_id)."""
estudios = tomllib.loads(ruta_de_catalogo(base.proyecto).read_text(encoding="utf-8"))
for estudio_id, estudio in estudios.items():
for nombre, resultado in estudio.get("resultados", {}).items():
valores = resultado.get("valores", ())
if len(valores) >= 2:
return f"{estudio_id}.{nombre}", valores[0]["valor"], valores[1]["valor"]
raise AssertionError("el catálogo no tiene un resultado codificado con dos valores")
def test_the_catalog_step_seeds_the_mappings_and_keeps_what_a_person_changed(base):
"""Pins down: the catalog step adds the catalog's own mappings (each value's code among them) and, run again,
adds nothing and leaves a person's row for a new form as it is. Fails if the step stops seeding or a deploy
replaces stored rows."""
base.run("catalogs")
mappings = base.ctx.repos.silver.mappings
resultado, primero, segundo = a_coded_result(base)
sembradas = mappings.forms(sistema_fuente_id=CATALOG, resultado_id=resultado, clase="valor")
assert {(m.forma, m.valor_id) for m in sembradas} >= {(primero, primero), (segundo, segundo)}
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=" forma del curador ", registrado_por="curador",
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
assert base.run("catalogs")["catalogs"]["mapeos_nuevos"] == 0
[mia] = mappings.forms(forma_normalizada="FORMA DEL CURADOR")
assert (mia.forma, mia.valor_id, mia.registrado_por) == ("forma del curador", segundo, "curador")
def test_register_refuses_a_second_code_for_a_form_in_force(base):
"""Pins down: `register` checks the new row against the stored ones: the catalog's own code of one value can't
be mapped to another value, and a lab's form can, once the first row's validity ends before the second's starts.
Fails if the write path stops running `check_function`."""
base.run("catalogs")
mappings = base.ctx.repos.silver.mappings
resultado, primero, segundo = a_coded_result(base)
with pytest.raises(ValueError, match="se escribe igual"):
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=primero, registrado_por="curador",
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
viejo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="Código de laboratorio",
registrado_por="curador", vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=primero)
mappings.close(viejo.mapeo_id, date(2026, 12, 31))
nuevo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="codigo de LABORATORIO",
registrado_por="curador", vigente_desde=date(2027, 1, 1), resultado_id=resultado, valor_id=segundo)
filas = mappings.forms(forma_normalizada=normalize("Código de laboratorio"))
assert [f.mapeo_id for f in filas] == [viejo.mapeo_id, nuevo.mapeo_id]
Generated
+762 -68
View File
File diff suppressed because it is too large Load Diff
+10 -11
View File
@@ -10,7 +10,7 @@ from webapi.blueprints.data import data_bp
from webapi.blueprints.governance import governance_bp
from webapi.blueprints.imports import imports_bp
from webapi.blueprints.reports import reports_bp
from webapi.follow_up.routes import follow_up_blueprint, in_dev
from webapi.follow_up.routes import follow_up_blueprint
class IsoJSONProvider(DefaultJSONProvider):
@@ -84,18 +84,17 @@ def create_app() -> Flask:
for domain in ("cacu", "cama", "tea"):
repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"])
app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}")
# The same measures in FHIR R4, and TEA's patients only in DEV (simulated data).
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=in_dev()),
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
url_prefix=f"/{domain}/fhir")
# Patient-level follow-up list and individual risk: only in DEV, with simulated data.
if in_dev():
from persistance.db import get_cacu_session
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
# an access rule still to be defined, not an environment variable.
from persistance import cacu as cacu_repositories
from persistance.db import get_cacu_session
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
from persistance import cacu as cacu_repositories
from webapi.patient_risk import patient_risk_blueprint
from webapi.patient_risk import patient_risk_blueprint
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
return app
+106 -12
View File
@@ -1,20 +1,32 @@
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
their promotion, and the OCR extraction jobs with their manual review queue.
their promotion, notebooks run on a cohort build, and the OCR extraction
jobs with their manual review queue.
Versions and artifacts live in MLflow (`models.io.registry`); training runs
elsewhere and registers its result through `POST /model-versions`, naming
the indicator kit cohort build it was trained on (`cohorte_armado_id`).
Notebooks (`models.pipelines.experiment`) run in the background on the build's
file alone and are kept as MLflow runs.
"""
import json
import os
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from pathlib import Path
from urllib.parse import quote
from core.governance.enums import EstatusExtraccion
from core.governance.models import ExtractionRun
from core.ocr import OcrEstatus
from flask import Blueprint, Response, jsonify, request
from models.io.lineage import DOMAINS
from models.io.registry import REPORT_TAGS, PromotionBlocked, registry
from models.io.storage import build_file, cohorts_root, exported_builds
from models.ocr import OCR_JOBS, OcrJob, run_pending_extractions
from models.pipelines import experiment
from persistance.governance import extraction_run_repository
from persistance.repository import Repository
from persistance.settings import settings
governance_bp = Blueprint("governance", __name__)
@@ -108,19 +120,101 @@ def retire_model_version(domain: str, scenario: str, version: str):
return jsonify(registry.describe(domain, scenario, version))
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
def upload_artifact(domain: str, scenario: str, version: str):
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
from core.governance.enums import ArtifactKind
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/artifacts/<path:path>")
def download_artifact(domain: str, scenario: str, version: str, path: str):
"""ML-01b: one file the version's training run stored; a folder (the saved model) as a zip."""
name, data = registry.artifact(domain, scenario, version, path)
return _download(name, data)
# -- notebooks -------------------------------------------------------------------------
def submit(job, *args):
"""Runs a notebook in the background, one at a time per worker by default (`WEBAPI_NOTEBOOK_WORKERS`)."""
return _notebooks.submit(job, *args)
_notebooks = ThreadPoolExecutor(max_workers=int(os.environ.get("WEBAPI_NOTEBOOK_WORKERS", "1")), thread_name_prefix="notebook")
def _cohorts_root(domain: str) -> Path:
if domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
return cohorts_root(getattr(settings, f"{domain}_database_url"))
@governance_bp.get("/cohort-files")
def list_cohort_files():
"""`?domain=`: the domain's cohort builds that have their file, the data a notebook can run on."""
domain = request.args.get("domain", "")
return jsonify({"builds": exported_builds(_cohorts_root(domain), domain)})
@governance_bp.get("/experiments")
def list_experiments():
"""Notebook runs, newest first; `?domain=` and `?domain=&scenario=` narrow them."""
return jsonify({"experiments": experiment.experiments(request.args.get("domain") or None,
request.args.get("scenario") or None)})
@governance_bp.post("/experiments")
def run_experiment():
"""Multipart `file` (a .ipynb), `domain`, `scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`:
runs the notebook on that build's file in the background and answers 202 with the run, still `en_curso`."""
upload = request.files.get("file")
if upload is None:
return jsonify({"error": "falta file"}), 400
kinds = [k.value for k in ArtifactKind]
if request.form.get("kind") not in kinds:
return jsonify({"error": f"kind debe ser uno de {kinds}"}), 400
registry.add_artifact(domain, scenario, version, kind=ArtifactKind(request.form["kind"]), filename=upload.filename or "artefacto", data=upload.read())
return jsonify(registry.describe(domain, scenario, version)), 201
form = request.form
missing = [k for k in ("domain", "scenario", "url", "source", "build") if not form.get(k)]
if upload is None or missing:
return jsonify({"error": f"faltan campos: {(['file'] if upload is None else []) + missing}"}), 400
domain, scenario, version = form["domain"], form["scenario"], form.get("version") or None
url = form["url"]
if url.split("/", 1)[0] != domain:
return jsonify({"error": f"la cohorte {url!r} no es del dominio {domain!r}"}), 400
if not form["build"].isdigit():
return jsonify({"error": "build debe ser un número"}), 400
path = build_file(_cohorts_root(domain), url, form["source"], int(form["build"]))
try:
notebook = experiment.check_notebook(json.loads(upload.read()))
except (UnicodeDecodeError, json.JSONDecodeError):
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
if version:
registry.get(domain, scenario, version)
name = experiment.notebook_name(upload.filename or "notebook")
run_id = experiment.start(notebook, name, path, domain, scenario, version)
submit(experiment.execute, run_id, notebook, name, path, domain, scenario, version)
return jsonify(experiment.describe(run_id)), 202
@governance_bp.get("/experiments/<run_id>")
def get_experiment(run_id: str):
return jsonify(experiment.describe(run_id))
@governance_bp.get("/experiments/<run_id>/page")
def experiment_page(run_id: str):
"""The notebook's rendered page. It's served sandboxed, as an origin of its own, since its scripts are the
notebook's."""
page = experiment.page(run_id)
if page is None:
return jsonify({"error": "el notebook todavía no tiene página"}), 404
response = Response(page, mimetype="text/html")
response.headers["Content-Security-Policy"] = "sandbox allow-scripts allow-popups"
response.headers["X-Content-Type-Options"] = "nosniff"
return response
@governance_bp.get("/experiments/<run_id>/artifacts/<path:path>")
def download_experiment_artifact(run_id: str, path: str):
name, data = experiment.artifact(run_id, path)
return _download(name, data)
def _download(name: str, data: bytes):
response = Response(data, mimetype="application/octet-stream")
response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{quote(name)}"
response.headers["X-Content-Type-Options"] = "nosniff"
return response
# -- OCR ---------------------------------------------------------------------------------
+85 -2
View File
@@ -4,6 +4,7 @@ import json
import logging
from flask import Blueprint, Response, jsonify, request
from sqlalchemy.exc import SQLAlchemyError
from extraction import BBox, ExtractionError
from extraction.readers import reader_for
@@ -11,13 +12,19 @@ from webapi.imports import audit as import_audit
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
from webapi.imports.connectors.base import decode_file
from webapi.imports.connectors.pdf import PdfConnector
from webapi.orchestration.reference.catalogs import CatalogoInvalido
from webapi.imports.connectors.sql import SqlConnector
from webapi.imports.connectors.tabular import FileConnector
from webapi.imports.schemas.registry import ENTITY_REGISTRY
from webapi.imports.services.catalog_commit_service import commit_discovered_fields
from webapi.imports.mapping.derived import CASES, DERIVATIONS
from webapi.imports.services.import_service import (
DatabaseRefused,
ImportRequestError,
ImportSource,
commit_sources,
document_columns_preview,
mapped_sample,
serialize_errors,
validate_source,
)
@@ -27,6 +34,7 @@ from webapi.imports.services.introspection_service import (
document_report,
extract_pdf_regions,
preview_with_suggestions,
suggest_mapping,
)
imports_bp = Blueprint("imports", __name__)
@@ -250,12 +258,17 @@ def pdf_regions_extract():
def document_extract():
"""Reads the documents, splits them into patient records and extracts
the target's fields: `{files: [{name, file_base64}], target,
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?,
include_pattern?, exclude_pattern?}`. `files` may be `sql` instead (a
connection plus `table`/`query` and `DocumentColumns`' options), or the
whole body may be `{source}`, an import source with `documents`.
Each record comes back with per-field confidence and evidence, conflicts
between sources, and the images found on its pages."""
body = _json_body()
if body.get("source"):
return jsonify(document_report(body))
_require(body, "target")
if not body.get("files"):
if not body.get("files") and not body.get("sql"):
raise BadRequest("faltan los archivos")
return jsonify(document_report(body))
@@ -279,6 +292,32 @@ def document_page_image():
# -- validate and load -------------------------------------------------------------------------
@imports_bp.get("/derivations")
def derivations():
"""The operations a source's `derived` fields may use, with their
parameters, so a client can build the form for each."""
return jsonify({"derivations": [cls.describe() for cls in DERIVATIONS.values()], "cases": list(CASES)})
@imports_bp.post("/mapped-preview")
def mapped_preview():
"""`{source, limit?}`: the source's first rows as they would be
written, with its mapping, derived fields and defaults applied."""
body = _json_body()
return jsonify({"rows": mapped_sample(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))})
@imports_bp.post("/sources/document/columns")
def document_columns_of_source():
"""`{source, target?}` for a source with `documents`: its own columns
plus every field and caption its documents print, as a preview the
mapping screen offers like any table's, with suggestions."""
body = _json_body()
preview = document_columns_preview(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))
target = body.get("target") or body["source"].get("target")
return jsonify({**preview, "suggested_mapping": suggest_mapping([c["name"] for c in preview["columns"]], target)})
@imports_bp.post("/validate")
def validate():
source = _require(_json_body(), "source")
@@ -302,6 +341,49 @@ def validate():
)
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
"""For every source that asks for it (`catalog_fallback: true`) and
reads documents, writes the captions no known field claimed but the
project's catalog does know straight into the silver layer
(`catalog_commit_service`). Best-effort: the structured fields already
landed through `commit_sources`, so a failure here is reported, not
raised."""
reports = []
for raw in raw_sources:
if not isinstance(raw, dict) or raw.get("catalog_fallback") is not True:
continue
if raw.get("source_type") != "document" and not raw.get("documents"):
continue
target = raw.get("target") or ""
domain = target.split(".", 1)[0]
if not domain:
continue
payload = {**(raw.get("payload") or {}), "target": target}
try:
if raw.get("documents"):
connector, _, _ = ImportSource.parse(raw).document_connector()
if connector is None:
continue
else:
connector = build_connector("document", payload)
result = commit_discovered_fields(connector.records, proyecto=domain, estudio_id=payload.get("estudio_id"))
except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError, ImportRequestError) as exc:
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
continue
reports.append(
{
"label": raw.get("label"),
"domain": result.proyecto,
"records_written": result.records_written,
"records_without_patient": result.records_without_patient,
"fields_matched": result.fields_matched,
"fields_minted": result.fields_minted,
"fields_unmatched": result.fields_unmatched,
}
)
return reports
@imports_bp.post("/commit")
def commit():
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
@@ -333,6 +415,7 @@ def commit():
"ok": all(r.rejected == 0 for r in results),
"audit_id": audit.id,
"indicadores_en_recalculo": recalculating,
"catalog_fallback": _commit_catalog_fallback(body.get("sources") or []),
"results": [
{
"target": r.target,
+83
View File
@@ -0,0 +1,83 @@
"""dbt's manifest for the deployment's engine.
The measures are served from `manifest.json` (`DBT_MANIFEST`), whose compiled SQL is the dialect of the dbt target it
was compiled with. The image ships SQLite's; on another engine the entrypoint runs this module, which compiles the
project in `TRANSFORMATION_DIR` against the configured databases (the adapters for MySQL, PostgreSQL and SQL Server
open a connection to compile) and prints the path of the manifest to serve. On SQLite it prints nothing: the image's
manifest is the right one.
The three domains must share one engine: one manifest covers every domain's models.
"""
import os
import subprocess
import sys
from pathlib import Path
from sqlalchemy.engine import make_url
DOMAINS = ("cacu", "cama", "tea")
TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"}
def target_of(urls: dict[str, str]) -> str:
"""The dbt target the domains' database URLs share. `ValueError` for an engine dbt has no target for, or when
the domains don't share one engine."""
targets = {domain: TARGETS.get(make_url(url).get_backend_name()) for domain, url in urls.items()}
if unknown := [domain for domain, target in targets.items() if target is None]:
raise ValueError(f"no dbt target for the engine of {', '.join(unknown)}")
if len(set(targets.values())) != 1:
raise ValueError("the domains' databases must be on one engine: one manifest serves the three domains")
return next(iter(targets.values()))
def environment(urls: dict[str, str], target: str) -> dict[str, str]:
"""What `Transformation/profiles.yml` reads: the server and credentials from CaCu's URL (one server for the three
domains), each domain's database name, and on SQLite each domain's file."""
env: dict[str, str] = {}
for domain, url in urls.items():
parsed = make_url(url)
if target == "sqlite":
env[f"{domain.upper()}_DB_PATH"] = parsed.database or f"{domain}.db"
else:
env[f"{domain.upper()}_DBT_DATABASE"] = parsed.database or domain
first = make_url(urls["cacu"])
if target != "sqlite":
env["DBT_HOST"] = first.host or "localhost"
if first.port:
env["DBT_PORT"] = str(first.port)
env["DBT_USER"] = first.username or ""
env["DBT_PASSWORD"] = first.password or ""
return env
def dbt_executable(root: Path, target: str) -> Path:
"""dbt-mysql runs on an older dbt-core, so it lives in its own environment next to the main one."""
return root / (".venv-mysql" if target == "mysql" else ".venv") / "bin" / "dbt"
def compile_manifest(root: Path, target: str, env: dict[str, str], out_dir: Path) -> Path:
"""Compiles every model with placeholders for the question's parameters (`--no-introspect`: the target's
tables needn't exist yet) and returns the manifest's path."""
out_dir.mkdir(parents=True, exist_ok=True)
command = [str(dbt_executable(root, target)), "compile", "--project-dir", str(root), "--profiles-dir", str(root),
"--profile", "cacu", "--target", target, "--no-introspect", "--target-path", str(out_dir)]
subprocess.run(command, check=True, env={**os.environ, **env}, stdout=sys.stderr)
return out_dir / "manifest.json"
def main() -> int:
from persistance.settings import settings
urls = {domain: getattr(settings, f"{domain}_database_url") for domain in DOMAINS}
target = target_of(urls)
if target == "sqlite":
return 0
root = Path(os.environ.get("TRANSFORMATION_DIR") or Path(__file__).resolve().parents[2] / "Transformation")
out_dir = Path(os.environ.get("DBT_MANIFEST_DIR", "/data/dbt"))
print(compile_manifest(root, target, environment(urls, target), out_dir))
return 0
if __name__ == "__main__":
sys.exit(main())
+8 -4
View File
@@ -342,13 +342,17 @@ def tea_outcome(status: int, code: str, error: Exception):
def _included(tea, queries, e, simulated: bool) -> list[dict]:
"""What an episode's search includes: its patient, its steps, its M-CHAT, its diagnosis and its study EEG."""
"""What an episode's search includes: its patient, its steps, its M-CHAT, its ADOS-2, its diagnosis and its study
EEG."""
from sqlalchemy import select
persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == e.child["pac_id"]))
resources = [tea.patient(e.child["pac_id"], persons[0]["fecha_nacimiento"] if persons else None, simulated),
pac_id = e.child["pac_id"]
persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == pac_id))
ados2 = tea.ados2_observation(tea._rows(queries, select(tea.ADOS2).where(tea.ADOS2.c.pac_id == pac_id)),
e.pseudonym, simulated)
resources = [tea.patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated),
tea.care_plan(e, simulated)]
resources += [r for r in (tea.mchat_observation(e, simulated), tea.condition(e, simulated)) if r]
resources += [r for r in (tea.mchat_observation(e, simulated), ados2, tea.condition(e, simulated)) if r]
if (eeg := e.study_eeg()) is not None:
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated)
return resources
+8 -2
View File
@@ -120,9 +120,15 @@ def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -
def _label(spec: dict, value: str) -> str | None:
"""A stratum value's label, when the stratum's `valores` maps values to labels."""
"""A stratum value's label: from `valores` as a map of values to labels, or as a list of entries with `etiqueta`
(a timeline stratum's), or `resto_etiqueta` for its `resto`."""
labels_of = spec.get("valores")
return labels_of.get(value) if isinstance(labels_of, dict) else None
if isinstance(labels_of, dict):
return labels_of.get(value)
if isinstance(labels_of, list):
found = [v.get("etiqueta") for v in labels_of if isinstance(v, dict) and v.get("valor") == value]
return found[0] if found else (spec.get("resto_etiqueta") if value == spec.get("resto") else None)
return None
def _stratum_value(stratifier: str, value: str, display: str | None = None) -> dict:
+7 -1
View File
@@ -10,6 +10,7 @@ Until the domain expert validates the reference ranges, every alteration stays h
the alteration filter, the abnormal/normal split, and the metric and electrode observations.
"""
import hashlib
import os
from dataclasses import dataclass
from datetime import date
@@ -17,7 +18,6 @@ from datetime import date
from sqlalchemy import column, select, table
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged
from webapi.follow_up.listing import seudonimo
STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"),
("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"),
@@ -62,6 +62,12 @@ def salt() -> str:
return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT)
def seudonimo(pac_id: int, sal: str) -> str:
"""TEA's patient and episode ids: stable for a salt, without saying the `pac_id`. CaCu's follow-up list moved
to the platform's `pac_id`; TEA keeps the pseudonym until its patient resources get their own identity."""
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
def _date(value) -> date | None:
if value is None or isinstance(value, date):
return value
+12 -11
View File
@@ -7,15 +7,16 @@ grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la m
estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas
de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
**Es dato por paciente.** Quien sirve la registra solo en DEV, con datos simulados, y toda respuesta
lleva `simulado: true`. Nunca sale `pac_id` ni `pac_id_hospital`: `id_seudonimo` es un hash con sal.
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
misma que usan los lotes de riesgo y `GET /cacu/pacientes/<pac_id>/riesgo`; `id_seudonimo` repite ese valor
mientras los consumidores migran. Nunca sale `pac_id_hospital`.
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
de `estratos.toml`) y salen en `reglas` con su estado. Recibe la sesión de quien sirve; no abre ninguna.
"""
import calendar
import hashlib
import json
import tomllib
from datetime import date, timedelta
@@ -85,7 +86,6 @@ class PaginaFuera(LookupError):
def seguimiento_de(
sesion: Session,
*,
sal: str,
corte: date | None = None,
meses: int | None = None,
estatus: str | None = None,
@@ -119,7 +119,7 @@ def seguimiento_de(
corte = _acotado(sesion, corte or hoy or date.today(), tablas)
desde = _meses_antes(corte, meses) + timedelta(days=1)
estatus_de = _estatus_al_corte(sesion, corte, valores_estatus)
items = _items(sesion, corte, desde, lista, estatus_de, sal, tablas)
items = _items(sesion, corte, desde, lista, estatus_de, tablas)
if estatus is not None:
items = [i for i in items if i["estatus"]["codigo"] == estatus]
@@ -140,9 +140,9 @@ def seguimiento_de(
}
def seudonimo(pac_id: int, sal: str) -> str:
"""El identificador que sale en la lista: estable para una sal, sin decir el `pac_id`."""
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
def identificador(pac_id: int) -> str:
"""El identificador que sale en la lista: el `pac_id` de la plataforma, como texto decimal."""
return str(pac_id)
def _validar_reglas(lista: dict) -> None:
@@ -164,7 +164,7 @@ def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int,
return {pac_id: estatus for pac_id, estatus in filas}
def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
"""Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua."""
estudios = _estudios(sesion, corte, lista["fecha_estudio"])
en_ventana: dict[int, dict[str, list]] = {}
@@ -187,7 +187,8 @@ def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
mas_reciente = max(e["fecha"] for e in [*de_la_paciente["citologia"], *de_la_paciente["vph"]])
estatus = estatus_de.get(pac_id, "INFO_INSUFICIENTE")
items.append({
"id_seudonimo": seudonimo(pac_id, sal),
"pac_id": identificador(pac_id),
"id_seudonimo": identificador(pac_id),
"grupo_edad": edades.get(pac_id, SIN_DATO),
"estatus": {"codigo": estatus, "etiqueta": _etiquetas_de_estatus()[estatus]},
"ultima_citologia": None if cito is None else {
@@ -201,7 +202,7 @@ def _items(sesion, corte, desde, lista, estatus_de, sal, tablas) -> list[dict]:
"prioridad": None,
"_orden": mas_reciente,
})
items.sort(key=lambda i: i["id_seudonimo"])
items.sort(key=lambda i: int(i["pac_id"]))
items.sort(key=lambda i: i.pop("_orden"), reverse=True)
return items
+10 -9
View File
@@ -1,16 +1,17 @@
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, solo en DEV.
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`.
GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size=
Es dato por paciente: **solo se registra en DEV** (con `DEV_REVISION`, que define el despliegue de
`deploy/dev`) y con datos simulados; toda respuesta lleva `simulado: true`. Fuera de DEV la ruta no
existe (404). La lista la arma el kit (`webapi.follow_up.listing`); aquí solo se valida,
se abre la sesión y se traducen los errores.
Es dato por paciente, sobre datos simulados: toda respuesta lleva `simulado: true`. La ruta se registra
siempre; quién puede verla lo decidirá una regla de acceso. Cada fila trae el `pac_id` de la plataforma, el que
usa la ruta de riesgo individual. La lista la arma `webapi.follow_up.listing`; aquí solo se valida, se abre la
sesión y se traducen los errores.
"""
import json
import os
import re
import warnings
from collections.abc import Callable
from datetime import date
@@ -19,16 +20,16 @@ from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
from sqlmodel import Session
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
DEFAULT_SALT = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
def in_dev() -> bool:
"""Si esta WebApi corre en el despliegue de DEV (`deploy/dev/compose.yml` define `DEV_REVISION`)."""
"""Obsoleta: las rutas por paciente ya no dependen de `DEV_REVISION` y nada la llama. Se quitará."""
warnings.warn("in_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2)
return bool(os.environ.get("DEV_REVISION"))
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"` solo en DEV."""
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"`."""
blueprint = Blueprint("cacu_seguimiento", __name__)
@blueprint.get("/seguimiento")
@@ -39,7 +40,7 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
return jsonify({"error": str(error)}), 400
sesion = get_session()
try:
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT), **pedido)
cuerpo = seguimiento_de(sesion, **pedido)
except PedidoInvalido as error:
return jsonify({"error": str(error)}), 400
except PaginaFuera as error:
+33 -7
View File
@@ -15,6 +15,7 @@ from __future__ import annotations
import fcntl
import json
import logging
import os
import re
import time
@@ -23,7 +24,7 @@ from collections import Counter, defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterable
from typing import TYPE_CHECKING, Any, Callable, Iterable
from webapi.imports.schemas.classify import ErrorCategory
@@ -31,7 +32,11 @@ if TYPE_CHECKING:
from webapi.imports.schemas.service import BatchValidationResult
from webapi.imports.services.import_service import ImportSource
log = logging.getLogger(__name__)
SCHEMA_VERSION = 1
# Longest caption, in words, that document discovery reports.
CAPTION_MAX_WORDS = 6
_SHAPE_MAX = 40
_MESSAGE_MAX = 300
_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")
@@ -57,11 +62,12 @@ def value_shape(value: Any) -> str:
return shape + ("…" if len(text) > _SHAPE_MAX else "")
def column_label(name: Any) -> str:
def column_label(name: Any, *, max_words: int = 4) -> str:
"""A source column name as it can be logged: verbatim when it looks like a
header, its shape when it looks like data."""
header, its shape when it looks like data. A document caption, already
cut at a colon, may run to more words (`max_words`) than a header."""
text = str(name).strip()
if len(text) > _SHAPE_MAX or text.count(" ") > 3 or _VALUE_LIKE.search(text):
if len(text) > _SHAPE_MAX or text.count(" ") >= max_words or _VALUE_LIKE.search(text):
return value_shape(text)
return text
@@ -128,9 +134,10 @@ class _SourceAudit:
self.rows: dict[str, Any] = {"leidas": 0}
self.links: dict[str, int] = {}
self.warnings: Counter = Counter()
self.captions: Counter = Counter()
def observe_rows(self, rows: Iterable[dict[str, Any] | None]) -> None:
mapped = set(self.source.column_mapping.values()) | set(self.source.defaults)
mapped = set(self.source.column_mapping.values()) | set(self.source.derived) | set(self.source.defaults)
merged = 0
for row in rows:
self.rows["leidas"] += 1
@@ -164,6 +171,15 @@ class _SourceAudit:
self.rows.update(insertadas=created, actualizadas=updated, rechazadas_por_conflicto=conflicts)
self.links = dict(linked)
def observe_captions(self, count: Callable[[], Counter]) -> None:
"""Captions the source's documents print that the import didn't
use (`ImportSource.unused_captions`). Best-effort: the report must
never be what makes an import fail."""
try:
self.captions = Counter(count())
except Exception:
log.warning("no se pudieron contar las etiquetas sin usar de %s", self.source.target, exc_info=True)
def observe_warnings(self, warnings: Iterable[dict[str, Any]]) -> None:
for warning in warnings:
self.warnings[f"{warning.get('category')}:{warning.get('field')}"] += 1
@@ -171,13 +187,14 @@ class _SourceAudit:
def as_dict(self, threshold: int) -> dict[str, Any]:
spec_fields = self.source.spec.schema.model_fields
required = {name for name, info in spec_fields.items() if info.is_required()}
mapped = set(self.source.column_mapping.values())
mapped = set(self.source.column_mapping.values()) | set(self.source.derived)
fixed = set(self.source.defaults)
out: dict[str, Any] = {
"destino": self.source.target,
"origen": _source_origin(self.source),
"mapeo": {
"columnas_origen": sorted(column_label(c) for c in self.source.column_mapping),
"columnas_origen": sorted(column_label(c) for c in self.source.source_columns),
"campos_derivados": {name: rule.op for name, rule in sorted(self.source.derived.items())},
"campos_mapeados": sorted(mapped),
"campos_con_valor_fijo": sorted(fixed),
"campos_sin_mapear": sorted(set(spec_fields) - mapped - fixed),
@@ -190,6 +207,15 @@ class _SourceAudit:
out["vinculos_resueltos"] = self.links
if self.warnings:
out["advertencias"] = dict(self.warnings)
if self.captions:
# Captions only, and only those enough records print: a caption
# seen once or twice can be a misread line holding a value.
out["etiquetas_sin_usar"] = {
column_label(c, max_words=CAPTION_MAX_WORDS): n for c, n in self.captions.most_common() if n >= threshold
}
rare = sum(1 for n in self.captions.values() if n < threshold)
if rare:
out["etiquetas_sin_usar_poco_frecuentes"] = rare
return out
+279 -26
View File
@@ -1,19 +1,27 @@
import hashlib
import json
import logging
import re
import threading
import unicodedata
from collections import OrderedDict
from typing import Any, ClassVar
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as package_version
from typing import Any, ClassVar, Iterator
import pandas as pd
from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make_segmenter, read_document, reader_for
from extraction.readers import PdfReader, combine_pages, supported_extensions
from extraction.nlp.ranking import examples_for, same_value
from extraction.segmentation import SEGMENTERS
from webapi.imports.connectors.base import decode_file
from webapi.imports.connectors.document_columns import DocumentBatch, DocumentColumns, document_bytes # noqa: F401
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.registry import register_connector
from webapi.imports.connectors.sql import SqlConnector
from webapi.imports.connectors.tabular import DataFrameConnector
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
from webapi.imports.schemas.field_specs import field_specs_for, foreign_subjects_for, key_field_for, subject_for
from webapi.imports.schemas.registry import ENTITY_REGISTRY
DOCUMENT_COLUMN = "documento"
@@ -21,6 +29,8 @@ IMAGE_COLUMN = "imagen"
CONFIDENCE_COLUMN = "confianza_extraccion"
SOURCES_COLUMN = "origen"
logger = logging.getLogger(__name__)
class _ResultCache:
"""OCR over a stack of scans is slow, and the stateless API runs the
@@ -28,11 +38,11 @@ class _ResultCache:
per worker for the last few distinct requests."""
def __init__(self, size: int = 8):
self._items: OrderedDict[str, list[ExtractedRecord]] = OrderedDict()
self._items: OrderedDict[str, Any] = OrderedDict()
self._size = size
self._lock = threading.Lock()
def get_or_compute(self, key: str, compute) -> list[ExtractedRecord]:
def get_or_compute(self, key: str, compute) -> Any:
with self._lock:
if key in self._items:
self._items.move_to_end(key)
@@ -48,24 +58,50 @@ class _ResultCache:
_CACHE = _ResultCache()
def _files_from_sql(sql: dict[str, Any]) -> DocumentBatch:
"""The documents of a SQL table or query (connected the same way
`SqlConnector` is), read as `DocumentColumns` describes: `column` or
`columns` hold them, and `key_column`/`name_by`, `group_column`/
`group_by` and `fields` name, group and carry values for them."""
if not sql.get("table") and not sql.get("query"):
raise ConnectorError("falta table o query")
spec = DocumentColumns.parse(sql)
connector = SqlConnector.connect(sql)
connector = (
connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema"))
)
return spec.assemble(connector.read_rows({column: column for column in spec.source_columns()}))
@register_connector
class DocumentConnector(DataFrameConnector):
"""Clinical documents that are not tables: one report per patient,
several pages per patient, many patients per file, scans, free text.
several pages per patient, many patients per file, scans, free text —
uploaded directly, or read one row at a time from a SQL source whose
`payload` carries `sql` (a connection plus `table`/`query`, `column`
and `key_column`) instead of `files`; either way, every row's content
reaches the same extraction, PDF, image or plain text alike.
Every file is read page by page (text layer or OCR), split into
per-patient records, and the target entity's fields are extracted from
labels and narrative text. Records of the same patient found in other
pages or files are merged. Each row also carries the record's pages as
a PDF (`documento`), mappable to the entity's file column.
Every file is read page by page (text layer or OCR; plain text as its
own lines), split into per-patient records, and the target entity's
fields are extracted from labels and narrative text. Records of the
same patient found in other pages or files — or rows — are merged.
Each row also carries the record's pages as a PDF (`documento`),
mappable to the entity's file column, when the source produced one.
Corrections made while reviewing travel in `overrides`
(`{"<row>": {"field": value}}`) and win over the extracted value.
A SQL source's `sql.fields` (`{target_field: sql_column}`) carries other
columns of the same row straight through as that row's values for those
fields, overriding whatever the document's own text parses to — a
source's own patient or study id is a structured join key, not a guess,
so it wins even over a page that prints nothing recognizable, or
prints something else entirely. Corrections made while reviewing
travel in `overrides` (`{"<row>": {"field": value}}`) and win over
both.
"""
kind = "document"
label = "Documentos clínicos"
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
description = "Reportes, formatos y notas en PDF, imagen o texto; los campos se extraen del contenido"
category = "document"
icon = "document_scanner"
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
@@ -80,6 +116,10 @@ class DocumentConnector(DataFrameConnector):
ocr_mode: str = "auto",
key_pattern: str | None = None,
overrides: dict[str, dict[str, Any]] | None = None,
source_fields: dict[str, dict[str, Any]] | None = None,
record_keys: dict[str, str] | None = None,
include_pattern: str | None = None,
exclude_pattern: str | None = None,
):
if not files:
raise ConnectorError("no se recibieron documentos")
@@ -92,6 +132,12 @@ class DocumentConnector(DataFrameConnector):
raise ConnectorError(f"ocr_mode desconocido {ocr_mode!r}")
self.files = files
self.target = target
self.domain = target.split(".", 1)[0]
self.subject = subject_for(entity)
self.foreign = foreign_subjects_for(entity)
# The entity's column for the extraction version that filled it, when it has one.
self.nlp_field = next((name for name in entity.schema.model_fields if name.endswith("_nlp_version")), None)
self.ranker = _ranker(self.domain)
self.specs = field_specs_for(entity, key_pattern=key_pattern)
self.key_field = key_field_for(entity)
self.segmentation = segmentation
@@ -99,19 +145,37 @@ class DocumentConnector(DataFrameConnector):
self.ocr_mode = ocr_mode
self.key_pattern = key_pattern
self.overrides = {str(k): v for k, v in (overrides or {}).items()}
self.source_fields = {str(k): v for k, v in (source_fields or {}).items()}
self.record_keys = {str(k): str(v) for k, v in (record_keys or {}).items()}
self.include_pattern = _compile_filter(include_pattern, "include_pattern")
self.exclude_pattern = _compile_filter(exclude_pattern, "exclude_pattern")
self.skipped: list[dict[str, str]] = []
known = {spec.name for spec in self.specs}
unknown = sorted({name for values in self.source_fields.values() for name in values} - known)
if unknown:
raise ConnectorError(f"fields desconocidos para {target}: {', '.join(unknown)}")
self._df: pd.DataFrame | None = None
@classmethod
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
if payload.get("sql"):
documents = _files_from_sql(payload["sql"])
else:
documents = DocumentBatch(
files=[(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
)
return cls(
files,
documents.files,
target=payload["target"],
segmentation=payload.get("segmentation", "auto"),
pages_per_record=payload.get("pages_per_record", 1),
ocr_mode=payload.get("ocr_mode", "auto"),
key_pattern=payload.get("key_pattern") or None,
overrides=payload.get("overrides"),
source_fields=documents.source_fields,
record_keys=documents.record_keys,
include_pattern=payload.get("include_pattern") or None,
exclude_pattern=payload.get("exclude_pattern") or None,
)
@classmethod
@@ -123,41 +187,119 @@ class DocumentConnector(DataFrameConnector):
@property
def records(self) -> list[ExtractedRecord]:
return _CACHE.get_or_compute(self._cache_key(), self._extract)
records, self.skipped = _CACHE.get_or_compute(self._cache_key(), self._extract)
return records
def _extract(self) -> list[ExtractedRecord]:
try:
documents = [read_document(name, raw, ocr_mode=self.ocr_mode) for name, raw in self.files]
except ExtractionError as exc:
raise ConnectorError(str(exc)) from exc
def _extract(self) -> tuple[list[ExtractedRecord], list[dict[str, str]]]:
documents, skipped = [], []
for name, raw in self.files:
try:
document = read_document(name, raw, ocr_mode=self.ocr_mode)
except ExtractionError as exc:
skipped.append({"document": name, "reason": f"ilegible: {exc}"})
continue
reason = self._filtered_out(document)
if reason:
skipped.append({"document": name, "reason": reason})
continue
documents.append(document)
if not documents:
detail = "; ".join(f"{s['document']}: {s['reason']}" for s in skipped[:5])
raise ConnectorError(f"ningún documento se pudo usar ({detail})")
segmenter = make_segmenter(
self.segmentation,
key=next((s for s in self.specs if s.name == self.key_field), None),
pages_per_record=self.pages_per_record,
)
return DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(documents)
records = DocumentExtractor(
self.specs, key_field=self.key_field, segmenter=segmenter, subject=self.subject, foreign=self.foreign, ranker=self.ranker
).extract(documents, source_fields=self.source_fields, record_keys=self.record_keys)
return records, skipped
@property
def nlp_version(self) -> str:
"""The extraction code's version and the ranker's (`extraccion:<n>`), when one was used."""
try:
code = package_version("extraction")
except PackageNotFoundError:
code = "dev"
return f"extraction {code}" + (f" + {self.ranker.version}" if self.ranker is not None and self.ranker.version else "")
def _filtered_out(self, document) -> str | None:
"""Why a document is left out by `include_pattern`/`exclude_pattern`,
matched case- and accent-insensitively against all of its text,
so a source mixing several kinds of report feeds each target only
its own."""
text = "\n".join(page.text for page in document.pages)
plain = _unaccented(text)
if self.include_pattern and not (self.include_pattern.search(text) or self.include_pattern.search(plain)):
return "no coincide con include_pattern"
if self.exclude_pattern and (self.exclude_pattern.search(text) or self.exclude_pattern.search(plain)):
return "coincide con exclude_pattern"
return None
def _cache_key(self) -> str:
digest = hashlib.sha256()
for name, raw in self.files:
digest.update(name.encode())
digest.update(hashlib.sha256(raw).digest())
config = [self.target, self.segmentation, self.pages_per_record, self.ocr_mode, self.key_pattern]
digest.update(json.dumps(config).encode())
config = [
self.target,
self.nlp_version,
self.segmentation,
self.pages_per_record,
self.ocr_mode,
self.key_pattern,
self.source_fields,
self.record_keys,
self.include_pattern.pattern if self.include_pattern else None,
self.exclude_pattern.pattern if self.exclude_pattern else None,
]
digest.update(json.dumps(config, sort_keys=True, default=str).encode())
return digest.hexdigest()
# -- rows -----------------------------------------------------------------
def _dataframe(self) -> pd.DataFrame:
if self._df is None:
columns = [spec.name for spec in self.specs] + [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
columns = (
[spec.name for spec in self.specs]
+ ([self.nlp_field] if self.nlp_field else [])
+ self.caption_columns()
+ [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
)
rows = [self._row(index, record) for index, record in enumerate(self.records)]
self._df = pd.DataFrame(rows, columns=columns, dtype=object)
return self._df
def caption_columns(self) -> list[str]:
"""Every caption the documents print that no field of the target
claims, in the order first seen: columns of their own, mappable
and usable in derived fields like any column of a table."""
reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
columns: list[str] = []
for record in self.records:
for found in record.discovered:
name = _caption_column(found.caption, reserved)
if name not in columns:
columns.append(name)
return columns
def record_rows(self) -> Iterator[tuple[dict[str, Any], list[str]]]:
"""Each record's row (overrides applied, its captions as columns,
its pages as `documento`) with the names of the documents it was
read from."""
for index, record in enumerate(self.records):
yield self._row(index, record), [source.document for source in record.sources]
def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]:
row: dict[str, Any] = record.row()
reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
for found in record.discovered:
row.setdefault(_caption_column(found.caption, reserved), found.value)
row.update(self.overrides.get(str(index), {}))
if self.nlp_field and record.values:
row[self.nlp_field] = self.nlp_version
row[DOCUMENT_COLUMN] = self._record_pdf(record)
row[IMAGE_COLUMN] = self._record_image(record)
row[CONFIDENCE_COLUMN] = round(record.confidence, 3)
@@ -207,7 +349,13 @@ class DocumentConnector(DataFrameConnector):
"index": index,
"key": record.key,
"confidence": round(record.confidence, 3),
"on_topic": record.on_topic,
"fields": fields,
"alternatives": {
name: _alternatives(proposed, record.values.get(name))
for name, proposed in record.candidates.items()
if _alternatives(proposed, record.values.get(name))
},
"missing": [s.name for s in self.specs if s.required and s.name not in fields],
"conflicts": [
{"field": c.field, "kept": c.kept.to_dict(), "discarded": c.discarded.to_dict()}
@@ -223,4 +371,109 @@ class DocumentConnector(DataFrameConnector):
return report
def metadata(self) -> dict[str, Any]:
return {"records": len(self.records), "key_field": self.key_field, "documents": [name for name, _ in self.files]}
return {
"records": len(self.records),
"key_field": self.key_field,
"documents": [name for name, _ in self.files],
"skipped": self.skipped,
"nlp_version": self.nlp_version,
}
# -- learning -------------------------------------------------------------
def reviewed(self) -> list[tuple[ExtractedRecord, dict[str, Any]]]:
"""The records a person corrected while reviewing, each with what is
known to be right about it: the corrected fields, and every other
field as it was extracted, since whoever corrected the record read
it. Fields a correction emptied are known to be empty."""
reviewed = []
for index, record in enumerate(self.records):
corrections = self.overrides.get(str(index))
if not corrections:
continue
truth: dict[str, Any] = {name: value.value for name, value in record.values.items()}
truth.update({name: (None if value in ("", None) else value) for name, value in corrections.items()})
known = {spec.name for spec in self.specs}
reviewed.append((record, {name: value for name, value in truth.items() if name in known}))
return reviewed
def learning_examples(self) -> tuple[list, dict[str, int], int]:
"""Examples for the ranker from the reviewed records
(`extraction.nlp.ranking.examples_for`), per field how many right
values no candidate had proposed, and how many records they came from."""
examples: list = []
unreachable: dict[str, int] = {}
reviewed = self.reviewed()
for record, truth in reviewed:
examples.extend(examples_for(self.specs, record.candidates, truth))
for name, value in truth.items():
if value is not None and not any(same_value(c.value, value) for c in record.candidates.get(name, ())):
unreachable[name] = unreachable.get(name, 0) + 1
return examples, unreachable, len(reviewed)
def _ranker(domain: str):
"""The domain's extraction ranker in the model registry, or `None` (rank by
confidence) when there is none or the registry can't be read."""
try:
from models.io.extraction_ranker import current
return current(domain)
except Exception as exc: # noqa: BLE001 - extraction must work without the registry
logger.warning("sin ranker de extracción para %s: %s", domain, exc)
return None
def _alternatives(proposed: list, chosen) -> list[dict[str, Any]]:
"""The other values the extractors proposed for a field, best first, for a reviewer to pick from."""
seen, found = set(), []
for candidate in sorted(proposed, key=lambda c: -c.confidence):
if chosen is not None and same_value(candidate.value, chosen.value):
continue
key = json.dumps(candidate.to_dict()["value"], default=str)
if key in seen:
continue
seen.add(key)
found.append({**candidate.to_dict(), "confidence": round(candidate.confidence, 3)})
return found[:5]
def _caption_column(caption: str, reserved: set[str]) -> str:
"""A discovered caption as a column name, kept apart from the target's
own fields and the connector's bookkeeping columns."""
name = " ".join(caption.split())
return f"texto: {name}" if name in reserved else name
def _compile_filter(pattern: str | None, name: str) -> re.Pattern | None:
if not pattern:
return None
try:
return re.compile(pattern, re.I)
except re.error as exc:
raise ConnectorError(f"{name} no es una expresión regular válida: {exc}") from exc
def _unaccented(text: str) -> str:
return "".join(ch for ch in unicodedata.normalize("NFKD", text) if not unicodedata.combining(ch))
DOCUMENT_OPTIONS = ("segmentation", "pages_per_record", "ocr_mode", "key_pattern", "overrides", "include_pattern", "exclude_pattern")
def document_options(raw: dict[str, Any]) -> dict[str, Any]:
"""The extraction settings `DocumentConnector` takes, out of a request."""
return {name: raw[name] for name in DOCUMENT_OPTIONS if raw.get(name) not in (None, "")}
def connector_for_batch(batch: DocumentBatch, target: str, options: dict[str, Any]) -> "DocumentConnector":
"""A `DocumentConnector` over documents read from a source's columns,
their row values restricted to the fields extraction knows."""
entity = ENTITY_REGISTRY.get(target)
if entity is None:
raise ConnectorError(f"destino desconocido: {target!r}")
known = {spec.name for spec in field_specs_for(entity)}
source_fields = {name: {k: v for k, v in values.items() if k in known} for name, values in batch.source_fields.items()}
return DocumentConnector(
batch.files, target=target, source_fields=source_fields, record_keys=batch.record_keys, **document_options(options)
)
@@ -0,0 +1,167 @@
"""Documents stored in the columns of any tabular source: a SQL table or
query, a CSV or Excel sheet, a JSON list. Each non-empty cell of a document
column becomes one document; the rest of its row travels with it as values
the extraction must trust over the page, and an optional grouping decides
which documents form one record.
A cell may hold the file itself (binary), the same file written as hex or
base64 text, or plain text; `document_bytes` tells them apart.
"""
import base64
import binascii
import re
from dataclasses import dataclass, field
from typing import Any, Iterable
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.mapping.derived import Derivation, rule_from
_HEX = re.compile(r"^(?:0x)?(?:[0-9a-fA-F]{2})+$")
_BASE64 = re.compile(r"^[A-Za-z0-9+/\r\n]+={0,2}$")
DOCUMENT_MAGIC = (b"%PDF", b"\x89PNG", b"\xff\xd8\xff", b"II*\x00", b"MM\x00*", b"BM", b"RIFF", b"GIF8")
def document_bytes(raw: Any) -> bytes:
"""A stored document as bytes. Binary values pass through; text is
checked for a binary file written out as hex or base64 before being
taken as plain UTF-8 text."""
if isinstance(raw, memoryview):
raw = raw.tobytes()
if isinstance(raw, (bytes, bytearray)):
return bytes(raw)
text = str(raw).strip()
if len(text) >= 16 and _HEX.match(text):
decoded = bytes.fromhex(text[2:] if text[:2].lower() == "0x" else text)
if decoded.startswith(DOCUMENT_MAGIC):
return decoded
if len(text) >= 16 and _BASE64.match(text):
try:
decoded = base64.b64decode(text, validate=False)
except (binascii.Error, ValueError):
decoded = b""
if decoded.startswith(DOCUMENT_MAGIC):
return decoded
return text.encode("utf-8")
def is_document(raw: Any) -> bool:
"""Whether a cell holds a file a document reader opens (as opposed to
a plain value), whatever way it was stored."""
if raw is None or isinstance(raw, (int, float, bool)):
return False
return document_bytes(raw).startswith(DOCUMENT_MAGIC)
@dataclass
class DocumentBatch:
"""What the extractor receives: one `(name, bytes)` per document and,
per document name, its authoritative values and the record it joins.
`rows` and `row_numbers` keep, per document name, the values of the row
it came from and that row's position (from 1)."""
files: list[tuple[str, bytes]] = field(default_factory=list)
source_fields: dict[str, dict[str, Any]] = field(default_factory=dict)
record_keys: dict[str, str] = field(default_factory=dict)
rows: dict[str, dict[str, Any]] = field(default_factory=dict)
row_numbers: dict[str, int] = field(default_factory=dict)
without_documents: list[dict[str, Any]] = field(default_factory=list)
@dataclass
class DocumentColumns:
"""How to read documents out of a source's rows.
`columns`: the columns holding documents (one or several per row).
`name_by`: names each row in reports (default: its row number).
`group_by`: rows giving the same value form one record, apart from
the same patient's other rows; without it, documents merge by the
target's key field, as uploaded files do.
`fields`: target fields filled from the row, trusted over the page.
The last three take a column name, a list of columns or a `derived`
rule (`webapi.imports.mapping.derived`)."""
columns: list[str]
name_by: Derivation | None = None
group_by: Derivation | None = None
fields: dict[str, Derivation] = field(default_factory=dict)
@classmethod
def parse(cls, raw: Any) -> "DocumentColumns":
if not isinstance(raw, dict):
raise ConnectorError("'documents' debe ser un objeto")
columns = raw.get("columns", raw.get("column"))
columns = [columns] if isinstance(columns, str) else list(columns or [])
if not columns or not all(isinstance(column, str) and column for column in columns):
raise ConnectorError("indique la columna (o columnas) con los documentos")
fields = raw.get("fields") or {}
if not isinstance(fields, dict):
raise ConnectorError("'fields' debe ser un objeto {campo: columna o regla}")
name_by = raw.get("name_by", raw.get("key_column"))
group_by = raw.get("group_by", raw.get("group_column"))
parsed = cls(
columns=columns,
name_by=rule_from(name_by) if name_by else None,
group_by=rule_from(group_by) if group_by else None,
fields={name: rule_from(rule, separator=" ") for name, rule in fields.items()},
)
roles = {"name_by (key_column)": [parsed.name_by], "group_by (group_column)": [parsed.group_by], "fields": list(parsed.fields.values())}
for role, rules in roles.items():
reused = set().union(*(rule.columns() for rule in rules if rule is not None)) & set(columns)
if reused:
raise ConnectorError(f"{sorted(reused)} contiene los documentos; no puede usarse también en {role}")
return parsed
def columns_read_by_rules(self) -> set[str]:
read: set[str] = set()
for rule in [self.name_by, self.group_by, *self.fields.values()]:
if rule is not None:
read |= rule.columns()
return read
def source_columns(self) -> set[str]:
return set(self.columns) | self.columns_read_by_rules()
def assemble(
self, raw_rows: Iterable[dict[str, Any]], mapped_rows: Iterable[dict[str, Any]] | None = None
) -> DocumentBatch:
"""`raw_rows` keyed by source column; `mapped_rows`, when the source
also has a mapping, the same rows already mapped to target fields,
whose values join `fields` as values to trust."""
batch = DocumentBatch()
seen: dict[str, int] = {}
mapped = iter(mapped_rows) if mapped_rows is not None else None
for number, raw in enumerate(raw_rows, start=1):
values = dict(next(mapped)) if mapped is not None else {}
values.update({name: rule.apply(raw) for name, rule in self.fields.items()})
values = {name: value for name, value in values.items() if not _blank(value)}
contents = [(column, raw.get(column)) for column in self.columns if not _blank(raw.get(column))]
if not contents:
batch.without_documents.append(values)
continue
base = _text(self.name_by.apply(raw)) if self.name_by else ""
base = base or str(number)
group = _text(self.group_by.apply(raw)) if self.group_by else ""
for column, content in contents:
name = base if len(self.columns) == 1 else f"{base}:{column}"
seen[name] = seen.get(name, 0) + 1
if seen[name] > 1:
name = f"{name}#{seen[name]}"
batch.files.append((name, document_bytes(content)))
batch.source_fields[name] = values
batch.rows[name] = values
batch.row_numbers[name] = number
if group:
batch.record_keys[name] = group
return batch
def _blank(value: Any) -> bool:
return value is None or (isinstance(value, str) and not value.strip())
def _text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, float) and value.is_integer():
value = int(value)
return str(value).strip()
+99 -6
View File
@@ -1,17 +1,19 @@
import datetime as _dt
import importlib.util
import re
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, ClassVar, Iterator
import pandas as pd
import sqlalchemy as sa
import sqlglot
from sqlalchemy.pool import NullPool
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.registry import register_connector
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
from webapi.imports.connectors.sql_policy import SQLGLOT_DIALECTS, SqlSourcePolicy
from webapi.imports.connectors.tabular import infer_type
@@ -27,6 +29,7 @@ class SqlEngine:
driver_module: str
description: str = ""
default_schema: str | None = None
supports_instance_name: bool = False
@property
def available(self) -> bool:
@@ -67,7 +70,10 @@ class SqlConnector(Connector):
SqlEngine("mysql", "MySQL", "mysql+pymysql", 3306, "pymysql", "Servidor MySQL 5.7+ / 8"),
SqlEngine("mariadb", "MariaDB", "mariadb+pymysql", 3306, "pymysql", "Servidor MariaDB"),
SqlEngine("postgresql", "PostgreSQL", "postgresql+psycopg2", 5432, "psycopg2", "Servidor PostgreSQL", "public"),
SqlEngine("mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql", "Microsoft SQL Server 2017+ / Azure SQL", "dbo"),
SqlEngine(
"mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql",
"Microsoft SQL Server 2017+ / Azure SQL", "dbo", supports_instance_name=True,
),
)
}
@@ -102,15 +108,27 @@ class SqlConnector(Connector):
raise ConnectorError(f"el controlador de {engine.label} ({engine.driver_module}) no está instalado en el servidor")
if not server.get("host") or not server.get("database"):
raise ConnectorError("se requieren el servidor (host) y la base de datos")
host, instance, embedded_port = _parse_server_address(str(server["host"]))
if instance and not engine.supports_instance_name:
raise ConnectorError(f"{engine.label} no admite una instancia con nombre ({server['host']!r}); indique solo el host y, si aplica, el puerto")
explicit_port = server.get("port")
try:
port = int(server.get("port") or engine.default_port)
port = int(explicit_port) if explicit_port not in (None, "") else embedded_port
except (TypeError, ValueError) as exc:
raise ConnectorError("el puerto debe ser un número") from exc
if instance:
host = f"{host}\\{instance}"
elif port is None:
port = engine.default_port
return sa.engine.URL.create(
engine.drivername,
username=server.get("user") or None,
password=server.get("password") or None,
host=server["host"],
host=host,
port=port,
database=server["database"],
)
@@ -205,7 +223,7 @@ class SqlConnector(Connector):
if self._table is not None:
return sa.select(self._table).subquery("source")
if self._query:
return _text_subquery(self._query)
return _text_subquery(self._query, self.get_dialect())
raise ConnectorError("no hay tabla ni consulta seleccionada")
def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]:
@@ -235,12 +253,87 @@ class SqlConnector(Connector):
conn.rollback()
def _text_subquery(query: str) -> sa.Subquery:
_ADDRESS_SCHEME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.\-:]*?://")
_ADDRESS_PORT_SEPARATORS = (",", ":")
def _parse_server_address(raw: str) -> tuple[str, str | None, int | None]:
"""Tolerates the ways a server address arrives typed or pasted from
a SQL client, a JDBC string or a connection URI instead of a bare host: a
leading scheme (`jdbc:sqlserver://`, `postgresql://`, `tcp:`), a
trailing path/query/property list, surrounding whitespace, a SQL
Server named instance (`host\\instance`), and a port given as
`host:port` or SQL Server's `host,port` / `host\\instance,port`.
Returns `(host, instance, port)`, with `instance` and `port` `None`
when absent, so the caller can leave the port unset for a named
instance instead of forcing the engine's default one.
"""
address = _ADDRESS_SCHEME_RE.sub("", raw.strip(), count=1)
if address.lower().startswith("tcp:"):
address = address[len("tcp:") :]
for cut in ("/", "?", ";"):
address = address.split(cut, 1)[0]
address = address.strip()
instance: str | None = None
if "\\" in address:
host, instance = (part.strip() for part in address.split("\\", 1))
else:
host = address
tail = instance or host
port: int | None = None
for sep in _ADDRESS_PORT_SEPARATORS:
if tail.count(sep) == 1:
prefix, suffix = (part.strip() for part in tail.split(sep))
if suffix.isdigit():
tail, port = prefix, int(suffix)
break
if instance:
instance = tail or None
else:
host = tail
return host, (instance or None), port
def _text_subquery(query: str, dialect: str | None = None) -> sa.Subquery:
"""Wraps policy-checked SELECT text as a derived table, so SQLAlchemy
composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks."""
query = _without_trailing_order_by(query, dialect)
return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source")
_ORDER_BY = re.compile(r"\bORDER\s+BY\b", re.I)
def _without_trailing_order_by(query: str, dialect: str | None) -> str:
"""Drops a top-level `ORDER BY` that nothing limits: SQL Server refuses
one inside a derived table, and row order means nothing to an import.
Kept when TOP, LIMIT or OFFSET makes it choose the rows."""
try:
[root] = sqlglot.parse(query, read=SQLGLOT_DIALECTS.get(dialect, dialect))
except Exception:
return query
if root is None or not root.args.get("order") or root.args.get("limit") or root.args.get("offset"):
return query
depth, quote, cut = 0, None, None
for position, char in enumerate(query):
if quote:
quote = None if char == quote else quote
elif char in "'\"[`":
quote = "]" if char == "[" else char
elif char == "(":
depth += 1
elif char == ")":
depth -= 1
elif depth == 0 and _ORDER_BY.match(query, position):
cut = position
return query[:cut].rstrip() if cut is not None else query
def _sa_type_to_kind(sa_type: sa.types.TypeEngine) -> str:
try:
python_type = sa_type.python_type
+2 -2
View File
@@ -22,7 +22,7 @@ from webapi.imports.connectors.errors import ConnectorError
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql"
_DEFAULT_PORTS = {"mysql": 3306, "mariadb": 3306, "postgresql": 5432, "mssql": 1433}
# SQLAlchemy dialect name -> sqlglot's name for it, where they differ.
_SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"}
SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"}
# Anything that writes, wherever it sits in the tree: a top-level
# `SELECT ... INTO table`/`INTO OUTFILE`, or a writable CTE
# (`WITH t AS (DELETE FROM x RETURNING *) SELECT * FROM t` still parses as a
@@ -73,7 +73,7 @@ class SqlSourcePolicy:
if not statement:
raise ConnectorError("la consulta no puede estar vacía")
try:
parsed = [node for node in sqlglot.parse(statement, read=_SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None]
parsed = [node for node in sqlglot.parse(statement, read=SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None]
except sqlglot.errors.ParseError as exc:
raise ConnectorError(f"la consulta no es SQL válido: {exc}") from exc
if len(parsed) != 1:
+305
View File
@@ -0,0 +1,305 @@
"""Target fields computed from one or more source columns, for sources whose
columns don't line up one-to-one with the target: a name and surnames kept
apart where the target wants one full name, or the reverse; an id spread
over two columns; a code that must be read out of a longer text.
A source's `derived` maps each target field to one rule,
`{"op": <name>, ...params}`, plus the optional `case` (`upper`, `lower`,
`title`) applied to the result. To add an operation, subclass `Derivation`,
declare its `params` and register it with `@register_derivation`.
"""
import re
import string
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, ClassVar
from webapi.imports.connectors.errors import ConnectorError
@dataclass(frozen=True)
class Param:
"""One parameter of an operation, described so a client can build its form."""
name: str
kind: str # column | columns | text | integer | mapping | boolean
label: str
required: bool = True
default: Any = None
def to_dict(self) -> dict[str, Any]:
return {"name": self.name, "kind": self.kind, "label": self.label, "required": self.required, "default": self.default}
CASES = {"upper": str.upper, "lower": str.lower, "title": str.title}
class Derivation(ABC):
op: ClassVar[str]
label: ClassVar[str]
description: ClassVar[str]
params: ClassVar[tuple[Param, ...]]
def __init__(self, rule: dict[str, Any]):
self.args: dict[str, Any] = {}
for param in self.params:
value = rule.get(param.name, param.default)
if param.required and _blank(value):
raise ConnectorError(f"la regla {self.op!r} requiere {param.name!r}")
if param.kind == "columns" and value is not None and not isinstance(value, list):
raise ConnectorError(f"{param.name!r} debe ser una lista de columnas")
self.args[param.name] = value
self.case = rule.get("case") or None
if self.case is not None and self.case not in CASES:
raise ConnectorError(f"case desconocido {self.case!r} (disponibles: {', '.join(CASES)})")
@abstractmethod
def columns(self) -> set[str]:
"""The source columns this rule reads."""
@abstractmethod
def compute(self, row: dict[str, Any]) -> Any: ...
def apply(self, row: dict[str, Any]) -> Any:
value = self.compute(row)
if isinstance(value, str):
value = " ".join(value.split())
if self.case:
value = CASES[self.case](value)
return value or None
return value
@classmethod
def describe(cls) -> dict[str, Any]:
return {
"op": cls.op,
"label": cls.label,
"description": cls.description,
"params": [param.to_dict() for param in cls.params],
}
DERIVATIONS: dict[str, type[Derivation]] = {}
def register_derivation(cls: type[Derivation]) -> type[Derivation]:
DERIVATIONS[cls.op] = cls
return cls
def build_derivation(rule: Any) -> Derivation:
if not isinstance(rule, dict):
raise ConnectorError("cada regla de 'derived' debe ser un objeto")
cls = DERIVATIONS.get(rule.get("op", ""))
if cls is None:
raise ConnectorError(f"operación desconocida {rule.get('op')!r} (disponibles: {', '.join(DERIVATIONS)})")
return cls(rule)
def _blank(value: Any) -> bool:
return value is None or (isinstance(value, str) and not value.strip()) or value == [] or value == {}
def _index(value: Any) -> int | None:
if value in (None, ""):
return None
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ConnectorError(f"se esperaba un número entero, no {value!r}") from exc
def _text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, float) and value.is_integer():
value = int(value)
return str(value).strip()
@register_derivation
class Column(Derivation):
op = "column"
label = "Columna"
description = "El valor de una columna, tal cual."
params = (Param("column", "column", "Columna"),)
def columns(self) -> set[str]:
return {self.args["column"]}
def compute(self, row: dict[str, Any]) -> Any:
return row.get(self.args["column"])
@register_derivation
class Concat(Derivation):
op = "concat"
label = "Unir columnas"
description = "Une los valores no vacíos de varias columnas, en orden, con un separador."
params = (
Param("columns", "columns", "Columnas"),
Param("separator", "text", "Separador", required=False, default=" "),
)
def columns(self) -> set[str]:
return set(self.args["columns"])
def compute(self, row: dict[str, Any]) -> Any:
parts = [_text(row.get(column)) for column in self.args["columns"]]
separator = self.args["separator"] if self.args["separator"] is not None else " "
return separator.join(part for part in parts if part)
@register_derivation
class Template(Derivation):
op = "template"
label = "Plantilla"
description = "Arma un texto con columnas entre llaves: `{Nombre} {Apellido}`. Las columnas vacías se omiten."
params = (Param("template", "text", "Plantilla"),)
def __init__(self, rule: dict[str, Any]):
super().__init__(rule)
try:
self._names = [name for _, name, _, _ in string.Formatter().parse(self.args["template"]) if name]
except ValueError as exc:
raise ConnectorError(f"plantilla inválida: {exc}") from exc
def columns(self) -> set[str]:
return set(self._names)
def compute(self, row: dict[str, Any]) -> Any:
values = {name: _text(row.get(name)) for name in self._names}
return string.Formatter().vformat(self.args["template"], (), _Fill(values))
class _Fill(dict):
def __missing__(self, key: str) -> str:
return ""
@register_derivation
class Split(Derivation):
op = "split"
label = "Tomar partes"
description = (
"Separa el valor de una columna y toma las partes de `start` a `stop` "
"(se cuentan desde 0; negativas desde el final): de un nombre completo, "
"el primer apellido es `start=-2, stop=-1`."
)
params = (
Param("column", "column", "Columna"),
Param("separator", "text", "Separador (vacío: espacios)", required=False, default=""),
Param("start", "integer", "Desde", required=False, default=0),
Param("stop", "integer", "Hasta (sin incluir)", required=False, default=None),
)
def columns(self) -> set[str]:
return {self.args["column"]}
def compute(self, row: dict[str, Any]) -> Any:
text = _text(row.get(self.args["column"]))
if not text:
return None
separator = self.args["separator"] or None
parts = text.split(separator) if separator else text.split()
start, stop = (_index(self.args[name]) for name in ("start", "stop"))
return (separator or " ").join(part.strip() for part in parts[start:stop] if part.strip())
@register_derivation
class Coalesce(Derivation):
op = "coalesce"
label = "Primera con valor"
description = "El valor de la primera columna, en orden, que no esté vacía."
params = (Param("columns", "columns", "Columnas"),)
def columns(self) -> set[str]:
return set(self.args["columns"])
def compute(self, row: dict[str, Any]) -> Any:
for column in self.args["columns"]:
value = row.get(column)
if not _blank(value):
return value
return None
@register_derivation
class Extract(Derivation):
op = "extract"
label = "Extraer con patrón"
description = "La parte del valor que coincide con una expresión regular (o su grupo `group`)."
params = (
Param("column", "column", "Columna"),
Param("pattern", "text", "Expresión regular"),
Param("group", "integer", "Grupo", required=False, default=0),
)
def __init__(self, rule: dict[str, Any]):
super().__init__(rule)
try:
self._regex = re.compile(self.args["pattern"], re.I)
except re.error as exc:
raise ConnectorError(f"expresión regular inválida: {exc}") from exc
def columns(self) -> set[str]:
return {self.args["column"]}
def compute(self, row: dict[str, Any]) -> Any:
match = self._regex.search(_text(row.get(self.args["column"])))
if not match:
return None
try:
return match.group(_index(self.args["group"]) or 0)
except IndexError as exc:
raise ConnectorError(f"la expresión no tiene el grupo {self.args['group']}") from exc
@register_derivation
class Translate(Derivation):
op = "map"
label = "Traducir valores"
description = "Cambia cada valor por otro según una tabla (`M` → `Masculino`), sin distinguir mayúsculas ni espacios."
params = (
Param("column", "column", "Columna"),
Param("values", "mapping", "Tabla de valores"),
Param("keep_unmatched", "boolean", "Conservar los que no estén en la tabla", required=False, default=True),
)
def __init__(self, rule: dict[str, Any]):
super().__init__(rule)
if not isinstance(self.args["values"], dict):
raise ConnectorError("'values' debe ser un objeto")
self._table = {_text(key).casefold(): value for key, value in self.args["values"].items()}
def columns(self) -> set[str]:
return {self.args["column"]}
def compute(self, row: dict[str, Any]) -> Any:
value = row.get(self.args["column"])
key = _text(value).casefold()
if key in self._table:
return self._table[key]
return value if self.args["keep_unmatched"] is not False else None
def rule_from(value: Any, *, separator: str = " | ") -> Derivation:
"""A rule given in short form: a column name, a list of columns (joined
with `separator`) or a full rule object."""
if isinstance(value, str):
return Column({"column": value})
if isinstance(value, list):
return Concat({"columns": value, "separator": separator})
return build_derivation(value)
def parse_derived(raw: Any, fields: set[str]) -> dict[str, Derivation]:
"""`{target_field: rule}` validated against the target's fields."""
if raw in (None, {}):
return {}
if not isinstance(raw, dict):
raise ConnectorError("'derived' debe ser un objeto {campo: regla}")
unknown = sorted(set(raw) - fields)
if unknown:
raise ConnectorError(f"campos desconocidos en 'derived': {unknown}")
return {field: rule_from(rule, separator=" ") for field, rule in raw.items()}
+160
View File
@@ -0,0 +1,160 @@
"""Matching OCR-discovered captions against a project's catalog, and
minting new catalog entries when nothing matches well enough.
`discover_captions` (Extraction) finds `caption: value` lines no known
`FieldSpec` already explains. For each one, this module decides whether an
existing `resultado_id` means the same thing closely enough to reuse
(`rapidfuzz`, tolerant of how a hospital's own report wording differs from
the catalog's own), or whether it's a field the catalog doesn't have yet —
in which case it's added (`add_resultado`), never silently dropped.
"""
import re
import unicodedata
from dataclasses import dataclass
from rapidfuzz import fuzz, process
from extraction.nlp import DiscoveredField
from extraction.nlp.text import find_date, fold
from webapi.orchestration.reference.catalogs import Catalogo, add_resultado
from webapi.orchestration.silver.procedures import valor_de_observacion
# `token_sort_ratio`, not `WRatio`: `WRatio`'s partial-alignment bonus scores
# two short, unrelated captions that merely share common words ("de", "del")
# too high for this use (two genuinely different captions can clear 80).
# Lower than `extraction.nlp.extractors.FUZZY_LABEL_THRESHOLD` (0-100 scale
# here, that one 0-1): a caption is free text, not a single known label
# tolerating only OCR noise, so it varies more from the catalog's wording.
CAPTION_MATCH_THRESHOLD = 80.0
CAPTION_SCORER = fuzz.token_sort_ratio
FALLBACK_ESTUDIO_ID = "documento_externo"
FALLBACK_ESTUDIO_ETIQUETA = "Documento externo"
@dataclass(frozen=True)
class MatchedField:
"""One discovered caption, resolved to a `resultado_id` (existing or
just minted) with its value already shaped for `observacion`."""
resultado_id: str
is_new: bool
observacion: dict
@dataclass(frozen=True)
class _NewResultado:
resultado_id: str
tipo_valor: str
def match_or_mint(
discovered: list[DiscoveredField],
*,
proyecto: str,
catalogo: Catalogo,
estudio_id: str | None = None,
mint: bool = True,
) -> list[MatchedField]:
"""One `MatchedField` per discovered caption, in order. With
`mint=False`, a caption nothing in the catalog matches is left out
instead of being added to the catalog file.
`estudio_id`, when the caller already knows it (the row's own
study-type column, resolved through `codigos_hospital`), scopes which
resultados are tried first and which estudio a minted field joins;
without it, every resultado in the catalog is a candidate and a new
field's estudio is guessed the same way, or falls back to
`documento_externo`.
"""
labels = _resultado_labels(catalogo, estudio_id)
valid_codes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
by_resultado_id = {r.resultado_id: r for r in catalogo.resultados}
resolved = []
for field in discovered:
found = _best_match(field.caption, labels)
if found is not None:
resultado, is_new = by_resultado_id[found], False
elif not mint:
continue
else:
resultado = _mint(field, proyecto=proyecto, estudio_id=estudio_id, catalogo=catalogo)
is_new = True
value = _coerce_value(field.value, resultado.tipo_valor)
observacion = valor_de_observacion(
value,
field.value,
tipo_valor=resultado.tipo_valor,
en_catalogo=lambda v, r=resultado.resultado_id: (r, v) in valid_codes,
)
resolved.append(MatchedField(resultado.resultado_id, is_new, observacion))
return resolved
def _resultado_labels(catalogo: Catalogo, estudio_id: str | None) -> dict[str, str]:
resultados = catalogo.resultados
if estudio_id is not None:
of_estudio = [r for r in resultados if r.estudio_id == estudio_id]
if of_estudio:
resultados = of_estudio
return {r.resultado_id: fold(r.etiqueta) for r in resultados}
def _best_match(caption: str, labels: dict[str, str]) -> str | None:
if not labels:
return None
found = process.extractOne(fold(caption), labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
return found[2] if found is not None else None
def _mint(field: DiscoveredField, *, proyecto: str, estudio_id: str | None, catalogo: Catalogo) -> _NewResultado:
estudio = estudio_id
estudio_etiqueta = None
if estudio is None:
estudio_labels = {e.estudio_id: fold(e.etiqueta) for e in catalogo.estudios}
found = process.extractOne(fold(field.caption), estudio_labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
estudio = found[2] if found is not None else None
if estudio is None:
estudio, estudio_etiqueta = FALLBACK_ESTUDIO_ID, FALLBACK_ESTUDIO_ETIQUETA
tipo_valor = _infer_tipo_valor(field.value)
resultado_id = add_resultado(
proyecto,
estudio_id=estudio,
nombre=_slug(field.caption),
etiqueta=field.caption.strip(),
tipo_valor=tipo_valor,
estudio_etiqueta=estudio_etiqueta,
)
return _NewResultado(resultado_id, tipo_valor)
def _slug(text: str) -> str:
without_accents = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
return re.sub(r"[^a-z0-9]+", "_", without_accents.lower()).strip("_") or "campo"
def _infer_tipo_valor(value: str) -> str:
if find_date(value) is not None:
return "fecha"
if _is_number(value):
return "numero"
return "texto"
def _is_number(value: str) -> bool:
try:
float(value.strip().replace(",", "."))
return True
except ValueError:
return False
def _coerce_value(value: str, tipo_valor: str):
if tipo_valor == "fecha":
found = find_date(value)
return found[0] if found else None
if tipo_valor in ("numero", "booleano"):
try:
return float(value.strip().replace(",", "."))
except ValueError:
return None
return value
+28 -1
View File
@@ -8,7 +8,17 @@ import typing
from datetime import date, datetime
from extraction.nlp import FieldKind, FieldSpec
from extraction.nlp.vocabulary import CLINICAL_TERMS, FREE_TEXT_FIELDS, PATTERNS, labels_for
from extraction.nlp.vocabulary import (
ANCHORS,
CLINICAL_TERMS,
FREE_TEXT_FIELDS,
NEGATED_VALUES,
PATTERNS,
SEVERITY,
SUBJECTS,
UNITS,
labels_for,
)
from webapi.imports.schemas.registry import EntitySpec
# Surrogate keys, stored files and OCR bookkeeping are never read from a document.
@@ -42,11 +52,28 @@ def field_specs_for(entity: EntitySpec, *, key_pattern: str | None = None) -> li
scan_free_text=name in FREE_TEXT_FIELDS or (pattern is not None and pattern == key_pattern),
multiline=kind is FieldKind.TEXT and bool(_LONG_TEXT.search(name)),
required=info.is_required(),
anchors=ANCHORS.get(name, ()),
severity=SEVERITY.get(name, ()),
negated_value=NEGATED_VALUES.get(name),
unit=UNITS.get(name),
)
)
return specs
def subject_for(entity: EntitySpec) -> tuple[str, ...]:
"""What a document feeding this entity is about (`vocabulary.SUBJECTS`)."""
return SUBJECTS.get(entity.model.__table__.name, ())
def foreign_subjects_for(entity: EntitySpec) -> tuple[str, ...]:
"""What documents feeding other entities are about, less this one's own terms."""
own = set(subject_for(entity))
if not own:
return ()
return tuple(sorted({term for table, terms in SUBJECTS.items() if table != entity.model.__table__.name for term in terms} - own))
def key_field_for(entity: EntitySpec) -> str | None:
"""The field that identifies whose record a page belongs to."""
fields = entity.schema.model_fields
@@ -15,3 +15,4 @@ class OrdenesEstudioImportSchema(ImportSchema):
ord_id_hospital: OptionalStr = None
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
ord_fecha: FlexDate = None
ord_pdf_blob: Optional[bytes] = None
@@ -0,0 +1,123 @@
"""Writes the catalog-fallback fields a document source's records carry
(captions no known `FieldSpec` claimed, see `extraction.nlp.discovery`)
into the silver layer directly: one synthetic `procedimiento` per record
per estudio its resolved fields touch, with their `observacion`s matched
against the project's catalog (`catalog_matching`). Only a source that
asks for it (`catalog_fallback`) gets here, and only captions the catalog
already knows are written: the catalog is versioned with the code, so a
running import never adds to it. Captions nothing matches are counted;
the import report lists them (`webapi.imports.audit`).
There is no staging row for these — the whole point is a field outside
today's structured schemas — so this bypasses `DESDE_STAGING` and writes
straight through the domain's existing `carga_repository`, the same one
`webapi.orchestration`'s `load` step uses for staging-derived batches.
Marked clearly apart from every staging-derived procedimiento:
`fuente_tabla` is the sentinel `FUENTE_CATALOGO_ABIERTO`, never a real
staging table name. `fuente_id` is the record's own natural key (not a SQL
row's surrogate id), so reprocessing the same record later — read again
from the SQL source, re-uploaded as a file, or corrected by hand — updates
the same rows in place instead of duplicating them; the structured fields
a source also carries keep going through the unmodified staging/import
path (`commit_sources`), independently of this.
"""
from collections import defaultdict
from dataclasses import dataclass
from importlib import import_module
from extraction import ExtractedRecord
from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint
from webapi.orchestration.reference.catalogs import Catalogo, catalogo_desde_toml, ruta_de_catalogo
from webapi.orchestration.silver.procedures import LotePlata
from webapi.orchestration.tables import tablas_de
FUENTE_CATALOGO_ABIERTO = "catalogo_abierto"
@dataclass
class CatalogCommitResult:
proyecto: str
records_written: int = 0
records_without_patient: int = 0
fields_matched: int = 0
fields_minted: int = 0
fields_unmatched: int = 0
def commit_discovered_fields(
records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None, mint: bool = False
) -> CatalogCommitResult:
"""A patient without a row in `persona` is counted and skipped: this
path only fills in fields for a patient already known, it doesn't
create one. `mint` lets unmatched captions become new catalog entries,
written to the catalog file; the import path never sets it."""
dominio = import_module(f"persistance.{proyecto}")
tablas = tablas_de(proyecto)
ruta = ruta_de_catalogo(proyecto)
catalogo = catalogo_desde_toml(ruta, tablas=tablas)
result = CatalogCommitResult(proyecto=proyecto)
procedures, observations = [], []
for record in records:
if not record.discovered or record.key is None:
continue
patients = dominio.paciente_repository.list(pac_id_hospital=record.key, limit=1)
if not patients:
result.records_without_patient += 1
continue
pac_id = patients[0].pac_id
matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id, mint=mint)
result.fields_unmatched += len(record.discovered) - len(matched)
if not matched:
continue
if any(field.is_new for field in matched):
catalogo = catalogo_desde_toml(ruta, tablas=tablas) # so a later record in this batch can match it too
matched = _fold_duplicates(matched)
by_estudio: dict[str, list] = defaultdict(list)
for field in matched:
by_estudio[field.resultado_id.split(".", 1)[0]].append(field)
result.fields_minted += int(field.is_new)
result.fields_matched += int(not field.is_new)
for estudio, fields in by_estudio.items():
key = (FUENTE_CATALOGO_ABIERTO, record.key, estudio, "reporte")
procedures.append({"llave": key, "padres": [], "pac_id": pac_id, "fecha": None, "fecha_del_padre": False})
observations += [
{"procedimiento": key, "pac_id": pac_id, "resultado_id": field.resultado_id, **field.observacion}
for field in fields
]
result.records_written += 1
if procedures:
_sync_catalog(dominio, proyecto, tablas)
dominio.carga_repository.save_load(
fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {})
)
return result
def _fold_duplicates(matched: list[MatchedField]) -> list[MatchedField]:
"""A record's discovered captions can repeat the same resultado_id (a
static label such as "FECHA" printed on several pages): `observacion`
has one row per `(procedimiento, resultado_id)`, so only the first
occurrence survives. `discover_captions` keeps every repeat on purpose
and leaves folding to the caller (see its docstring)."""
seen: set[str] = set()
folded = []
for field in matched:
if field.resultado_id in seen:
continue
seen.add(field.resultado_id)
folded.append(field)
return folded
def _sync_catalog(dominio, proyecto: str, tablas) -> None:
"""A field minted by `match_or_mint` only exists in the TOML until this
runs: `procedimiento.estudio_id` and `observacion`'s catalog both need
the matching `cat_estudio`/`cat_resultado` row to already be there."""
catalogo: Catalogo = catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas)
dominio.catalog_repository.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
+163 -6
View File
@@ -8,6 +8,8 @@ sources of a batch target the same domain and the batch is written in one
transaction: it lands completely or not at all.
"""
from dataclasses import dataclass, field
from collections import Counter
from itertools import islice
from typing import Any, Iterator
from sqlalchemy.exc import SQLAlchemyError
@@ -15,9 +17,20 @@ from sqlalchemy.exc import SQLAlchemyError
from persistance.repository import ConflictPolicy
from webapi.imports.audit import ImportAudit
from webapi.imports.connectors import Connector, ConnectorError, build_connector
from webapi.imports.connectors.document import (
CONFIDENCE_COLUMN,
DOCUMENT_COLUMN,
IMAGE_COLUMN,
SOURCES_COLUMN,
DocumentConnector,
connector_for_batch,
)
from webapi.imports.connectors.document_columns import DocumentColumns
from webapi.imports.mapping.derived import Derivation, parse_derived
from webapi.imports.schemas.registry import ENTITY_REGISTRY, EntitySpec
from webapi.imports.schemas.service import BatchValidationResult, validate_rows
from webapi.imports.services.link_resolver import LinkResolver, dependency_rank
from webapi.imports.services.review_learning import learn_from_reviews
class ImportRequestError(Exception):
@@ -40,6 +53,8 @@ class ImportSource:
defaults: dict[str, Any]
payload: dict[str, Any]
label: str | None = None
derived: dict[str, Derivation] = field(default_factory=dict)
documents: dict[str, Any] | None = None
@classmethod
def parse(cls, raw: Any) -> "ImportSource":
@@ -60,11 +75,24 @@ class ImportSource:
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
if unknown:
raise ImportRequestError(f"{target} no tiene los campos {unknown}")
targets = list(mapping.values())
try:
derived = parse_derived(raw.get("derived"), fields)
except ConnectorError as exc:
raise ImportRequestError(str(exc)) from exc
targets = list(mapping.values()) + list(derived)
duplicated = sorted({t for t in targets if targets.count(t) > 1})
if duplicated:
raise ImportRequestError(f"más de una columna de origen asignada a {duplicated}")
if not mapping and not defaults:
documents = raw.get("documents") or None
if documents is not None:
try:
DocumentColumns.parse(documents)
except ConnectorError as exc:
raise ImportRequestError(str(exc)) from exc
file_field = documents.get("file_field")
if file_field and file_field not in fields:
raise ImportRequestError(f"{target} no tiene el campo {file_field!r}")
if not mapping and not defaults and not derived and not documents:
raise ImportRequestError(f"la fuente de {target} no asigna ninguna columna")
payload = raw.get("payload")
@@ -78,6 +106,8 @@ class ImportSource:
defaults=defaults,
payload=payload,
label=raw.get("label"),
derived=derived,
documents=documents,
)
@property
@@ -94,12 +124,106 @@ class ImportSource:
except ConnectorError as exc:
raise ImportRequestError(str(exc)) from exc
@property
def source_columns(self) -> set[str]:
"""Every source column the mapping, the derived fields and the
document columns read."""
columns = set(self.column_mapping)
for rule in self.derived.values():
columns |= rule.columns()
if self.documents:
columns |= DocumentColumns.parse(self.documents).source_columns()
return columns
def _mapped(self, raw: dict[str, Any]) -> dict[str, Any]:
row = {target: raw.get(column) for column, target in self.column_mapping.items()}
for field_name, rule in self.derived.items():
row[field_name] = rule.apply(raw)
return row
def document_connector(
self, raw_rows: list[dict[str, Any]] | None = None
) -> tuple[DocumentConnector | None, list[dict[str, Any]], dict[str, dict[str, Any]]]:
"""For a source with `documents`: the extraction over its document
cells, the rows that had none (as read) and, per document, the row
it came from. Values the mapping and `derived` take from the row's
own columns go to the extraction as values to trust."""
if raw_rows is None:
raw_rows = list(self.connector().read_rows({column: column for column in self.source_columns}))
spec = DocumentColumns.parse(self.documents)
batch = spec.assemble(raw_rows, [self._mapped(raw) for raw in raw_rows])
raw_by_document = {name: raw_rows[number - 1] for name, number in batch.row_numbers.items()}
with_documents = set(batch.row_numbers.values())
plain = [raw for number, raw in enumerate(raw_rows, start=1) if number not in with_documents]
if not batch.files:
return None, plain, raw_by_document
return connector_for_batch(batch, self.target, self.documents), plain, raw_by_document
def record_namespaces(self, raw_rows: list[dict[str, Any]] | None = None) -> Iterator[tuple[dict[str, Any], dict[str, Any]]]:
"""Per record of a source with `documents`: everything known about
it by column name (its rows' own columns first, then every field
and caption its documents gave) and what extraction produced."""
connector, plain, raw_by_document = self.document_connector(raw_rows)
if connector is not None:
for extracted, documents in connector.record_rows():
namespace: dict[str, Any] = {}
for name in documents:
for key, value in raw_by_document.get(name, {}).items():
if _is_blank(namespace.get(key)):
namespace[key] = value
for key, value in extracted.items():
if _is_blank(namespace.get(key)):
namespace[key] = value
yield namespace, extracted
for raw in plain:
yield raw, {}
def unused_captions(self) -> Counter:
"""For a source that reads documents: per caption its documents
print that neither a field claims nor the mapping or a derived
field uses, how many records print it. Captions only, never their
values, for the import report."""
if self.source_type == "document":
connector = self.connector()
elif self.documents:
connector, _, _ = self.document_connector()
else:
return Counter()
if not isinstance(connector, DocumentConnector):
return Counter()
used = {column.casefold() for column in self.source_columns}
counts: Counter = Counter()
for record in connector.records:
captions = {" ".join(found.caption.split()) for found in record.discovered}
counts.update(caption for caption in captions if caption.casefold() not in used)
return counts
def _document_rows(self, raw_rows: list[dict[str, Any]]) -> Iterator[dict[str, Any]]:
"""Rows of a source with document columns: the mapping and `derived`
applied to each record's namespace, so they reach what the
documents print as well as the row's own columns; then every field
extraction filled that they left empty, and the record's pages in
`file_field`."""
fields = set(self.spec.schema.model_fields)
file_field = self.documents.get("file_field")
for namespace, extracted in self.record_namespaces(raw_rows):
row = self._mapped(namespace)
for key, value in extracted.items():
if key in fields and _is_blank(row.get(key)) and not _is_blank(value):
row[key] = value
if file_field and extracted:
row[file_field] = extracted.get(DOCUMENT_COLUMN)
yield row
def rows(self) -> Iterator[dict[str, Any]]:
"""Mapped rows, with `defaults` filling any field the source left
empty or didn't map at all (a constant "dependencia" for a file that
has none, a fallback for blank cells)."""
"""Mapped rows: each mapped column under its field, each `derived`
field computed from the source columns it names, and `defaults`
filling any field still empty or not mapped at all (a constant
"dependencia" for a file that has none, a fallback for blank cells)."""
try:
for row in self.connector().read_rows(self.column_mapping):
raw_rows = self.connector().read_rows({column: column for column in self.source_columns})
mapped = self._document_rows(list(raw_rows)) if self.documents else (self._mapped(raw) for raw in raw_rows)
for row in mapped:
for field_name, value in self.defaults.items():
if _is_blank(row.get(field_name)):
row[field_name] = value
@@ -111,6 +235,9 @@ class ImportSource:
return validate_rows(self.spec.schema, self.rows())
DOCUMENT_BOOKKEEPING = {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
def _is_blank(value: Any) -> bool:
return value is None or (isinstance(value, str) and not value.strip())
@@ -135,6 +262,33 @@ def _jsonable(value: Any) -> Any:
return str(value)
def document_columns_preview(raw_source: dict[str, Any], limit: int = 20) -> dict[str, Any]:
"""The columns a source with `documents` offers to its mapping (its own
columns and every field and caption its documents print), with sample
values per record, shaped like a source preview."""
source = ImportSource.parse({**raw_source, "column_mapping": raw_source.get("column_mapping") or {}})
connector = source.connector()
own = [column.name for column in connector.preview(limit=1).columns]
raw_rows = list(connector.read_rows({column: column for column in set(own) | source.source_columns}))
names: list[str] = list(own)
rows = []
for namespace, _ in source.record_namespaces(raw_rows):
for key in namespace:
if key not in names and key not in DOCUMENT_BOOKKEEPING:
names.append(key)
if len(rows) < limit:
rows.append({key: _jsonable(value) for key, value in namespace.items() if key not in DOCUMENT_BOOKKEEPING})
columns = [{"name": name, "inferred_type": "string"} for name in names]
return {"columns": columns, "sample_rows": rows, "total_rows": None}
def mapped_sample(raw_source: dict[str, Any], limit: int = 20) -> list[dict[str, Any]]:
"""The first rows of a source as they would be written: mapping,
derived fields and defaults applied, before validation."""
source = ImportSource.parse(raw_source)
return [{name: _jsonable(value) for name, value in row.items()} for row in islice(source.rows(), max(1, limit))]
def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None) -> BatchValidationResult:
source = ImportSource.parse(raw_source)
if audit is None:
@@ -142,6 +296,7 @@ def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None
tracked = audit.source(source)
rows = list(source.rows())
tracked.observe_rows(rows)
tracked.observe_captions(source.unused_captions)
validation = validate_rows(source.spec.schema, rows)
tracked.observe_validation(validation)
return validation
@@ -251,6 +406,7 @@ def commit_sources(
source_audit.observe_rows(rows[position])
source_audit.observe_validation(validated[position][1])
source_audit.observe_warnings(merge_warnings.get(position, []))
source_audit.observe_captions(sources[position].unused_captions)
session = sources[0].spec.repository.open_session()
links = LinkResolver(session)
@@ -310,4 +466,5 @@ def commit_sources(
) from exc
finally:
session.close()
learn_from_reviews(sources)
return [results[i] for i in range(len(validated))]
@@ -7,6 +7,7 @@ import pandas as pd
from webapi.imports.connectors import Connector, ConnectorError
from webapi.imports.connectors.document import DocumentConnector
from webapi.imports.connectors.document_columns import is_document
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
from webapi.imports.connectors.tabular import columns_from_dataframe, rows_from_dataframe
from webapi.imports.mapping import column_matcher
@@ -35,9 +36,16 @@ def preview_with_suggestions(connector: Connector, target_key: str | None, *, li
"suggested_mapping": suggest_mapping([c.name for c in preview.columns], target_key),
"tables": [{"name": t.name, "options": t.options, "kind": t.kind} for t in connector.tables()],
"source_metadata": connector.metadata(),
"document_columns": document_columns(preview.columns, preview.sample_rows),
}
def document_columns(columns, rows: list[dict[str, Any]]) -> list[str]:
"""The columns whose sampled cells hold files a document reader opens,
so a client can offer to read them as documents."""
return [column.name for column in columns if any(is_document(row.get(column.name)) for row in rows)]
def detect_pdf(raw: bytes) -> dict[str, Any]:
"""Page count, whether there is a text layer, and every ruled table
pdfplumber found, best candidates first."""
@@ -72,10 +80,27 @@ def extract_pdf_regions(raw: bytes, regions: list[dict[str, Any]], *, dpi: int =
def document_report(payload: dict[str, Any]) -> dict[str, Any]:
connector = DocumentConnector.from_payload(payload)
"""The extraction report of uploaded documents, of a document source's
SQL table, or (with `source`) of the document columns of any import
source, read through that source's own mapping."""
if payload.get("source"):
from webapi.imports.services.import_service import ImportSource
connector, _, _ = ImportSource.parse(payload["source"]).document_connector()
if connector is None:
raise ConnectorError("ninguna fila de la fuente tiene documentos")
else:
connector = DocumentConnector.from_payload(payload)
preview = preview_with_suggestions(connector, connector.target, limit=500)
fields = [
{"name": spec.name, "kind": spec.kind.value, "required": spec.required, "labels": list(spec.labels)}
for spec in connector.specs
]
return {**preview, "key_field": connector.key_field, "fields": fields, "records": connector.report()}
return {
**preview,
"key_field": connector.key_field,
"fields": fields,
"records": connector.report(),
"skipped": connector.skipped,
"nlp_version": connector.nlp_version,
}
@@ -0,0 +1,64 @@
"""Learning from the corrections made while reviewing documents: once an
import is written, each document source whose records a person corrected
teaches its domain's extraction ranker (`models.io.extraction_ranker`), in
the background so the import never waits for it, one batch at a time.
`EXTRACTION_LEARNING=0` turns it off.
"""
import logging
import os
from concurrent.futures import Future, ThreadPoolExecutor
from typing import Sequence
from webapi.imports.connectors.document import DocumentConnector
LEARNING_ENV = "EXTRACTION_LEARNING"
SOURCE = "revision"
logger = logging.getLogger(__name__)
_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="extraction-learning")
def enabled() -> bool:
return os.environ.get(LEARNING_ENV, "1").strip().lower() not in ("0", "false", "no")
def _connector(source) -> DocumentConnector | None:
if source.source_type == "document":
connector = source.connector()
elif source.documents:
connector, _, _ = source.document_connector()
else:
return None
return connector if isinstance(connector, DocumentConnector) else None
def learn_from_reviews(sources: Sequence) -> list[Future]:
"""Queues one learning step per corrected document source; returns them,
for a caller that wants to wait."""
if not enabled():
return []
futures = []
for source in sources:
try:
connector = _connector(source)
if connector is None or not connector.overrides:
continue
examples, unreachable, records = connector.learning_examples()
except Exception: # noqa: BLE001 - the import is already written
logger.exception("no se pudieron preparar ejemplos de %s", getattr(source, "target", "?"))
continue
if examples:
documents = len(connector.files)
futures.append(_executor.submit(_learn, connector.domain, examples, unreachable, records, documents))
return futures
def _learn(domain: str, examples: list, unreachable: dict[str, int], records: int, documents: int) -> str | None:
from models.io.extraction_ranker import Batch, learn
try:
return learn(domain, Batch(examples, SOURCE, documents, records, unreachable))
except Exception: # noqa: BLE001
logger.exception("el ranker de extracción de %s no pudo aprender de la revisión", domain)
return None
+12 -3
View File
@@ -46,6 +46,7 @@ TOTAL = "total"
NO_DATA = "sin_dato"
AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo"
TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo"
TIMELINE_BY_CUTOFF = "linea_de_tiempo_al_corte"
OF_THE_CHOSEN = "del_elegido"
COLUMN = "columna"
STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo"
@@ -129,6 +130,9 @@ class Stratum:
`fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose
condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a
timeline `tipo` to whether there was one;
- `linea_de_tiempo_al_corte`: the same, with what the timeline held by the question's event cut-off (all of it
without one) instead of before the period's start: a patient's characteristic learned after the fact that
put her in the period, such as the stage of a cancer whose biopsy the period counts;
- `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category;
- `columna`: a column of the event model (`columna`), one value per unit; `sin_dato` when null.
"""
@@ -143,7 +147,7 @@ class Stratum:
@classmethod
def of(cls, name: str, spec: dict) -> "Stratum":
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN, COLUMN):
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, TIMELINE_BY_CUTOFF, OF_THE_CHOSEN, COLUMN):
raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered")
return cls(name, spec["tipo"], spec)
@@ -411,7 +415,8 @@ class MeasureQueries:
return joined
def _timeline(self, stratum: Stratum):
"""Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start.
"""Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start
(or, for `linea_de_tiempo_al_corte`, by the event cut-off).
Known by the knowledge cut-off, if the question has one. Joined, not correlated, so the value can be grouped
by on every engine.
@@ -422,7 +427,11 @@ class MeasureQueries:
line = table(stratum.spec["linea"], column("pac_id"), column("tipo"), column("fecha"),
column("conocida_en", FechaHoraUTC))
period = self.periods.alias(f"periodo_{stratum.name}")
conditions = [line.c.tipo.in_(kinds), line.c.fecha < period.c.inicio]
conditions = [line.c.tipo.in_(kinds)]
if stratum.kind == TIMELINE_AT_PERIOD_START:
conditions.append(line.c.fecha < period.c.inicio)
elif self.q.event_cutoff is not None:
conditions.append(line.c.fecha <= self.q.event_cutoff.isoformat())
if self.q.knowledge_cutoff is not None:
conditions.append(line.c.conocida_en <= self.q.knowledge_cutoff)
had = (select(line.c.pac_id, *(func.max(case((line.c.tipo == k, 1), else_=0)).label(k) for k in kinds))
+153
View File
@@ -0,0 +1,153 @@
"""Measuring and training document extraction against an answer key (VAR-04, VARM-05).
python -m webapi.nlp evaluate --documents <folder> --key <key.json> [--with-values] [--no-ranker]
python -m webapi.nlp train --documents <folder> --key <key.json>
The key is JSON: per document file name, per import target, per field, the right value (`null` for a field that
must stay empty); fields left out are not scored.
{"reporte_01.pdf": {"cacu.BiopsiaCervical": {"bx_cin_grado": "LIEBG", "bx_fecha_reporte": "2025-01-31"}}}
Each document is read as one record. `evaluate` prints precision, recall and F1 per field and overall, with the
domain's current ranker (`models.io.extraction_ranker`) unless `--no-ranker`; errors list which document and
field, and their values only with `--with-values`. `train` first estimates how a ranker trained on the key would do
on documents it has not seen (leaving each document out in turn), then teaches the domain's ranker the whole key and
registers it as a new DEV version, which a person promotes like any model.
"""
import argparse
import json
import sys
from pathlib import Path
from typing import Any
from extraction import DocumentExtractor, read_document
from extraction.nlp.evaluation import evaluate
from extraction.nlp.ranking import LearnedRanker, examples_for, same_value
from extraction.readers import supported_extensions
from extraction.segmentation import WholeDocument
from webapi.imports.schemas.field_specs import field_specs_for, foreign_subjects_for, key_field_for, subject_for
from webapi.imports.schemas.registry import ENTITY_REGISTRY
def _documents(folder: Path, names) -> dict[str, Any]:
extensions = tuple(supported_extensions())
found = {}
for name in names:
path = folder / name
if not path.is_file() or not path.name.lower().endswith(extensions):
raise SystemExit(f"no se encontró el documento {name} en {folder}")
found[name] = read_document(name, path.read_bytes())
return found
def _extractor(target: str, ranker) -> DocumentExtractor:
entity = ENTITY_REGISTRY.get(target)
if entity is None:
raise SystemExit(f"destino desconocido: {target}")
return DocumentExtractor(
field_specs_for(entity), key_field=key_field_for(entity), segmenter=WholeDocument(), merger=None,
subject=subject_for(entity), foreign=foreign_subjects_for(entity), ranker=ranker,
)
def _records(documents: dict[str, Any], key: dict[str, dict[str, dict[str, Any]]], rankers: dict[str, Any]):
"""Per (document, target): the extracted record."""
records = {}
for name, targets in key.items():
for target in targets:
extractor = _extractor(target, rankers.get(target.split(".", 1)[0]))
[records[(name, target)]] = extractor.extract([documents[name]])[:1] or [None]
return records
def _scores(records, key) -> dict[str, Any]:
extracted = {f"{name} · {target}": {f: v.value for f, v in record.values.items()} for (name, target), record in records.items() if record}
expected = {f"{name} · {target}": fields for name, targets in key.items() for target, fields in targets.items()}
return evaluate(extracted, expected)
def _examples(records, key) -> tuple[dict[str, list], dict[str, dict[str, int]]]:
"""Per domain, the labelled examples of every record, and per field how many right values no candidate had."""
examples: dict[str, list] = {}
unreachable: dict[str, dict[str, int]] = {}
for (name, target), record in records.items():
if record is None:
continue
domain = target.split(".", 1)[0]
specs = field_specs_for(ENTITY_REGISTRY[target])
truth = key[name][target]
examples.setdefault(domain, []).extend(examples_for(specs, record.candidates, truth))
missing = unreachable.setdefault(domain, {})
for field, value in truth.items():
if value is not None and not any(same_value(c.value, value) for c in record.candidates.get(field, ())):
missing[field] = missing.get(field, 0) + 1
return examples, unreachable
def _current_rankers(domains) -> dict[str, Any]:
from models.io.extraction_ranker import current
return {domain: current(domain) for domain in domains}
def command_evaluate(args) -> dict[str, Any]:
key = json.loads(Path(args.key).read_text())
documents = _documents(Path(args.documents), key)
domains = {target.split(".", 1)[0] for targets in key.values() for target in targets}
rankers = {} if args.no_ranker else _current_rankers(domains)
result = _scores(_records(documents, key, rankers), key).to_dict(with_values=args.with_values)
result["rankers"] = {domain: getattr(ranker, "version", None) for domain, ranker in rankers.items()}
return result
def command_train(args) -> dict[str, Any]:
from models.io.extraction_ranker import Batch, learn
key = json.loads(Path(args.key).read_text())
documents = _documents(Path(args.documents), key)
records = _records(documents, key, {})
held_out = {}
for left_out in key:
training = {k: v for k, v in records.items() if k[0] != left_out}
examples, _ = _examples(training, key)
rankers = {domain: _trained(batch) for domain, batch in examples.items()}
held_out.update({k: v for k, v in _records({left_out: documents[left_out]}, {left_out: key[left_out]}, rankers).items()})
estimate = _scores(held_out, key).to_dict()
examples, unreachable = _examples(records, key)
versions = {}
for domain, batch in examples.items():
documents_in_domain = len({name for (name, target) in records if target.startswith(f"{domain}.")})
records_in_domain = sum(1 for (_, target) in records if target.startswith(f"{domain}."))
versions[domain] = learn(domain, Batch(batch, "clave", documents_in_domain, records_in_domain, unreachable.get(domain, {})))
return {
"sin_ranker": _scores(records, key).to_dict()["global"],
"estimacion_dejando_uno_fuera": estimate["global"],
"versiones": versions,
}
def _trained(examples) -> LearnedRanker:
ranker = LearnedRanker()
ranker.learn(examples)
return ranker
def main(argv=None) -> int:
parser = argparse.ArgumentParser(prog="python -m webapi.nlp", description=__doc__.split("\n\n")[0])
commands = parser.add_subparsers(dest="command", required=True)
for name in ("evaluate", "train"):
command = commands.add_parser(name)
command.add_argument("--documents", required=True, help="carpeta con los documentos")
command.add_argument("--key", required=True, help="JSON con los valores correctos")
if name == "evaluate":
command.add_argument("--with-values", action="store_true", help="incluir los valores de cada error")
command.add_argument("--no-ranker", action="store_true", help="ordenar candidatos solo por confianza")
args = parser.parse_args(argv)
result = command_evaluate(args) if args.command == "evaluate" else command_train(args)
json.dump(result, sys.stdout, ensure_ascii=False, indent=1, default=str)
sys.stdout.write("\n")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+3 -1
View File
@@ -13,6 +13,7 @@ from datetime import date
from pathlib import Path
from webapi.orchestration.context import Context
from webapi.orchestration.estimators import live_estimators
from webapi.orchestration.runner import run
PROJECTS = ("cacu", "cama", "tea")
@@ -42,7 +43,8 @@ def main(argv: list[str] | None = None) -> None:
print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.void else 'confirmadas'}")
return
logging.basicConfig(level=logging.INFO, format="%(message)s")
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters)
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters,
estimators=live_estimators(args.project))
for paso in run(ctx, only=args.only):
print(f"{paso.name:20} {paso.seconds:6.1f} s")
+12 -2
View File
@@ -27,6 +27,7 @@ from webapi.orchestration.reference.support import (
grupos_de_edad_de,
)
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
from webapi.orchestration.reference.source_mapping import catalog_rows
from webapi.orchestration.reference.rules import (
RUTA_PARAMETROS,
leer_parametros,
@@ -66,9 +67,18 @@ def migrate(ctx: Context) -> str:
def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra."""
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra.
Then the catalog's own mappings (`cat_mapeo`, system `catalogo`): only the forms with no row yet are added, so a
mapping edited in the application survives every deploy."""
catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project))
return ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
counts = ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
mappings = ctx.repos.silver.mappings
if mappings is not None:
system, rows = catalog_rows(ctx.project, mappings)
mappings.ensure_system(system)
counts["mapeos_nuevos"] = mappings.seed(rows)
return counts
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
+81
View File
@@ -0,0 +1,81 @@
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
its domain has in production.
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
set, read from the build's exported file (the same export `python -m models cohorts export` writes), so an
estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership,
the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go
unused by design.
"""
from dataclasses import dataclass
from importlib import import_module
from typing import Any
@dataclass(frozen=True)
class Provenance:
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str | None
def como_dict(self) -> dict[str, str]:
return {key: value for key, value in self.__dict__.items() if value}
class Cin2LogisticEstimator:
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to
test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has
something to report when `estimate` calls it."""
def __init__(self, domain: str = "cacu", version: str | None = None):
self.domain = domain
self.version = version
self.desenlace = "cin2_mas"
self._provenance: Provenance | None = None
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
import mlflow.pyfunc
from persistance.settings import settings
from models.cacu.cin2_logistic.model import SETTINGS
from models.io.registry import registered_name, registry
from models.io.storage import cohorts_root, read_cohort
from models.pipelines.export_cohort import export_kit_build
from models.steps.risks import risk_rows
repos = import_module(f"persistance.{self.domain}")
url = SETTINGS["cohort"]
build_id = repos.cohort_repository.latest_build(url)
resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version)
root = cohorts_root(getattr(settings, f"{self.domain}_database_url"))
path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id)
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path))
window = SETTINGS["outcome_window_months"]
self.desenlace = f"cin2_{window}m"
self._provenance = Provenance(
modelo_nombre=registered_name(self.domain, SETTINGS["scenario"]), modelo_version=resolved.version,
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
return [tuple(row) for row in risk_rows(risks, window / 12)]
def procedencia(self) -> Provenance:
if self._provenance is None:
raise RuntimeError("estimar() runs before procedencia()")
return self._provenance
def live_estimators(domain: str) -> dict[str, Any]:
"""The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return {}
from models.cacu.cin2_logistic.model import SETTINGS
from models.io.registry import registry
try:
registry.resolve(domain, SETTINGS["scenario"])
except LookupError:
return {}
return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)}
@@ -18,6 +18,7 @@ import core
from core.indicadores.catalogos import TIPOS_DE_VALOR
from sqlmodel import SQLModel
from webapi.orchestration.reference.source_mapping import check_function, from_result
from webapi.orchestration.tables import TablasKit
# Los catálogos viven en Core, junto a los modelos de sus tablas.
@@ -54,6 +55,7 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo:
for nombre, resultado in estudio.get("resultados", {}).items():
resultado_id = f"{estudio_id}.{nombre}"
tipo_valor = _tipo_de_valor(resultado, resultado_id)
_claves_de_extraccion(resultado, resultado_id)
resultados.append(
tablas.CatResultado(
resultado_id=resultado_id,
@@ -77,6 +79,40 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo:
return Catalogo(estudios, resultados, valores)
def add_resultado(
proyecto: str, *, estudio_id: str, nombre: str, etiqueta: str, tipo_valor: str, estudio_etiqueta: str | None = None
) -> str:
"""Appends a new `resultado_id` to the project's TOML (not to the
database): a `[estudio.resultados.nombre]` table, and the `[estudio]`
table too if it didn't exist yet. The file stays the source: the next
`catalogo_desde_toml` already brings it, and whoever syncs the table
writes it.
Idempotent: if the resultado is already in the file, nothing is
written and its `resultado_id` is returned as is. `nombre` must be a
valid TOML key (whoever discovers the field builds it, e.g. from a
slug of the text found).
"""
if tipo_valor not in TIPOS_DE_VALOR:
raise CatalogoInvalido(f"{estudio_id}.{nombre}: tipo_valor {tipo_valor!r} no es uno de {', '.join(TIPOS_DE_VALOR)}.")
ruta = ruta_de_catalogo(proyecto)
existentes = _leer(ruta)
resultado_id = f"{estudio_id}.{nombre}"
if estudio_id in existentes and nombre in existentes[estudio_id].get("resultados", {}):
return resultado_id
blocks = []
if estudio_id not in existentes:
blocks.append(f'\n[{estudio_id}]\netiqueta = "{_escape(estudio_etiqueta or estudio_id)}"\n')
blocks.append(f'\n[{estudio_id}.resultados.{nombre}]\netiqueta = "{_escape(etiqueta)}"\ntipo_valor = "{tipo_valor}"\n')
with Path(ruta).open("a", encoding="utf-8") as archivo:
archivo.write("".join(blocks))
return resultado_id
def _escape(text: str) -> str:
return text.replace("\\", "\\\\").replace('"', '\\"')
def codigos_hospital(proyecto: str) -> dict[str, str]:
"""Código del hospital -> `estudio_id`, del catálogo del proyecto.
@@ -93,6 +129,60 @@ def codigos_hospital(proyecto: str) -> dict[str, str]:
return codigos
class ResultadoExtraible(NamedTuple):
"""A result read from a document's text: the captions it's printed under and, if coded, each value's spellings."""
resultado_id: str
tipo_valor: str
etiquetas_fuente: tuple[str, ...]
alias: dict[str, tuple[str, ...]] # valor -> its spellings, the label included
buscar_en_texto: bool # also as a mention anywhere in the text, without a caption
provisional: bool
def resultados_extraibles(proyecto: str) -> dict[str, ResultadoExtraible]:
"""`resultado_id` -> how it's found in a document, for every result of the catalog with `etiquetas_fuente`.
The mapping lives in the catalog so that a new caption or spelling from the laboratory is one line there:
the next load reads it, and nothing already stored is renamed.
"""
extraibles = {}
for estudio_id, estudio in _leer(ruta_de_catalogo(proyecto)).items():
for nombre, resultado in estudio.get("resultados", {}).items():
resultado_id = f"{estudio_id}.{nombre}"
_claves_de_extraccion(resultado, resultado_id)
if "etiquetas_fuente" not in resultado:
continue
extraibles[resultado_id] = ResultadoExtraible(
resultado_id=resultado_id,
tipo_valor=resultado["tipo_valor"],
etiquetas_fuente=tuple(resultado["etiquetas_fuente"]),
alias={v["valor"]: (v["etiqueta"], *v.get("alias", ())) for v in resultado.get("valores", ())},
buscar_en_texto=bool(resultado.get("buscar_en_texto", False)),
provisional=bool(resultado.get("provisional", False)),
)
return extraibles
def _claves_de_extraccion(resultado: dict, resultado_id: str) -> None:
"""The extraction keys of a result: captions as a non-empty list of texts, and its spellings a function into
its values (`source_mapping.check_function`)."""
etiquetas = resultado.get("etiquetas_fuente")
if etiquetas is not None and (not isinstance(etiquetas, list) or not etiquetas
or not all(isinstance(e, str) and e.strip() for e in etiquetas)):
raise CatalogoInvalido(f"{resultado_id}: etiquetas_fuente es una lista de textos, no vacía.")
if etiquetas is None and ("buscar_en_texto" in resultado or any("alias" in v for v in resultado.get("valores", ()))):
raise CatalogoInvalido(f"{resultado_id}: alias y buscar_en_texto solo sirven con etiquetas_fuente.")
if etiquetas is not None and resultado.get("tipo_valor") not in ("codigo", "numero", "fecha", "texto"):
raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo {resultado.get('tipo_valor')} no se extrae de texto.")
if resultado.get("buscar_en_texto") and resultado.get("tipo_valor") != "codigo":
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo se busca como mención en el texto.")
try:
check_function(from_result(resultado_id, resultado))
except ValueError as e:
raise CatalogoInvalido(str(e)) from None
def _leer(ruta: Path) -> dict:
return tomllib.loads(Path(ruta).read_text(encoding="utf-8"))
@@ -0,0 +1,158 @@
"""How a source writes the catalog's values: a partial, non-injective function into a fixed set of codes.
A source form (a spelling, an abbreviation, a lab's own code) maps to one `valor_id` of one result:
f : (source system, resultado_id, normalized form, document date) -> valor_id
- non-injective: many forms give the same code ("3+", "Positivo (score 3)" -> H3);
- partial: a form with no mapping gives nothing, and the observation keeps it as `valor_fuente`, counted as out of
catalog, until a mapping is added;
- per source system and per date: the same form may mean different codes at two labs, and a mapping applies to the
documents dated within its validity;
- into a fixed set: a mapping only names a `valor_id` the catalog defines (`cat_valor`).
For `f` to be a function, two mappings in force on the same date can't give the same key two codes:
`check_function` rejects that, and `resolve` returns nothing for a key it still finds ambiguous, so the observation
goes back to the out-of-catalog queue instead of keeping a code.
The mappings are stored in `cat_sistema_fuente` and `cat_mapeo`: the `catalogs` step seeds the catalog's own
(`catalog_rows`, system `catalogo`, always in force) and never changes a stored row, and `register` adds one after
checking it against the rows of the same form.
"""
import tomllib
from collections import defaultdict
from datetime import date, datetime, timezone
from typing import Iterable, NamedTuple
from extraction.nlp.text import fold
CATALOG = "catalogo" # the source system of the mappings written in the catalog's TOML
class SourceForm(NamedTuple):
"""One mapping: how `system` writes `value_id` of `result_id`, in force from `valid_from` to `valid_to`."""
system: str
result_id: str
form: str
value_id: str
valid_from: date | None = None # None: since always
valid_to: date | None = None # None: while current
@property
def key(self) -> tuple[str, str, str]:
return self.system, self.result_id, normalize(self.form)
def in_force(self, on: date | None) -> bool:
return on is None or ((self.valid_from is None or self.valid_from <= on)
and (self.valid_to is None or on <= self.valid_to))
class AmbiguousForm(NamedTuple):
"""Two mappings of the same key whose validities overlap and whose codes differ."""
first: SourceForm
second: SourceForm
def normalize(form: str) -> str:
"""What is compared: uppercase, without accents, single spaces."""
return " ".join(fold(form).split())
def ambiguities(rows: Iterable[SourceForm]) -> list[AmbiguousForm]:
"""Every pair of mappings that would give one key two codes on some date."""
by_key: dict[tuple, list[SourceForm]] = defaultdict(list)
for row in rows:
by_key[row.key].append(row)
found = []
for same_key in by_key.values():
for i, a in enumerate(same_key):
found += [AmbiguousForm(a, b) for b in same_key[i + 1:] if a.value_id != b.value_id and _overlap(a, b)]
return found
def check_function(rows: Iterable[SourceForm]) -> None:
"""Raises `ValueError` naming each form that maps to two codes while both mappings are in force."""
found = ambiguities(rows)
if found:
raise ValueError("; ".join(f"{a.first.result_id}: {a.first.form!r} se escribe igual para "
f"{a.first.value_id!r} y {a.second.value_id!r}" for a in found) + ".")
def resolve(rows: Iterable[SourceForm], system: str, result_id: str, form: str, on: date | None = None) -> str | None:
"""The code `form` maps to on `on` for `system`; None when no mapping in force matches it or two disagree."""
key = (system, result_id, normalize(form))
codes = {r.value_id for r in rows if r.key == key and r.in_force(on)}
return codes.pop() if len(codes) == 1 else None
def from_result(result_id: str, result: dict, system: str = CATALOG) -> list[SourceForm]:
"""A catalog result's mappings: each value's code, label and aliases, in force always."""
return [SourceForm(system, result_id, form, value["valor"])
for value in result.get("valores", ())
for form in (value["valor"], value.get("etiqueta", ""), *value.get("alias", ())) if form.strip()]
def _overlap(a: SourceForm, b: SourceForm) -> bool:
starts_before_b_ends = a.valid_from is None or b.valid_to is None or a.valid_from <= b.valid_to
b_starts_before_a_ends = b.valid_from is None or a.valid_to is None or b.valid_from <= a.valid_to
return starts_before_b_ends and b_starts_before_a_ends
# --- the mappings stored in `cat_sistema_fuente` and `cat_mapeo` ---
CATALOG_SINCE = date(1900, 1, 1) # the catalog's own mappings hold for every document
def as_source_form(row) -> SourceForm:
"""A `cat_mapeo` row as the function sees it: a study code maps to its `estudio_id`, a spelling to its value."""
return SourceForm(row.sistema_fuente_id, row.resultado_id or "", row.forma, row.valor_id or row.estudio_id,
row.vigente_desde, row.vigente_hasta)
def check_stored(same_form: list, new) -> None:
"""`SourceMappingRepository.add`'s check: a study code or a spelling stays a function with the new row. A
caption may introduce several results (a receptor and its percentage), so it isn't checked."""
if new.clase == "etiqueta":
return
check_function([as_source_form(r) for r in same_form if r.clase == new.clase] + [as_source_form(new)])
def register(repository, *, sistema_fuente_id: str, clase: str, forma: str, registrado_por: str,
vigente_desde: date, estudio_id: str | None = None, resultado_id: str | None = None,
valor_id: str | None = None, motivo: str | None = None):
"""Adds one mapping, rejected with `ValueError` if it makes a form give two codes while both are in force."""
row = repository.model(
sistema_fuente_id=sistema_fuente_id, clase=clase, forma=forma.strip(), forma_normalizada=normalize(forma),
estudio_id=estudio_id, resultado_id=resultado_id, valor_id=valor_id, vigente_desde=vigente_desde,
registrado_por=registrado_por, registrado_en=datetime.now(timezone.utc), motivo=motivo)
return repository.add(row, check=check_stored)
def catalog_rows(project: str, repository) -> tuple[object, list]:
"""The catalog's source system and its mappings, from the TOML: study codes, captions, and each value's code,
label and aliases. What `SourceMappingRepository.seed` adds when they're missing."""
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
system = repository.sistema(sistema_fuente_id=CATALOG, etiqueta="Catálogo del proyecto", fuente_tabla=None,
vigente_desde=CATALOG_SINCE)
now = datetime.now(timezone.utc)
rows = {}
def add(clase, forma, **target):
row = repository.model(sistema_fuente_id=CATALOG, clase=clase, forma=forma, forma_normalizada=normalize(forma),
vigente_desde=CATALOG_SINCE, registrado_por=CATALOG, registrado_en=now, **target)
rows.setdefault((clase, target.get("resultado_id"), target.get("estudio_id"), row.forma_normalizada), row)
for study_id, study in tomllib.loads(ruta_de_catalogo(project).read_text(encoding="utf-8")).items():
for code in study.get("codigos_hospital", ()):
add("estudio", code, estudio_id=study_id)
for name, result in study.get("resultados", {}).items():
result_id = f"{study_id}.{name}"
for caption in result.get("etiquetas_fuente", ()):
add("etiqueta", caption, resultado_id=result_id)
for form in from_result(result_id, result):
add("valor", form.form, resultado_id=result_id, valor_id=form.value_id)
return system, list(rows.values())
+3
View File
@@ -21,6 +21,7 @@ from persistance.edges.silver import (
ObservationRepository,
TimelineRepository,
LinksRepository,
SourceMappingRepository,
ViewsRepository,
)
from persistance.materializer import Materializer
@@ -43,6 +44,7 @@ class Silver:
observation: ObservationRepository
links: LinksRepository
timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it
mappings: SourceMappingRepository | None = None # how each source writes the catalog's codes
@dataclass(frozen=True)
@@ -80,6 +82,7 @@ def repositories_of(proyecto: str) -> Repositories:
observation=dominio.observation_period_repository,
links=dominio.links_repository,
timeline=dominio.timeline_repository,
mappings=dominio.source_mapping_repository,
),
materializer=dominio.materializer,
gold=Gold(
+24 -3
View File
@@ -7,6 +7,7 @@ derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
@@ -23,6 +24,23 @@ def _biopsia_que_pasa(fila) -> bool:
return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None
# Results read from text, with how the catalog says each is printed (`etiquetas_fuente`, `alias`): the
# radiologist's interpretation, the pathology report's text layer, and the note's diagnosis and prognosis.
DE_LA_INTERPRETACION = DesdeTexto(
"cama", ("mastografia.densidad", "mastografia.tamano_lesion_mm"), texto=lambda f: f.mast_interpretacion,
)
DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
"cama",
("biopsia.tipo_histologico", "biopsia.grado_nottingham", "biopsia.receptor_estrogeno",
"biopsia.receptor_estrogeno_pct", "biopsia.receptor_progesterona", "biopsia.receptor_progesterona_pct",
"biopsia.her2", "biopsia.ki67_pct"),
texto=lambda f: f.bx_pdf_blob,
)
DE_LA_NOTA = DesdeTexto(
"cama", ("nota_medica.estadio_clinico",),
texto=lambda f: "\n".join(t for t in (f.nm_diagnostico_texto, f.nm_pronostico) if t),
)
DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
@@ -33,14 +51,17 @@ DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
resultados={"mast_birads": "mastografia.birads"},
derivadas=DE_LA_INTERPRETACION.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados},
fuentes=DE_LA_INTERPRETACION.fuentes,
),
DeStaging(
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
derivadas=DEL_REPORTE_DE_PATOLOGIA.derivadas, fuentes=DEL_REPORTE_DE_PATOLOGIA.fuentes,
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
resultados={"bx_grado_histologico": "biopsia.grado"}),),
resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),),
),
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA),
)
+119
View File
@@ -0,0 +1,119 @@
"""Results of the catalog read from a staging row's text: a report's interpretation, a note, a PDF's text layer.
The catalog says how each result is printed (`etiquetas_fuente`, each value's `alias`;
`reference.catalogs.resultados_extraibles`); `DesdeTexto` turns that into Extraction's field specs and into the
derived columns, results and sources of a `DeStaging`. A coded value comes out as its `valor_id` when one of its
spellings matches, and always with what was read as `valor_fuente`: a spelling the catalog doesn't know yet stays
stored as text, counted as out of catalog by the silver check, and becomes a code on the next load after its alias
is added. Nothing extracted is written anywhere but silver's two tables.
"""
from collections.abc import Callable
from dataclasses import dataclass, field
from functools import lru_cache
from extraction import BBox, ExtractionError, FieldKind, FieldSpec, Line, read_document
from extraction.nlp.extractors import RecordExtractor, SegmentLine
from webapi.orchestration.reference.catalogs import ResultadoExtraible, resultados_extraibles
# A value read after a caption, kept as its source when the catalog doesn't know it: enough to recognize it.
LARGO_DE_FUENTE = 120
TIPOS = {"codigo": FieldKind.CHOICE, "numero": FieldKind.DECIMAL, "fecha": FieldKind.DATE, "texto": FieldKind.TEXT}
SUFIJO_DE_TEXTO = "#texto" # the plain-text twin of a coded field: what follows its caption, matched or not
def especificaciones(resultado: ResultadoExtraible) -> tuple[FieldSpec, ...]:
"""Extraction's fields for one result: the result itself and, if coded, the text after its caption."""
choices = {forma: valor for valor, formas in resultado.alias.items() for forma in formas}
campo = FieldSpec(
resultado.resultado_id, TIPOS[resultado.tipo_valor], labels=resultado.etiquetas_fuente,
choices=choices, scan_free_text=resultado.buscar_en_texto,
)
if resultado.tipo_valor != "codigo":
return (campo,)
return campo, FieldSpec(resultado.resultado_id + SUFIJO_DE_TEXTO, FieldKind.TEXT, labels=resultado.etiquetas_fuente)
def lineas_de_texto(texto: str, nombre: str = "texto") -> list[SegmentLine]:
"""A plain text as the lines of one page, as a reader would give them."""
renglones = [r for r in texto.splitlines() if r.strip()]
alto = 1 / max(len(renglones), 1)
return [SegmentLine(nombre, 1, Line(r, BBox(0, i * alto, 1, (i + 1) * alto))) for i, r in enumerate(renglones)]
def lineas_de_pdf(contenido: bytes) -> list[SegmentLine]:
"""The text layer of a PDF, without OCR: a load doesn't run OCR, and a scan without text gives no lines."""
try:
documento = read_document("documento.pdf", contenido, ocr_mode="never")
except ExtractionError:
return []
return [SegmentLine(documento.name, p.number, linea) for p in documento.pages for linea in p.lines]
@dataclass(frozen=True)
class DesdeTexto:
"""Catalog results read from what `texto` gives for a row: a text, a PDF's bytes, or nothing.
`derivadas`, `resultados` and `fuentes` go into the `DeStaging` (or its `Hija`) as they are. The row is read
once for all its results.
"""
proyecto: str
resultado_ids: tuple[str, ...]
texto: Callable[[object], str | bytes | None]
_extraer: Callable = field(init=False, repr=False, compare=False)
def __post_init__(self):
extraibles = resultados_extraibles(self.proyecto)
faltan = [r for r in self.resultado_ids if r not in extraibles]
if faltan:
raise ValueError(f"Sin etiquetas_fuente en el catálogo de {self.proyecto}: {', '.join(faltan)}.")
tipos = {r: extraibles[r].tipo_valor for r in self.resultado_ids}
extractor = RecordExtractor([e for r in self.resultado_ids for e in especificaciones(extraibles[r])])
@lru_cache(maxsize=256)
def extraer(contenido: str | bytes) -> dict[str, tuple]:
lineas = lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido)
leidos = extractor.extract(lineas)
return {r: _valor_y_fuente(leidos.get(r), leidos.get(r + SUFIJO_DE_TEXTO), tipos[r]) for r in tipos}
object.__setattr__(self, "_extraer", extraer)
def leer(self, fila) -> dict[str, tuple]:
"""`resultado_id` -> (value, source) read from the row; (None, None) when it isn't there."""
contenido = self.texto(fila)
if not contenido or (isinstance(contenido, str) and not contenido.strip()):
return dict.fromkeys(self.resultado_ids, (None, None))
return self._extraer(contenido)
@property
def derivadas(self) -> dict[str, Callable]:
columnas = {}
for r in self.resultado_ids:
columnas[_columna(r)] = lambda f, r=r: self.leer(f)[r][0]
columnas[_columna(r) + "_fuente"] = lambda f, r=r: self.leer(f)[r][1]
return columnas
@property
def resultados(self) -> dict[str, str]:
return {_columna(r): r for r in self.resultado_ids}
@property
def fuentes(self) -> dict[str, str]:
return {_columna(r): _columna(r) + "_fuente" for r in self.resultado_ids}
def _columna(resultado_id: str) -> str:
return "extraido:" + resultado_id
def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
"""A coded value with the spelling it matched, or, unmatched, with what followed its caption; others as read."""
if tipo_valor != "codigo":
return (None, None) if leido is None else (leido.value, None)
if leido is not None:
return leido.value, leido.raw
if texto is not None and str(texto.value).strip():
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
return None, None
@@ -9,11 +9,13 @@ da sus tablas y su catálogo de especialidades. Es la normalización que hacían
como llegó;
- el CIE-10 de la nota, sin espacios ni punto y en mayúsculas; su identificador del hospital, en `id_hospital`;
- el motivo de consulta y el diagnóstico en texto, solo si el proyecto los pide (`con_textos`, CaCu: T-24b),
sin normalizarlos (I-K61).
sin normalizarlos (I-K61);
- the catalog results a project reads from the note's texts (`extraidos`, CaMa's clinical stage).
"""
from collections.abc import Collection, Mapping
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio
from webapi.orchestration.silver.procedures import DeStaging
@@ -52,22 +54,26 @@ def orden_de_estudio(staging: type, alias: Mapping[str, str], codigos: Collectio
def nota_medica(
staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False
staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False,
extraidos: DesdeTexto | None = None,
) -> DeStaging:
textos = {
"motivo": lambda f: texto_limpio(f.nm_motivo_consulta),
"diagnostico_texto": lambda f: texto_limpio(f.nm_diagnostico_texto),
} if con_textos else {}
leidos = extraidos.derivadas if extraidos else {}
return DeStaging(
staging, "nm_id", "encuentro", estudio_id="nota_medica", fecha="nm_fecha",
columnas={"id_hospital": "nm_id_hospital"}, # para ligarla después con sus órdenes (provisional)
derivadas={
"cie_codigo": lambda f: cie(f.nm_cie_codigo), **especialidad("nm_especialidad", alias, codigos), **textos,
**leidos,
},
resultados={
"cie_codigo": "nota_medica.diagnostico",
"especialidad": "nota_medica.especialidad",
**({f: f"nota_medica.{f}" for f in textos}),
**(extraidos.resultados if extraidos else {}),
},
fuentes={"especialidad": "especialidad_fuente"},
fuentes={"especialidad": "especialidad_fuente", **(extraidos.fuentes if extraidos else {})},
)
+4 -4
View File
@@ -1,9 +1,9 @@
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`, only in DEV.
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`.
The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance
cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed
evaluation. Patient data: **registered only in DEV** (`DEV_REVISION`), on simulated data, and every response carries
`simulado: true`. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
evaluation. Patient data, on simulated data: every response carries `simulado: true`. The route is always registered;
who may see it is an access rule still to be defined. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
removed or renamed, only added.
"""
@@ -16,7 +16,7 @@ COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0")
def patient_risk_blueprint(repositories) -> Blueprint:
"""The blueprint, to register with `url_prefix="/cacu"` only in DEV. `repositories` is `persistance.cacu`."""
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
blueprint = Blueprint("cacu_patient_risk", __name__)
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
+52 -15
View File
@@ -1,11 +1,15 @@
"""Recomputes a domain's indicators after its staging tables change.
A successful import asks for a recomputation (`RecomputationQueue.solicitar`),
A successful import asks for a recomputation (`RecomputationQueue.request_run`),
which only drops a marker file. A separate process (`python -m
webapi.recomputation`, the `indicadores` compose service) picks the
markers up and runs that domain's cycle (`webapi.orchestration.correr`): catalogs ->
staging to facts -> views -> registry -> definitions -> reports.
Requests that arrive while a domain is running are folded into one more run.
webapi.recomputation`, the `indicadores` compose service) watches the markers'
directory and, on any change there, runs every pending domain's cycle
(`webapi.orchestration.run`): catalogs -> staging to facts -> views -> registry
-> definitions -> event models -> cohorts -> estimates, with the live estimators
of the models in production (`webapi.orchestration.estimators`). A periodic
check (`INDICADORES_INTERVALO_S`) stays as a fallback for a missed or coalesced
filesystem event; it no longer sets the normal reaction time. Requests that
arrive while a domain is running are folded into one more run.
State lives in files under `INDICADORES_DIR`: `pendiente/<dominio>` markers
and `estado.json`; each run is also appended, as counts only, to
@@ -24,6 +28,9 @@ from datetime import date, datetime, timezone
from pathlib import Path
from typing import Any
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message
DOMAINS = ("cacu", "cama", "tea") # the domains whose measures the cycle computes
@@ -99,6 +106,7 @@ class RecomputationQueue:
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
from webapi.orchestration import Context, run, steps_of
from webapi.orchestration.estimators import live_estimators
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year))
@@ -107,7 +115,7 @@ class RecomputationQueue:
self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
try:
ctx = Context(dominio, desde, hasta, allow_undecided=True)
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
entrada.update(
estado="ok",
@@ -134,22 +142,51 @@ class RecomputationQueue:
return ran
class _Waker(FileSystemEventHandler):
"""Wakes the main loop on any change in the pending-markers directory."""
def __init__(self, wake: threading.Event):
self._wake = wake
def on_any_event(self, event) -> None:
self._wake.set()
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
cola = RecomputationQueue()
interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20"))
cola._pending.mkdir(parents=True, exist_ok=True)
fallback_s = float(os.environ.get("INDICADORES_INTERVALO_S", "20"))
if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1":
for dominio in DOMAINS:
cola.request_run(dominio)
stop = threading.Event()
signal.signal(signal.SIGTERM, lambda *_: stop.set())
signal.signal(signal.SIGINT, lambda *_: stop.set())
log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base)
while True:
for dominio in cola.serve():
log.info("%s: %s", dominio, cola.status()[dominio].get("estado"))
if stop.wait(interval):
break
wake = threading.Event()
def _stop(*_):
stop.set()
wake.set()
signal.signal(signal.SIGTERM, _stop)
signal.signal(signal.SIGINT, _stop)
observer = Observer()
observer.schedule(_Waker(wake), str(cola._pending), recursive=False)
observer.start()
log.info("indicadores en vivo: observando %s (respaldo cada %.0f s)", cola._pending, fallback_s)
try:
while True:
for dominio in cola.serve():
log.info("%s: %s", dominio, cola.status()[dominio].get("estado"))
if stop.is_set():
break
wake.wait(fallback_s)
wake.clear()
if stop.is_set():
break
finally:
observer.stop()
observer.join()
if __name__ == "__main__":