Compare commits

..

27 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 10f0c59975 Reject invalid optional access callbacks 2026-11-13 18:19:39 -06:00
Angel Capetillo Zavala 1d8cd264b8 Clarify optional cohort access boundary 2026-11-13 17:56:50 -06:00
Angel Capetillo Zavala 46eb3dfc31 Use shared access for synthetic breast follow-up 2026-11-13 17:54:56 -06:00
Angel Capetillo Zavala 9c0e03f947 Remove obsolete cohort example switch 2026-11-13 17:49:44 -06:00
Angel Capetillo Zavala 6d32115eca Check startup with retained cohort settings 2026-11-13 17:47:37 -06:00
Angel Capetillo Zavala 06dd74cdb6 Verify cervical patient identity contract 2026-11-13 17:43:50 -06:00
Angel Capetillo Zavala eeb55c4255 Use source patient identity for breast follow-up 2026-11-13 17:38:19 -06:00
edgar 2ca86232c9 Follow-up list without a salt: the kit identifies each patient by pac_id 2026-11-13 17:31:07 -06:00
Angel Capetillo Zavala 8b47f1522d Connect breast follow-up to the configured cohort 2026-11-13 15:16:14 -06:00
Angel Capetillo Zavala 7bc214b50c Validate patient identity in breast cohort links 2026-11-13 14:52:55 -06:00
Angel Capetillo Zavala 1d5f1e0cc4 Add synthetic breast cohort reconciliation 2026-11-13 13:27:18 -06:00
Angel Capetillo Zavala ca54656124 Add breast cancer follow-up export and patient endpoints 2026-11-12 22:40:22 -06:00
Angel Capetillo Zavala 102999c8de Verify CaMa publication without demonstration labels 2026-11-12 11:57:45 -06:00
Angel Capetillo Zavala 7798d007d1 Update synthetic diagnosis publication expectations 2026-11-12 11:15:36 -06:00
Angel Capetillo Zavala c72c03988e Align synthetic CaMa follow-up contract 2026-11-12 11:15:22 -06:00
Angel Capetillo Zavala 91537e9efd Test and document CaMa histopathology publication 2026-11-12 10:38:34 -06:00
Angel Capetillo Zavala f11abd8f6e Test publication of CaMa demonstration measures 2026-11-12 10:16:38 -06:00
Angel Capetillo Zavala 6afe329e52 Add synthetic CaMa follow-up endpoint 2026-11-12 10:06:17 -06:00
Roberto Treviño Cervantes 96a29cfb19 import files in columns 2026-11-11 11:09:48 -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
edgar f74ccf5496 uv.lock records the dependencies models adds: pandas, pandera, pyarrow and scikit-learn 2026-11-06 08:29:05 -06:00
edgar 72a8e76108 GET /cacu/pacientes/<pac_id>/riesgo, only in DEV: the patient's cohort membership and risks in the current batch, in the WebApp's contract 2026-11-06 08:21:38 -06:00
edgar 01ac568c22 Merge pull request 'Models round-trip test imports resolve_repository from models.io.storage' (#9) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/9
2026-11-06 05:38:03 +00:00
angel 429275547b Merge pull request 'fix: synchronize locked dependency metadata' (#8) from fix/134-uv-lock into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApi/pulls/8
2026-11-06 04:58:43 +00:00
edgar fad503ef56 Models round-trip test imports resolve_repository from models.io.storage 2026-11-05 16:12:23 -06:00
29 changed files with 2538 additions and 50 deletions
+9
View File
@@ -96,3 +96,12 @@ uv run pytest -q
Las pruebas contra MySQL en vivo se activan con `MYSQL_TEST_URL`; sin ella
se omiten.
### Seguimiento CaMa sintético
El lector usa la base configurada por `CAMA_DATABASE_URL` y publica el
`pac_id` de la plataforma como cadena decimal, con ámbito limitado a esa base
y dominio. Las rutas por paciente usan el mismo acceso de la aplicación que
Seguimiento CaCu. Los parámetros de corte, ventana y selección, la revisión, la
supresión y los ejemplos de listado, ficha y exportación se describen en
[el contrato de cohorte](docs/cama-cohort-api.md).
+477
View File
@@ -0,0 +1,477 @@
{
"id": "cama_histopatologia_birads",
"titulo": "Histopatología por BI-RADS (demostración sintética)",
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": "birads",
"valores_estrato": [
"BIRADS_4",
"BIRADS_4A",
"BIRADS_4B",
"BIRADS_4C",
"BIRADS_5",
"BIRADS_6"
],
"etiquetas_estrato": {
"BIRADS_4": "BI-RADS 4 sin subtipo",
"BIRADS_4A": "BI-RADS 4A",
"BIRADS_4B": "BI-RADS 4B",
"BIRADS_4C": "BI-RADS 4C",
"BIRADS_5": "BI-RADS 5",
"BIRADS_6": "BI-RADS 6"
},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"BENIGNO": {
"etiqueta": "Benigno",
"color": "#9DBFE3",
"grupo": "NO_MALIGNO",
"gravedad": 1
},
"RIESGO_B3": {
"etiqueta": "Lesión de riesgo (B3)",
"color": "#2F6DB3",
"grupo": "NO_MALIGNO",
"gravedad": 2
},
"IN_SITU": {
"etiqueta": "Carcinoma in situ",
"color": "#D9822B",
"grupo": "MALIGNO",
"gravedad": 3
},
"INVASOR": {
"etiqueta": "Carcinoma invasor",
"color": "#B5482E",
"grupo": "MALIGNO",
"gravedad": 4
},
"SIN_BIOPSIA": {
"etiqueta": "Sin biopsia reportada",
"color": "#C9CDD2",
"grupo": null,
"gravedad": null
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_MALIGNO": "No maligno",
"MALIGNO": "Maligno",
"SIN_DATO": "Sin dato"
},
"notas": [
"Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 141,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2025-12-31",
"generado_en": "2026-11-12T16:33:37.621606+00:00",
"kit_version": "0.8.0",
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
"parametros": {
"sql": {
"_catalogo": [
"BENIGNO",
"RIESGO_B3",
"IN_SITU",
"INVASOR"
],
"_grupos": [
"TOTAL"
],
"fecha_corte": "2025-12-31",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 5
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "BENIGNO",
"n": 2,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "RIESGO_B3",
"n": 0,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "INVASOR",
"n": 2,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
}
],
"totales_estrato": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"n": 7,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"n": 6,
"suprimido": 0
}
]
}
+150
View File
@@ -0,0 +1,150 @@
{
"id": "cama_histopatologia_birads",
"titulo": "Histopatología por BI-RADS (demostración sintética)",
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": null,
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"BENIGNO": {
"etiqueta": "Benigno",
"color": "#9DBFE3",
"grupo": "NO_MALIGNO",
"gravedad": 1
},
"RIESGO_B3": {
"etiqueta": "Lesión de riesgo (B3)",
"color": "#2F6DB3",
"grupo": "NO_MALIGNO",
"gravedad": 2
},
"IN_SITU": {
"etiqueta": "Carcinoma in situ",
"color": "#D9822B",
"grupo": "MALIGNO",
"gravedad": 3
},
"INVASOR": {
"etiqueta": "Carcinoma invasor",
"color": "#B5482E",
"grupo": "MALIGNO",
"gravedad": 4
},
"SIN_BIOPSIA": {
"etiqueta": "Sin biopsia reportada",
"color": "#C9CDD2",
"grupo": null,
"gravedad": null
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_MALIGNO": "No maligno",
"MALIGNO": "Maligno",
"SIN_DATO": "Sin dato"
},
"notas": [
"Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 141,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2025-12-31",
"generado_en": "2026-11-12T16:33:37.621606+00:00",
"kit_version": "0.8.0",
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
"parametros": {
"sql": {
"_catalogo": [
"BENIGNO",
"RIESGO_B3",
"IN_SITU",
"INVASOR"
],
"_grupos": [
"TOTAL"
],
"fecha_corte": "2025-12-31",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 5
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "BENIGNO",
"n": 7,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "RIESGO_B3",
"n": 5,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "IN_SITU",
"n": 6,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "INVASOR",
"n": 7,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "SIN_BIOPSIA",
"n": 6,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "SIN_DATO",
"n": 6,
"orden": 5,
"suprimido": 0
}
],
"totales_estrato": []
}
+75
View File
@@ -0,0 +1,75 @@
# Breast cohort: synthetic integration contract
This contract is for a synthetic source. The application reads the configured
CaMa database through the shared persistence settings. Patient routes have
the same application access boundary as CaCu follow-up; an optional access
callback can apply an additional boundary. An unavailable reader returns 503.
Authorization for real patient data has not been implemented.
`GET /cama/analisis/indicadores?corte=2026-10-20` returns a descriptive count
by BI-RADS. It includes `cohorte`, `revision`, `escenario`, `corte`,
`umbral_supresion`, `unidad`, `denominador` and `grupos`. A sample group is
`{"codigo":"BIRADS_5","n":6,"suprimido":false}`. A suppressed group's `n`
is null. The prototype's required `indicadores` array is empty: the new
`grupos` is a count distribution, not an incidence or survival estimate.
No survival, recurrence, subgroup grid or other analysis endpoints are supplied.
One patient contributes once: choose the latest mammogram with a BI-RADS report
available by cutoff; then include it if BI-RADS is 4, 4A, 4B, 4C, 5 or 6.
`revision` is a digest of the materialized cohort, including its data and stable
patient identifiers. It is an integrity marker, not an authorization credential.
For each patient request send `cohorte=cama_birads_v1`, `escenario=diagnostico`,
the exact `revision` and `corte` from the aggregate, `meses`, and any selected
`birads` or `grupo_edad`. For example:
```
GET /cama/seguimiento?cohorte=cama_birads_v1&escenario=diagnostico&revision=<revision>&corte=2026-10-20&meses=0&birads=BIRADS_5
```
For the same selected population use the same query on
`/cama/seguimiento/exportacion` or `/cama/pacientes/<pac_id>`; list
accepts `page` and `page_size` (maximum 200). Export is limited to 5,000.
`meses=0` means the whole eligible cohort through cutoff. Its inclusive
`desde` is the earliest eligible mammography date before filtering; when the
cohort is empty it is the cutoff. `hasta` is the inclusive cutoff. Windows 1,
3, 6 and 12 retain their calendar-month semantics.
Regular follow-up accepts the same window and filters without cohort context;
it reads the same source, checks access and returns its cohort context and
revision. When omitted, cutoff is the server's current date and the window is
three months. Quote the returned context in subsequent page, detail and export
requests to pin them to that revision. The old independent fixture, status and
priority filters are no longer served; these values cannot be derived safely
from the available records.
BI-RADS codes are `BIRADS_4`, `BIRADS_4A`, `BIRADS_4B`, `BIRADS_4C`,
`BIRADS_5`, `BIRADS_6`. Age options are `MENOR_40`, `40-49`, `50-59`,
`60-69`, `70+`, `SIN_DATO`. Filters combine with AND. Unknown, duplicated or
invalid parameters return 400. A filtered group with fewer than five patients,
or a nonempty whole cohort smaller than five, returns 403; empty unfiltered
cohorts return an empty page. A revision mismatch returns 409; absent detail
returns 404, an unavailable reader returns 503 and oversized exports return 413.
An optional access callback is checked independently of suppression. Responses
containing patient data carry `Cache-Control: no-store`.
The source uses the kit's silver mammography and biopsy queries. A biopsy must
be linked through its order to the selected mammogram and patient. Clinical
dates and load start timestamps are distinct fields. Procedure and observation
load timestamps must be no later than the UTC cutoff day. Silver stores only
the current row: a historical value overwritten later cannot be reconstructed,
and the person table does not version date of birth. Therefore this contract
does not certify a historical snapshot. Revision detects changes between
requests but does not persist the previous cohort. The current implementation
materializes the full cohort in memory and has not been sized for production.
The local example `examples/serve_cama_cohort.py` accepts an existing synthetic
SQLite file in `CAMA_SYNTHETIC_SQLITE`, opens it read-only, binds to loopback,
and does not require cohort-specific environment variables.
Other domain database URLs are set to isolated in-memory SQLite by the example.
The Windows-only `fcntl` shim raises if locking is attempted: this example does
not validate file-locking functionality.
`examples/serve_cama_integration.py` runs normal application configuration
against an existing disposable SQLite copy, bound to loopback. It is suitable only
for local synthetic integration and does not provide production authentication.
+51
View File
@@ -0,0 +1,51 @@
"""Run the cohort endpoints locally against an explicitly supplied synthetic SQLite file."""
import os
from pathlib import Path
import sqlite3
from urllib.parse import quote
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
if os.name == 'nt':
import sys
import types
fcntl = types.ModuleType('fcntl')
fcntl.LOCK_EX, fcntl.LOCK_UN = 2, 8
def unavailable(*args):
raise RuntimeError('File locking is unavailable in this local Windows example')
fcntl.flock = unavailable
sys.modules['fcntl'] = fcntl
path = Path(os.environ['CAMA_SYNTHETIC_SQLITE']).resolve(strict=True)
if not path.is_file():
raise ValueError('The synthetic SQLite database must already exist')
# The cohort reader can only open the named file in read-only mode.
uri = 'file:' + quote(path.as_posix(), safe='/:') + '?mode=ro'
engine = create_engine('sqlite://', creator=lambda: sqlite3.connect(uri, uri=True))
# The other application blueprints must not inherit a live database URL.
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:'
from webapi import create_app
from webapi.cama_cohort import CamaCohort
app = create_app()
def read(cutoff):
with Session(engine) as session:
return CamaCohort(session).rows(cutoff)
app.config['CAMA_COHORT_READER'] = read
if __name__ == '__main__':
app.run(host='127.0.0.1', port=int(os.environ.get('CAMA_COHORT_PORT', '5059')), debug=False)
+34
View File
@@ -0,0 +1,34 @@
"""Serve an isolated synthetic database through a loopback-only test proxy."""
import argparse
import os
from pathlib import Path
import sys
import types
parser = argparse.ArgumentParser()
parser.add_argument('--database', required=True, help='Existing disposable synthetic SQLite database')
parser.add_argument('--port', type=int, default=5059)
args = parser.parse_args()
database = Path(args.database).resolve(strict=True)
if not database.is_file():
raise ValueError('The synthetic database must be an existing file')
os.environ.update(CAMA_DATABASE_URL='sqlite:///' + database.as_posix(),
MLFLOW_DISABLE_AGENT_HINT='1',
MLFLOW_DISABLE_TELEMETRY='true')
for domain in ('CACU', 'TEA', 'GOVERNANCE'):
os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:'
if os.name == 'nt':
fcntl = types.ModuleType('fcntl')
fcntl.LOCK_EX, fcntl.LOCK_UN = 2, 8
def unavailable(*_args):
raise RuntimeError('POSIX locking is unavailable in this Windows test harness')
fcntl.flock = unavailable
sys.modules['fcntl'] = fcntl
from webapi import create_app
from werkzeug.serving import make_server
app = create_app()
print(f'Isolated synthetic test proxy: http://127.0.0.1:{args.port}', flush=True)
make_server('127.0.0.1', args.port, app, threaded=True).serve_forever()
+184
View File
@@ -0,0 +1,184 @@
"""Exercise cohort selection with isolated synthetic silver rows and Flask clients."""
from datetime import date, datetime, timezone
import pytest
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from indicadores_kit.cama.tablas import TABLAS
from webapi.cama_analysis import analysis
from webapi.cama_cohort import CamaCohort
from webapi.seguimiento_cama import blueprint_seguimiento_cama
@pytest.fixture
def cohort_db():
"""Six eligible people, one linked biopsy and one biopsy without a link."""
t = TABLAS
engine = create_engine('sqlite:///:memory:')
for model in (t.Persona, t.Carga, t.Procedimiento, t.Observacion):
model.__table__.create(engine)
with Session(engine) as session:
session.add_all([
t.Carga(carga_id=1, fuente='test', inicio=datetime(2025, 1, 1, tzinfo=timezone.utc)),
t.Carga(carga_id=2, fuente='test', inicio=datetime(2027, 1, 1, tzinfo=timezone.utc)),
])
for patient in range(1, 7):
session.add(t.Persona(pac_id=patient, pac_id_hospital=f'T-{patient}', fecha_nacimiento=date(1970, 1, 1)))
session.add(t.Procedimiento(procedimiento_id=patient * 10, fuente_tabla='mastografia', fuente_id=str(patient),
carga_id=1, pac_id=patient, estudio_id='mastografia', clase='toma', fecha=date(2025, 2, 1)))
session.add(t.Procedimiento(procedimiento_id=patient * 10 + 1, padre_id=patient * 10, fuente_tabla='mastografia',
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='mastografia',
clase='reporte', fecha=date(2025, 2, 2)))
session.add(t.Observacion(observacion_id=patient, procedimiento_id=patient * 10 + 1, carga_id=1,
pac_id=patient, resultado_id='mastografia.birads', valor_fuente='B5'))
for patient, parent, load in ((1, 10, 1), (2, None, 1), (3, 30, 2), (4, 40, 1)):
report_date = date(2027, 2, 15) if patient == 4 else date(2025, 2, 15)
session.add(t.Procedimiento(procedimiento_id=100 + patient * 2, padre_id=parent, fuente_tabla='biopsiamama',
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='biopsia',
clase='orden', fecha=date(2025, 2, 10)))
session.add(t.Procedimiento(procedimiento_id=101 + patient * 2, padre_id=100 + patient * 2,
fuente_tabla='biopsiamama', fuente_id=str(patient), carga_id=1, pac_id=patient,
estudio_id='biopsia', clase='reporte', fecha=report_date))
session.add(t.Observacion(observacion_id=100 + patient, procedimiento_id=101 + patient * 2, carga_id=load,
pac_id=patient, resultado_id='biopsia.grado', valor_fuente='BENIGNO'))
session.commit()
yield engine
engine.dispose()
@pytest.fixture
def client(cohort_db):
"""Configure an explicitly synthetic reader and an authorized test principal."""
app = Flask(__name__)
app.register_blueprint(analysis, url_prefix='/cama')
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
def read(cutoff):
with Session(cohort_db) as session:
return CamaCohort(session).rows(cutoff)
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=lambda req: True)
return app.test_client()
QUERY = '?cohorte=cama_birads_v1&escenario=diagnostico&corte=2026-10-20&meses=0&birads=BIRADS_5'
def query(client, cutoff='2026-10-20'):
revision = client.get('/cama/analisis/indicadores?corte=' + cutoff).get_json()['revision']
return QUERY.replace('2026-10-20', cutoff) + '&revision=' + revision
def test_aggregate_list_detail_and_export_have_one_selection(client):
"""The published aggregate reconciles with pages, patient details and export."""
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 6
selection = query(client)
first = client.get('/cama/seguimiento' + selection + '&page_size=2').get_json()
assert first['ventana'] == {'meses': 0, 'desde': '2025-02-01', 'hasta': '2026-10-20'}
items = []
for page in (1, 2, 3):
data = client.get('/cama/seguimiento' + selection + f'&page_size=2&page={page}').get_json()
items.extend(data['items'])
exported = client.get('/cama/seguimiento/exportacion' + selection).get_json()
assert exported['items'] == items and exported['total_items'] == 6
for item in items:
detail = client.get('/cama/pacientes/' + item['pac_id'] + selection).get_json()
assert detail['item'] == item and detail['corte'] == aggregate['corte']
assert sum(item['biopsia'] == 'BENIGNO' for item in items) == 1
assert client.get('/cama/seguimiento' + selection).get_json()['items'] == items
def test_rejects_unknown_and_suppressed_selections_and_denies_access(client):
"""Unknown filters and small groups cannot silently broaden patient access."""
selection = query(client)
assert client.get('/cama/seguimiento' + selection + '&estadio=IV').status_code == 400
assert client.get('/cama/seguimiento' + selection.replace('BIRADS_5', 'BIRADS_4A')).status_code == 403
assert client.get('/cama/seguimiento' + selection.replace('cama_birads_v1', 'otra')).status_code == 400
assert client.get('/cama/seguimiento' + selection.replace(selection[-64:], '0' * 64)).status_code == 409
client.application.config['CAMA_COHORT_ACCESS'] = lambda req: False
assert client.get('/cama/seguimiento' + selection).status_code == 403
assert client.get('/cama/seguimiento/exportacion' + selection).status_code == 403
assert client.get('/cama/pacientes/some-id' + selection).status_code == 403
def test_cutoff_excludes_later_clinical_and_load_dates(client):
"""A report or observation not yet known at the cutoff cannot appear."""
early = query(client, '2025-02-09')
rows = client.get('/cama/seguimiento' + early).get_json()['items']
assert len(rows) == 6 and all(row['biopsia'] is None for row in rows)
empty = query(client, '2025-02-01').replace('&birads=BIRADS_5', '')
response = client.get('/cama/seguimiento' + empty).get_json()
assert response['items'] == [] and response['ventana']['desde'] == '2025-02-01'
def test_links_and_load_dates_are_distinct(client, cohort_db):
"""A missing link and a late load cannot supply a diagnosis before cutoff."""
ids = {i: str(i) for i in range(1, 5)}
data = client.get('/cama/seguimiento' + query(client)).get_json()
rows = {item['pac_id']: item for item in data['items']}
assert rows[ids[1]]['biopsia'] == 'BENIGNO'
assert rows[ids[2]]['biopsia'] is None and rows[ids[2]]['biopsia_fecha'] is None
assert rows[ids[3]]['biopsia'] is None and rows[ids[3]]['biopsia_fecha'] == '2025-02-15'
assert rows[ids[4]]['biopsia'] is None and rows[ids[4]]['biopsia_fecha'] is None
later = client.get('/cama/seguimiento' + query(client, '2027-12-01')).get_json()
rows_later = {item['pac_id']: item for item in later['items']}
assert rows_later[ids[3]]['biopsia'] == 'BENIGNO'
assert rows_later[ids[4]]['biopsia_fecha'] == '2027-02-15'
assert set(rows) == set(rows_later)
def test_full_application_registers_cohort_and_regular_followup(client):
"""The regular follow-up uses the configured reader instead of unrelated fixture rows."""
from webapi import create_app
app = create_app()
app.config.update(client.application.config)
full = app.test_client()
assert full.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 200
assert full.get('/cama/seguimiento?corte=2026-10-20&meses=0').get_json()['paginacion']['total_items'] == 6
assert full.get('/cama/seguimiento?meses=12&resultado=INVASOR').status_code == 400
def test_windows_and_disabled_provider(client):
"""Regular windows remain available and a missing reader returns unavailable."""
selection = query(client).replace('&meses=0', '&meses=1').replace('&birads=BIRADS_5', '')
body = client.get('/cama/seguimiento' + selection).get_json()
assert body['items'] == [] and body['ventana']['desde'] == '2026-09-21'
client.application.config['CAMA_COHORT_READER'] = None
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
def test_newer_noneligible_result_changes_revision_and_excludes_patient(client, cohort_db):
"""The latest reported result is selected before checking BI-RADS eligibility."""
previous = query(client)
with Session(cohort_db) as session:
session.add(TABLAS.Procedimiento(procedimiento_id=200, fuente_tabla='mastografia', fuente_id='new',
carga_id=1, pac_id=6, estudio_id='mastografia', clase='toma', fecha=date(2025, 4, 1)))
session.add(TABLAS.Procedimiento(procedimiento_id=201, padre_id=200, fuente_tabla='mastografia', fuente_id='new',
carga_id=1, pac_id=6, estudio_id='mastografia', clase='reporte', fecha=date(2025, 4, 2)))
session.add(TABLAS.Observacion(observacion_id=200, procedimiento_id=201, carga_id=1, pac_id=6,
resultado_id='mastografia.birads', valor_fuente='B1'))
session.commit()
assert client.get('/cama/seguimiento' + previous).status_code == 409
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 5
assert len(client.get('/cama/seguimiento' + query(client)).get_json()['items']) == 5
def test_cross_patient_links_and_observations_are_not_used(cohort_db):
"""A mismatched patient or an order before the mammogram cannot supply a result."""
with Session(cohort_db) as session:
# The biopsy order is linked to patient 1's mammogram but belongs to patient 2.
session.get(TABLAS.Procedimiento, 102).pac_id = 2
# Patient 3's otherwise linked biopsy order predates the mammogram.
session.get(TABLAS.Procedimiento, 106).fecha = date(2025, 1, 1)
# The BI-RADS observation belongs to a different patient.
session.get(TABLAS.Observacion, 6).pac_id = 5
session.commit()
reader = CamaCohort(session)
rows = {row['pac_id']: row for row in reader.rows(date(2027, 12, 1))}
assert '6' not in rows
assert rows['1']['biopsia'] is None
assert rows['3']['biopsia'] is None
+25
View File
@@ -0,0 +1,25 @@
"""Verify default persistent cohort setup with retained legacy configuration."""
from flask import Flask
from webapi.cama_runtime import configure_cama_cohort
def test_default_reader_uses_shared_persistence(monkeypatch):
"""The reader is registered without special cohort environment variables."""
for key in ('CAMA_COHORT_SYNTHETIC', 'CAMA_COHORT_SECRET', 'CAMA_COHORT_ACCESS_TOKEN'):
monkeypatch.delenv(key, raising=False)
app = Flask(__name__)
configure_cama_cohort(app)
assert callable(app.config['CAMA_COHORT_READER'])
assert 'CAMA_COHORT_ACCESS' not in app.config
def test_application_starts_with_retained_obsolete_configuration(monkeypatch):
"""Retained synthetic settings cannot prevent the health endpoint starting."""
monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1')
monkeypatch.delenv('CAMA_COHORT_SECRET', raising=False)
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 'invalid')
from webapi import create_app
assert create_app().test_client().get('/health').get_json() == {'status': 'ok'}
+120
View File
@@ -0,0 +1,120 @@
"""`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 indicadores_kit.registry import catalogos
from indicadores_kit.tablas 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`/`sincronizar` 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_mints_a_resultado_and_is_written_too(cacu_catalog, known_patient):
result = commit_discovered_fields(
[_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia"
)
assert result.fields_minted == 1
nombres = set(catalogos._leer(cacu_catalog)["citologia"]["resultados"])
assert nombres == {"calidad_muestra", "tipo_de_fijador"} # the fixture's field, plus the minted one
minted_id = "citologia.tipo_de_fijador"
catalogo = catalogos.catalogo_desde_toml(cacu_catalog, tablas=tablas_de("cacu"))
assert minted_id in {r.resultado_id for r in catalogo.resultados}
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 == minted_id
assert observacion.valor_texto == "Formol"
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 indicadores_kit.registry import catalogos
from indicadores_kit.registry.catalogos import Catalogo
from indicadores_kit.tablas 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"
+165
View File
@@ -0,0 +1,165 @@
"""`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 (`varbinary(max)`) 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 shaped like ISSSTELEON's: 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 ISSSTELEON'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`) still reaches the silver layer through the open-catalog
path, alongside the recognized fields `commit_sources` writes as
before. Fails if `/imports/commit` stops wiring that second path in.
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 indicadores_kit.registry import catalogos
from core.cacu.paciente.model import Paciente
from persistance.cacu import carga_repository, paciente_repository
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
(tmp_path / "cacu.toml").write_text('[citologia]\netiqueta = "Citología cervical"\n', 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
[report] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
assert report["records_written"] == 1 and report["fields_minted"] == 1
with carga_repository.open_session() as sesion:
[minted] = 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 minted.resultado_id == "citologia.tipo_de_fijador" and minted.valor_texto == "Formol"
+66
View File
@@ -0,0 +1,66 @@
"""Publicación HTTP de CAM-01 y CAM-02 sobre la base sintética del kit."""
import pytest
from conftest import cliente_de
IDS = {"cama_tasa_deteccion_histopatologica": "C1", "cama_dias_resultado_diagnostico": "C3r"}
@pytest.fixture(scope="module")
def client(tmp_path_factory):
yield from cliente_de("cama", tmp_path_factory)
def test_catalogo_publica_las_dos_medidas(client):
"""Keep C1/C3r publication while titles remain suitable for the interface."""
catalogo = {item["id"]: item for item in client.get("/cama/indicadores").get_json()}
for identificador, contrato in IDS.items():
assert catalogo[identificador]["contrato"] == contrato
assert "demostración" not in catalogo[identificador]["titulo"]
assert "sintética" not in catalogo[identificador]["titulo"]
assert set(catalogo[identificador]["tipos_periodo"]) == {"mes", "semestre"}
@pytest.mark.parametrize("indicador,contrato", IDS.items())
def test_periodos_metadatos_y_datos(client, indicador, contrato):
raiz = f"/cama/indicadores/{indicador}"
assert client.get(raiz + "/metadatos").status_code == 200
assert client.get(raiz + "/periodos").status_code == 200
response = client.get(raiz + "/datos?periodos=2025-S1")
assert response.status_code == 200 and response.is_json
data = response.get_json()
assert data["contrato"] == contrato and data["periodos"] == ["2025-S1"]
assert isinstance(data["filas"], list) and data["filas"]
assert client.get(raiz + "/datos?periodos=2025-13").status_code == 404
@pytest.fixture(scope="module")
def client_sin_supresion(tmp_path_factory):
from indicadores_kit.demostracion import base_de_prueba
from indicadores_kit.registry.parametros import RUTA_PARAMETROS
from persistance import db
from persistance.settings import settings
from webapi import create_app
carpeta = tmp_path_factory.mktemp("cama_f4b2")
parametros = carpeta / "parametros.toml"
parametros.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
with pytest.MonkeyPatch.context() as mp:
mp.setattr(settings, "cama_database_url", f"sqlite:///{carpeta / 'demo.db'}")
db.get_cama_engine.cache_clear()
try:
base_de_prueba(db.get_cama_engine(), "cama", ruta_parametros=parametros)
yield create_app().test_client()
finally:
db.get_cama_engine().dispose()
db.get_cama_engine.cache_clear()
def test_valores_sinteticos_visibles_con_umbral_de_prueba(client_sin_supresion):
raiz = "/cama/indicadores/"
c1 = client_sin_supresion.get(raiz + "cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1").get_json()
c3 = client_sin_supresion.get(raiz + "cama_dias_resultado_diagnostico/datos?periodos=2025-S1").get_json()
assert c1["filas"][0]["numerador"] == 0 and c1["filas"][0]["denominador"] == 1
assert c1["filas"][0]["valor"] == 0 and c1["filas"][0]["ic_alto"] > 0
fila = c3["filas"][0]
assert (fila["n"], fila["q1"], fila["mediana"], fila["q3"]) == (5, 3, 7, 10)
assert fila["n_excluido"] == 1 and fila["unidad"] == "dias"
+107
View File
@@ -0,0 +1,107 @@
"""Publicación C2 de CAM-03 con dos matrices sintéticas y base aislada."""
from datetime import date
import json
import os
from pathlib import Path
import pytest
from sqlmodel import Session
from conftest import cliente_de
from indicadores_kit.cama.familias.histopatologia_birads.fixture_demo import agregar_en
from indicadores_kit.cama.tablas import TABLAS
from indicadores_kit.demostracion import base_de_prueba
from indicadores_kit.pruebas import calcular_measure
from indicadores_kit.registry.measures import measures_de
from persistance import db
from persistance.settings import settings
from webapi import create_app
ID = "cama_histopatologia_birads"
RAIZ = f"/cama/indicadores/{ID}"
@pytest.fixture(scope="module")
def publicaciones(tmp_path_factory):
resultados = []
for variante in (1, 2):
ruta = tmp_path_factory.mktemp(f"matriz{variante}") / "cama.db"
with pytest.MonkeyPatch.context() as mp:
mp.setattr(settings, "cama_database_url", f"sqlite:///{ruta}")
db.get_cama_engine.cache_clear()
motor = db.get_cama_engine()
try:
base_de_prueba(motor, "cama")
with Session(motor) as sesion:
agregar_en(sesion, variante=variante)
medida = measures_de("cama")[ID]
for periodo in ("2025-S1", "2025-02"):
calcular_measure(sesion, medida, periodo, tablas=TABLAS, corte=date(2025, 12, 31))
cliente = create_app().test_client()
general = cliente.get(RAIZ + "/datos?periodos=2025-S1")
matriz = cliente.get(RAIZ + "/datos?periodos=2025-S1&estrato=birads")
assert general.status_code == matriz.status_code == 200
resultados.append((general.get_json(), matriz.get_json()))
if variante == 1:
destinos = os.environ.get("CAM03_EJEMPLOS_DIR")
if destinos:
carpeta = Path(destinos)
carpeta.mkdir(parents=True, exist_ok=True)
for nombre, respuesta in (("cam03-general.json", general), ("cam03-birads.json", matriz)):
(carpeta / nombre).write_text(json.dumps(respuesta.get_json(), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
catalogo = cliente.get("/cama/indicadores").get_json()
assert {"cama_tasa_deteccion_histopatologica", "cama_dias_resultado_diagnostico", ID} <= {i["id"] for i in catalogo}
historicos = ("cama_birads_456_paciente", "cama_birads_456_mastografia",
"cama_confirmacion_birads45", "cama_dias_toma_diagnostico", "cama_eu38a")
assert set(historicos) <= {i["id"] for i in catalogo}
for historico in historicos:
assert cliente.get(f"/cama/indicadores/{historico}/datos?periodos=2025-S1").status_code == 200
assert cliente.get(RAIZ + "/metadatos").status_code == 200
assert next(i for i in catalogo if i['id'] == ID)['titulo'] == 'Histopatología por BI-RADS'
assert matriz.get_json()['titulo'] == 'Histopatología por BI-RADS'
assert 'datos sintéticos' not in matriz.get_json()['notas'][0]
assert cliente.get(RAIZ + "/periodos").status_code == 200
assert cliente.get(RAIZ + "/datos?periodos=2025-02&estrato=birads").status_code == 200
figura = cliente.get(RAIZ + "/figuras/fig_c2_donas?periodos=2025-S1")
assert figura.status_code == 200
finally:
motor.dispose()
db.get_cama_engine.cache_clear()
return resultados
def test_cruce_completo_y_catalogos(publicaciones):
general, datos = publicaciones[0]
assert datos["contrato"] == general["contrato"] == "C2"
assert datos["estrato"] == "birads" and general["estrato"] is None
estratos = {"BIRADS_4", "BIRADS_4A", "BIRADS_4B", "BIRADS_4C", "BIRADS_5", "BIRADS_6"}
categorias = {"BENIGNO", "RIESGO_B3", "IN_SITU", "INVASOR", "SIN_DATO", "SIN_BIOPSIA"}
assert set(datos["valores_estrato"]) == estratos
assert {(f["estrato"], f["categoria"]) for f in datos["filas"]} == {(e, c) for e in estratos for c in categorias}
assert datos["categorias"]["BENIGNO"]["grupo"] == "NO_MALIGNO"
assert datos["categorias"]["RIESGO_B3"]["grupo"] == "NO_MALIGNO"
assert datos["categorias"]["IN_SITU"]["grupo"] == datos["categorias"]["INVASOR"]["grupo"] == "MALIGNO"
assert datos["categorias"]["SIN_DATO"]["grupo"] == "SIN_DATO"
assert datos["categorias"]["SIN_BIOPSIA"]["grupo"] is None
assert datos["grupos_de_categoria"]["MALIGNO"] == "Maligno"
celdas = {(f["estrato"], f["categoria"]): f for f in datos["filas"]}
assert celdas["BIRADS_4", "RIESGO_B3"]["n"] == 0 and celdas["BIRADS_4", "RIESGO_B3"]["suprimido"] == 0
assert celdas["BIRADS_4", "SIN_DATO"]["n"] == 1
for total in datos["totales_estrato"]:
assert total["n"] == sum(f["n"] for f in datos["filas"] if f["estrato"] == total["estrato"])
assert sum(f["n"] for f in general["filas"]) == sum(f["n"] for f in datos["filas"])
def test_mismas_marginales_no_ocultan_celdas_distintas(publicaciones):
(g1, m1), (g2, m2) = publicaciones
assert {f["categoria"]: f["n"] for f in g1["filas"]} == {f["categoria"]: f["n"] for f in g2["filas"]}
assert {f["estrato"]: f["n"] for f in m1["totales_estrato"]} == {f["estrato"]: f["n"] for f in m2["totales_estrato"]}
assert {(f["estrato"], f["categoria"]): f["n"] for f in m1["filas"]} != {(f["estrato"], f["categoria"]): f["n"] for f in m2["filas"]}
def test_supresion_en_fixture_pequeno(tmp_path_factory):
for cliente in cliente_de("cama", tmp_path_factory):
datos = cliente.get(RAIZ + "/datos?periodos=2025-S1&estrato=birads").get_json()
assert datos["filas"] and all(f["suprimido"] == 1 and f["n"] is None for f in datos["filas"])
assert all(t["suprimido"] == 1 and t["n"] is None for t in datos["totales_estrato"])
assert "BIRADS_4" not in datos["valores_estrato"]
assert not any(f["estrato"] == "BIRADS_4" for f in datos["filas"])
+1 -1
View File
@@ -22,7 +22,7 @@ def test_imported_rows_are_what_models_reads_and_model_writes_are_what_the_api_s
"""Rows imported over HTTP are read back through `models`' repository, and a row written there is served by
the API. Fails if `resolve_repository` stops returning the objects WebApi writes with."""
from core.cama.models import Mastografia
from models.io.repositories import resolve_repository
from models.io.storage import resolve_repository
csv = b"Expediente,BIRADS\nRT-1,BI-RADS 4\nRT-2,2\n"
response = client.post(
+98
View File
@@ -0,0 +1,98 @@
"""What this module covers: `GET /cacu/pacientes/<pac_id>/riesgo` (`webapi.patient_risk`): when the route exists, the
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
there.
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
import pytest
from conftest import cliente_de
COHORT_KEYS = {"url", "version", "fecha_indice", "tipo_censura", "c", "l", "r", "pap_0", "hpv_0"}
RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "estado_lote", "horizontes"}
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.delenv("DEV_REVISION", raising=False)
yield from cliente_de("cacu", tmp_path_factory)
@pytest.fixture(scope="module")
def seeded(client):
"""Two patients of the demo data in a new surveillance build; the first has `pap_0`, `c` and a batch with risks at
1 and 3 years, confirmed. Returns (scored patient, member without risks, patient outside the build)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, CohorteVariable
from persistance import cacu
from persistance.db import get_cacu_session
scored, unscored, outside = [p.pac_id for p in cacu.persona_repository.list(limit=3)]
with get_cacu_session() as session:
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-route", marco_sha="m",
n_miembros=2, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))
session.add(build)
session.flush()
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(p))
for p in (scored, unscored)])
session.flush()
session.add_all([CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="pap_0", valor_codigo="ASC-US"),
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
session.commit()
build_id = build.armado_id
batch, _ = cacu.cohorte_repository.guardar_lote(
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
cacu.cohorte_repository.cambiar_estado(batch, "final", "revisado")
return scored, unscored, outside
def test_a_scored_member_has_the_contracts_shape(client, seeded):
"""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()
assert response.status_code == 200 and body["simulado"] is True
assert set(body["cohorte"]) == COHORT_KEYS and set(body["riesgo"]) == RISK_KEYS
assert (body["cohorte"]["pap_0"], body["cohorte"]["c"], body["cohorte"]["hpv_0"]) == ("ASC-US", 0.0, None)
assert body["riesgo"]["evaluado_en"] == "2026-10-01T00:00:00Z" and body["riesgo"]["estado_lote"] == "final"
horizons = body["riesgo"]["horizontes"]
assert all(set(h) == HORIZON_KEYS for h in horizons)
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
def test_follow_up_identity_resolves_scored_patient(client, seeded):
"""The patient selected from follow-up resolves to that patient's seeded risk."""
listing = client.get('/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200').get_json()
row = next(item for item in listing['items'] if item['pac_id'] == str(seeded[0]))
assert row['id_seudonimo'] == row['pac_id']
response = client.get(f"/cacu/pacientes/{row['pac_id']}/riesgo")
assert response.status_code == 200
assert response.get_json()['cohorte']['pap_0'] == 'ASC-US'
assert response.get_json()['riesgo']['horizontes'][0]['probabilidad'] == 0.1
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
null. Fails if either case errors or invents a risk."""
member = client.get(f"/cacu/pacientes/{seeded[1]}/riesgo").get_json()
outside = client.get(f"/cacu/pacientes/{seeded[2]}/riesgo").get_json()
assert member["cohorte"] is not None and member["riesgo"] is None
assert outside == {"simulado": True, "cohorte": None, "riesgo": None}
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
+16 -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,8 @@ 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)
assert all(i["pac_id"] == i["id_seudonimo"] and i["pac_id"].isdigit() 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 +61,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_en_dev_esta_obsoleta():
"""Fija: `en_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso."""
from webapi.seguimiento import en_dev
with pytest.warns(DeprecationWarning):
en_dev()
+72
View File
@@ -0,0 +1,72 @@
"""Exercise regular and cohort follow-up with an authorized synthetic reader."""
from datetime import date
import pytest
from flask import Flask
from webapi.cama_analysis import analysis, revision_of
from webapi.seguimiento_cama import blueprint_seguimiento_cama
@pytest.fixture
def client():
"""A fixed six-person cohort and a server-controlled access callback."""
rows = [dict(pac_id=str(n + 1), mastografia_fecha='2026-10-15',
birads='BIRADS_5', grupo_edad='50-59', biopsia=None,
biopsia_fecha=None) for n in range(6)]
app = Flask(__name__)
app.register_blueprint(analysis, url_prefix='/cama')
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=lambda cutoff: rows,
CAMA_COHORT_ACCESS=lambda request: request.headers.get('X-Test') == 'yes')
return app.test_client()
def test_regular_list_detail_and_export_use_the_same_selection(client):
"""Pagination, detail and export resolve the same filtered persistent cohort."""
headers = {'X-Test': 'yes'}
query = '?corte=2026-10-20&meses=3&birads=BIRADS_5'
page = client.get('/cama/seguimiento' + query + '&page_size=2', headers=headers).get_json()
assert page['paginacion']['total_items'] == 6
assert page['cohorte'] == 'cama_birads_v1'
context = '&cohorte=' + page['cohorte'] + '&escenario=' + page['escenario'] + '&revision=' + page['revision']
rows = []
for number in (1, 2, 3):
rows.extend(client.get('/cama/seguimiento' + query + context + f'&page_size=2&page={number}', headers=headers).get_json()['items'])
exported = client.get('/cama/seguimiento/exportacion' + query + context, headers=headers).get_json()
assert exported['items'] == rows
assert client.get('/cama/pacientes/' + rows[0]['pac_id'] + query + context, headers=headers).get_json()['item'] == rows[0]
assert client.get('/cama/seguimiento' + query, headers=headers).headers['Cache-Control'] == 'no-store'
def test_regular_followup_checks_access_and_suppression(client):
"""The ordinary route cannot bypass authorization or suppression."""
assert client.get('/cama/seguimiento').status_code == 403
headers = {'X-Test': 'yes'}
assert client.get('/cama/seguimiento?corte=2026-10-20&birads=BIRADS_4', headers=headers).status_code == 403
assert client.get('/cama/seguimiento?corte=2026-10-20&estatus=BENIGNO', headers=headers).status_code == 400
assert client.get('/cama/seguimiento?revision=' + '0' * 64, headers=headers).status_code == 400
client.application.config['CAMA_COHORT_ACCESS'] = 'invalid'
assert client.get('/cama/seguimiento', headers=headers).status_code == 403
def test_disabled_provider_and_empty_window(client):
"""Unavailable sources fail closed and an empty unfiltered window stays empty."""
headers = {'X-Test': 'yes'}
body = client.get('/cama/seguimiento?corte=2025-01-01&meses=3', headers=headers).get_json()
assert body['items'] == [] and body['paginacion']['total_items'] == 0
client.application.config['CAMA_COHORT_READER'] = None
assert client.get('/cama/seguimiento', headers=headers).status_code == 503
def test_provider_failure_does_not_break_other_routes(client):
"""A failing cohort source returns unavailable while the app can serve other requests."""
def fail(_cutoff):
raise RuntimeError('provider unavailable')
client.application.add_url_rule('/health', 'health', lambda: {'status': 'ok'})
client.application.config['CAMA_COHORT_READER'] = fail
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
assert client.get('/cama/seguimiento?corte=2026-10-20', headers={'X-Test': 'yes'}).status_code == 503
assert client.get('/health').get_json() == {'status': 'ok'}
Generated
+9 -13
View File
@@ -1,5 +1,5 @@
version = 1
revision = 2
revision = 3
requires-python = ">=3.12"
resolution-markers = [
"python_full_version >= '3.14' and sys_platform == 'win32'",
@@ -1026,9 +1026,7 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/72/18/3fc6d951466ae9a2a688edcddde3b2e388da0a8244e0caf7117bbeb0eb95/greenlet-3.5.6-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:a5876d0a60355af98d535c47f6cd6eb0f8a432396dab26845d380b92f8412422", size = 295668, upload-time = "2026-09-14T14:22:33.241Z" },
{ url = "https://files.pythonhosted.org/packages/27/89/366d2af5061eeefa5012f510d95a99c8620dcc457609838db4d538820318/greenlet-3.5.6-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e85880b538e59a59f55117b81f208a6660ad5ac328aad9305f812d9b8bc67a0f", size = 611700, upload-time = "2026-09-14T15:12:01.962Z" },
{ url = "https://files.pythonhosted.org/packages/54/1c/07f133f865fd58ae593dd2bbec3144acaee9b04ffe2eb48c6e121747ceef/greenlet-3.5.6-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f0ba7c2a329d650628f4c8572fd1db29f0a59dd70a3e3e0710dcf18a35cce9d8", size = 624223, upload-time = "2026-09-14T15:20:42.459Z" },
{ url = "https://files.pythonhosted.org/packages/a7/f2/844dc823ff2752ad049caa6b59d57e4572f9c445934b02d3518f4c67197c/greenlet-3.5.6-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee7d9da3bf493909cf811a3f038840cb34fab5ae2956b8a263919f6e289ab188", size = 629529, upload-time = "2026-09-14T15:25:06.354Z" },
{ url = "https://files.pythonhosted.org/packages/66/6a/1594f3869c57c149abdb380492529e04d4c0229b5e4d79572c5bd0aaa673/greenlet-3.5.6-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:975736b002ed080d124cf81a79cb7e05cb26d6b3f5c7a7b651c0fcce70353aa1", size = 621404, upload-time = "2026-09-14T14:35:59.027Z" },
{ url = "https://files.pythonhosted.org/packages/c0/42/b1f8dbc89a53b9e77859fc1ad1627d106fc361daa3ea4bdf43a91ebb4338/greenlet-3.5.6-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:71890d5247020c25c21a6b65202782bfc281d4e6e244842419d30e3492bb6dcc", size = 432385, upload-time = "2026-09-14T15:28:37.369Z" },
{ url = "https://files.pythonhosted.org/packages/a2/f5/33e5c9e48178b9259fd000f8f45caa4a65036f65d3d0c06a602f570f025d/greenlet-3.5.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0616b8f878098c5681fd8f0dc92d887551717402342a70f0abcbfea5f5ad8a44", size = 1584998, upload-time = "2026-09-14T15:10:06.653Z" },
{ url = "https://files.pythonhosted.org/packages/ef/31/9b4e140bc24d0ad7927ebd651f5608b0acc2334d061748c3b6ad19085cfa/greenlet-3.5.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3dbb4596a6a4e5d47121a33ff20533a81e60f302d9e67b69909a8bc21a43f0a7", size = 1647568, upload-time = "2026-09-14T14:35:49.787Z" },
{ url = "https://files.pythonhosted.org/packages/c3/71/d79f1791f824f8ff15c2978746640467ae932a2365e0201069f7f272395f/greenlet-3.5.6-cp312-cp312-win_amd64.whl", hash = "sha256:7ac4abb3877c43af320392c664774eef6fa2cc063c79a55fc02d844a3cbe7395", size = 324203, upload-time = "2026-09-14T14:22:54.504Z" },
@@ -1036,9 +1034,7 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f1/a1/e720a38852366c589e1a46cf570b886507ad2cf591050c203365638baab0/greenlet-3.5.6-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:f96f0e30b5a95c7631b12bfe214cbc90ec8fe8cfa36920596c10514a65743519", size = 294627, upload-time = "2026-09-14T14:24:40.102Z" },
{ url = "https://files.pythonhosted.org/packages/eb/c3/58187858df41354a11e6a55b421e7af9059798abdab3a384cc51b8567c38/greenlet-3.5.6-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c75116c9de79949de23006e2d9b35ee82874c594fcf5c0311b439acaa14b8441", size = 614356, upload-time = "2026-09-14T15:12:03.399Z" },
{ url = "https://files.pythonhosted.org/packages/ce/b9/3a7e67d5f05c9760b1ad411fa52264bd69cc08e22a2ebfb4018b90628ced/greenlet-3.5.6-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cad5782f93f7f738b62c6527b6f32a60694d924029f299a8b524758cfa53d815", size = 626756, upload-time = "2026-09-14T15:20:44.269Z" },
{ url = "https://files.pythonhosted.org/packages/c6/7c/40400455f5b5a65bb83e94fde66d1be9e5ec518638113f8083ace746c309/greenlet-3.5.6-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a93ee7c6e8fd0f8a83525a51bd777be57ee17787e91d805bd8d6faf9dcada18e", size = 632632, upload-time = "2026-09-14T15:25:07.813Z" },
{ url = "https://files.pythonhosted.org/packages/85/cb/ab0c123c514ed4e94c0dc9ee2e86362633e6b998cfc05de7fc9ac2eb9690/greenlet-3.5.6-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f98e8215e172f567ce80eeaed9107fb4d32b6c44f26983d9b8334658136a205a", size = 623779, upload-time = "2026-09-14T14:36:01.104Z" },
{ url = "https://files.pythonhosted.org/packages/f9/67/1f35cff30a6c51c3f23b63d4afcc7313ab4f97490ba3676fa78178984b27/greenlet-3.5.6-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:7f731ebac68ea06d628658295cb2d217b10186329fcf9a3b6a149045059bf92e", size = 434933, upload-time = "2026-09-14T15:28:38.858Z" },
{ url = "https://files.pythonhosted.org/packages/a5/26/fda8a5a06e7073333ccb038133c5893b9e0c4fe29d5992a17e83c241bc6e/greenlet-3.5.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df19e2d0b1620039af5102563fbd96e8938c7f5c3f5828528d641d9fc585525e", size = 1584930, upload-time = "2026-09-14T15:10:08.234Z" },
{ url = "https://files.pythonhosted.org/packages/2f/37/50f8813163148d6234e08b23dcad6a9e37f01d148c8ec976e4c44ea2d918/greenlet-3.5.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:06c0e933290fba8ffe53ead4ae1b8044b0e9754b75cebf381aa2bc3e50d82fac", size = 1647590, upload-time = "2026-09-14T14:35:51.173Z" },
{ url = "https://files.pythonhosted.org/packages/86/da/b7669b09586365654083a62bd0724cf06cb74bd5085a15cdd161271f992f/greenlet-3.5.6-cp313-cp313-win_amd64.whl", hash = "sha256:5b602b4201b965a8354d74e232364a66ff243dd142e350d035f46169bb36e13d", size = 324086, upload-time = "2026-09-14T14:23:48.428Z" },
@@ -1046,9 +1042,7 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/66/c0/d254544ae2b8bdd311aef000fafc02828c2771b17d994b3075620ea7cc6e/greenlet-3.5.6-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8cddea1b8339451c2fb3388e138347b6126744f33b611bdb55b7357361cfef46", size = 295221, upload-time = "2026-09-14T14:25:11.583Z" },
{ url = "https://files.pythonhosted.org/packages/18/18/eb54be16b9cc3971e09ca5b73334e1b8c804a4630d9addaaf218a4fe300f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c59acfa8eb73a1e0d484392dc002bdf001fd4ce73394e0132df3d1ab6093d7cb", size = 660992, upload-time = "2026-09-14T15:12:04.876Z" },
{ url = "https://files.pythonhosted.org/packages/8f/b4/e193efe65671dcf294bc51fcc59efb52d154adf8612c4ea016da0d2c486c/greenlet-3.5.6-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a3b4a01c6da07ef9f80d4fe8933b994bc99747bcea3eab0330a9c34d3c12655b", size = 673428, upload-time = "2026-09-14T15:20:45.756Z" },
{ url = "https://files.pythonhosted.org/packages/fd/21/631bb45fafde1dca782152377c0676d182ec924820064047f533a3627b28/greenlet-3.5.6-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dd0b83bed3405b586a3133629f1d1a5bc7bfd64822a3b7ab342bdc68e6dbc61b", size = 677688, upload-time = "2026-09-14T15:25:09.279Z" },
{ url = "https://files.pythonhosted.org/packages/45/ac/28fa7a9e50f2859466214c4ac584d776db52c1604ad4dd158960a5af2a1f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a09d59bef1db94f384b5bcc2d523694d338f3df6b757aeeaf7baca5d0c0be88", size = 670773, upload-time = "2026-09-14T14:36:02.577Z" },
{ url = "https://files.pythonhosted.org/packages/40/30/2b0a73e68e1e18e30b601d0d183cfdfc2beca4de5a6843c630f0fc9fb90c/greenlet-3.5.6-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:fdacf26402389bdd89857ad3c045a26fe8f3314f9a8b28226f82f88463a65b77", size = 480475, upload-time = "2026-09-14T15:28:40.741Z" },
{ url = "https://files.pythonhosted.org/packages/c3/cd/fb7d6cdd86ff3427c1494854f0e35437eba05142be91f530f6da75e09e19/greenlet-3.5.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8b7c73d1cef3d9ae963e9ff03f6222df43efbb9054ffd2f1969c935b7fc84c02", size = 1631900, upload-time = "2026-09-14T15:10:09.745Z" },
{ url = "https://files.pythonhosted.org/packages/f6/40/143bdbb20a516628cb15074ae52ed17d850b450292609c7a6fccac6dbece/greenlet-3.5.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8b27df301f56e3b3d2298095c8f7d6b68f2521f6b1693e901fa039bdbae34424", size = 1693740, upload-time = "2026-09-14T14:35:52.959Z" },
{ url = "https://files.pythonhosted.org/packages/c9/9e/019642432e6ae283301df1361227d47610709d2dc69a38f95edef266d713/greenlet-3.5.6-cp314-cp314-win_amd64.whl", hash = "sha256:f8f0bd690e1a41294ac87905e8121c81a3761ec2583c768f13467428606c8c7a", size = 327473, upload-time = "2026-09-14T14:28:12.948Z" },
@@ -1056,18 +1050,14 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/14/7e/7a205688a5b3074933b18a906608d46d106e9a79d776bdab5a4abf4b4feb/greenlet-3.5.6-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:97c5a53e8c1754df58e73f047a99e287d4da1bdfe64b0072fb25c87000897951", size = 305352, upload-time = "2026-09-14T14:21:31.962Z" },
{ url = "https://files.pythonhosted.org/packages/78/cb/9c4a57a9d9dd0256e20b8f7f4f06554c2c92badebf0ab73ce344321b78b9/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fea4427d1ffdb3b523d7daa6712038428a4c16c450b9777bdd1221cfee0eab49", size = 672671, upload-time = "2026-09-14T15:12:06.347Z" },
{ url = "https://files.pythonhosted.org/packages/97/52/c6729681ebbd298f4decd28746815acc8a0b0a0fde21d2df33776fd4d042/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:73a29b5ba642e35433166a03a3e02935e7238c4b3467fbd77523b99edea23e5b", size = 679489, upload-time = "2026-09-14T15:20:47.291Z" },
{ url = "https://files.pythonhosted.org/packages/71/76/3c11c21e0716b1f1dc7c1a4b3d690abb1d3b448c69a9d32049fecb64010a/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:61a61b4a95a4f97922c3a6f5606d3e360851584bd47e500a5161373c53810e3d", size = 681303, upload-time = "2026-09-14T15:25:11.088Z" },
{ url = "https://files.pythonhosted.org/packages/58/c5/2b6c721ba8b8963da42d5a0f57f25b8aaeb1fe9bdd156875e57f3be648a2/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:460e70b033aba8ed47e2ac9b5d0d2157b05a34fbfa30a241400aef4118902cdc", size = 676608, upload-time = "2026-09-14T14:36:03.959Z" },
{ url = "https://files.pythonhosted.org/packages/3f/26/3ae402202452cd5941bbbd483e5a74297e2397e7aa3182c2a5e3ab7d5666/greenlet-3.5.6-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:fe3170a69fe039b18ad18171e66faa9a75f6fe9d78f968fd9b54e09fbd714d81", size = 510112, upload-time = "2026-09-14T15:28:42.112Z" },
{ url = "https://files.pythonhosted.org/packages/b2/04/0d018e0d05bcdde19a0fcb907834155f1fc853a9bedd3f3f5e6acadcae19/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca80a49b53ed1d22f7282da7255f7bb2fd1935fd0f623d8613fda38745f18961", size = 1641479, upload-time = "2026-09-14T15:10:11.216Z" },
{ url = "https://files.pythonhosted.org/packages/59/bb/f02ef9073919158f6403fe3701d4ed4403d646720e7201dfc6e9d264bac3/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:916f92f2a8db10508f739d0b5e00b83defe5d1115a997c54532a6d7cf8c95404", size = 1698758, upload-time = "2026-09-14T14:35:54.336Z" },
{ url = "https://files.pythonhosted.org/packages/08/a5/1f48fe647473a2dcccfd1839b2ff2c78eb57009be776b4da071e901c9bff/greenlet-3.5.6-cp314-cp314t-win_amd64.whl", hash = "sha256:886bcf1870af74c32bc310fd00a6b803445e17e51b7d5a107c7b35c0f362cc16", size = 331574, upload-time = "2026-09-14T14:27:18.451Z" },
{ url = "https://files.pythonhosted.org/packages/cd/72/3882855a75838faeb54a58aeef4fd77d20b2a86d4bad570c70d41b565dcf/greenlet-3.5.6-cp315-cp315-macosx_11_0_universal2.whl", hash = "sha256:3ac3494c381dab876cad7d0b22f3a722f3e0c8deb3a65b9e7f35ad7f58b8fcb3", size = 295926, upload-time = "2026-09-14T14:27:21.16Z" },
{ url = "https://files.pythonhosted.org/packages/10/1f/be4d957d8a9b90bcbe8db206548a42134d96222d43e5ed3fc4708fb6e24b/greenlet-3.5.6-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:602024dae6d77e161f4b89491b62ca1d4f19949d79d47b2db057e476d21179d6", size = 666910, upload-time = "2026-09-14T15:12:07.901Z" },
{ url = "https://files.pythonhosted.org/packages/a1/af/60d62571a7d6de961e4ce7625d6c2faf359345659fc782d2cdf517c34577/greenlet-3.5.6-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f8e63209c3e1e828ee6a457529b4a6d8b05d050fe0ae03a7ae49e967c5d312e0", size = 677415, upload-time = "2026-09-14T15:20:48.817Z" },
{ url = "https://files.pythonhosted.org/packages/f5/41/b3114c97c10e796010f00a30f51c81470072bca4b53e396ccca87484fcf7/greenlet-3.5.6-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9133d68624b1f2e89ec2f554d56aea8a5b0d7168cd9320200ba58d4d794845a4", size = 681337, upload-time = "2026-09-14T15:25:12.812Z" },
{ url = "https://files.pythonhosted.org/packages/fb/16/ac9e547b611539aaed1870eb1d6ddc57abdd5924b3a99bb9b5f0b44176b8/greenlet-3.5.6-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccadce0130fd813ec86ebfe969a6c58b42acc1d0fe55a47525375b740e07b605", size = 675927, upload-time = "2026-09-14T14:36:05.34Z" },
{ url = "https://files.pythonhosted.org/packages/48/1b/d41861c2fa00968e39e467a495ca8db9ce9b6310a5d9b57561b3d0dc48fa/greenlet-3.5.6-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:5adcbbfe78bdc242c71740a02e0991cc1b2f34d33c8bb15ca45eee8fd1140942", size = 487339, upload-time = "2026-09-14T15:28:43.497Z" },
{ url = "https://files.pythonhosted.org/packages/c4/b1/b7ba08d6431121741f1d30be0d5d292e76873325179a63586cd9217b62f6/greenlet-3.5.6-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9297fb9c39b9a2c039dbcd306c410bd6906b95244dec3bba4318d36c718c164c", size = 1637236, upload-time = "2026-09-14T15:10:12.442Z" },
{ url = "https://files.pythonhosted.org/packages/af/c5/3b1cbc68f0c082022fc8717f7fe4b8b13b8d583c52352be37f4e9f55bcd2/greenlet-3.5.6-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:b374e79ffa7511afc11773aef40a4ccea6191fba1c856ea2f9c56738dca69d7a", size = 1698526, upload-time = "2026-09-14T14:35:56.039Z" },
{ url = "https://files.pythonhosted.org/packages/de/56/12941ed2711400451c89d544e10f831800a2770f19dd55eac8f0f7f2003b/greenlet-3.5.6-cp315-cp315-win_amd64.whl", hash = "sha256:7969bffa322c097bd46ae595ada6a931cefda613f18ba64587e9cff4cb320756", size = 327739, upload-time = "2026-09-14T14:23:55.768Z" },
@@ -1075,9 +1065,7 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/16/c2/86cfc5555a98e12b86966ddbd24fd39af32f71f2f785c6595b7feb2db156/greenlet-3.5.6-cp315-cp315t-macosx_11_0_universal2.whl", hash = "sha256:de3de000d459402cda015068fd135aa50c0bf6f2477a80d4da1e646f123b4e78", size = 306244, upload-time = "2026-09-14T14:27:57.565Z" },
{ url = "https://files.pythonhosted.org/packages/14/6d/83ffc9d05a75a80ab3a7595dbb1d9604e5d4fc2996d73a8ae2dbd1284900/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45663c01a4de48b9a64a2ee1509d92d1dfd3afb02b2ccfc9333029d11aef996a", size = 676578, upload-time = "2026-09-14T15:12:09.468Z" },
{ url = "https://files.pythonhosted.org/packages/5d/d6/c2cf684810e5caded075970aaadea654ecb58b8382b9aecf1d231b936894/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3deccbb57a481e3a408fe61cdfd5c13e0678fc0a30fdd09597917ca87b4be877", size = 684203, upload-time = "2026-09-14T15:20:50.261Z" },
{ url = "https://files.pythonhosted.org/packages/f2/d1/039c353d5593a97a89699e989324c9bc86af499e6c6152fe0180f5742204/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:63aff70fe5aac59c72215f42ec39fcb59ff46774fa966e717f8ecb6ee2273577", size = 686023, upload-time = "2026-09-14T15:25:14.528Z" },
{ url = "https://files.pythonhosted.org/packages/62/19/00e1bee5d2af890dc8f400b54d0b0f9b489965f92bc12b407ff72cc6f469/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:311018b46472fb26ee85870847fb89eb64cc8aaddb617400789d87076f7cfeec", size = 681253, upload-time = "2026-09-14T14:36:06.742Z" },
{ url = "https://files.pythonhosted.org/packages/8a/62/97ceb8e0b2ea96046cdf8e95b042715020ebb12d83ea0690db80a8f03d23/greenlet-3.5.6-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:520648db8fb92eef7b3e6013f5a6f901cdf0d6685f639c2f7a245879f865bef7", size = 517058, upload-time = "2026-09-14T15:28:44.924Z" },
{ url = "https://files.pythonhosted.org/packages/89/58/c9275fd0ca195d1d3402931bcce8cfcc74726ff76efb1883d229e6e1a3d7/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:7f924a5a9d5890649566f2f6682e0d8ad8ca23028bacffbbac36dbd7fd680176", size = 1645988, upload-time = "2026-09-14T15:10:13.758Z" },
{ url = "https://files.pythonhosted.org/packages/e0/36/b35747582fa4f1a5453f8f3002405dbac788e450cec7674dc2d204b6ccb5/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:de9923832f2d8c1a5ecd8d7260465a6ca5a86888a0d129e3bd5cf0406d2fc5bf", size = 1702383, upload-time = "2026-09-14T14:35:58.143Z" },
{ url = "https://files.pythonhosted.org/packages/ed/69/6ec22ac9351e474d2a134d0ff9400dc80362d1c20f0721088ffffdfc205b/greenlet-3.5.6-cp315-cp315t-win_amd64.whl", hash = "sha256:2ab5f42ac6c238eb71770715e6e909ad9a1a92b6c681ccb64cd5a0f07edb953f", size = 331845, upload-time = "2026-09-14T14:27:41.723Z" },
@@ -1611,7 +1599,11 @@ dependencies = [
{ name = "apache-hamilton" },
{ name = "extraction" },
{ name = "mlflow" },
{ name = "pandas" },
{ name = "pandera" },
{ name = "persistance" },
{ name = "pyarrow" },
{ name = "scikit-learn" },
]
[package.optional-dependencies]
@@ -1625,7 +1617,11 @@ requires-dist = [
{ name = "extraction", editable = "../Extraction" },
{ name = "mlflow", specifier = ">=2.9" },
{ name = "onnx", marker = "extra == 'export'", specifier = ">=1.15" },
{ name = "pandas", specifier = ">=2.0" },
{ name = "pandera", specifier = ">=0.20" },
{ name = "persistance", editable = "../Persistance" },
{ name = "pyarrow", specifier = ">=15" },
{ name = "scikit-learn", specifier = ">=1.4" },
]
provides-extras = ["export"]
+16 -5
View File
@@ -12,7 +12,9 @@ from webapi.blueprints.governance import governance_bp
from webapi.blueprints.imports import imports_bp
from webapi.blueprints.reportes import reportes_bp
from webapi.blueprints.tea import tea_bp
from webapi.seguimiento import blueprint_de_seguimiento, en_dev
from webapi.seguimiento import blueprint_de_seguimiento
from webapi.seguimiento_cama import blueprint_seguimiento_cama
from webapi.cama_analysis import analysis as cama_analysis
class IsoJSONProvider(DefaultJSONProvider):
@@ -33,6 +35,9 @@ class IsoJSONProvider(DefaultJSONProvider):
def create_app() -> Flask:
app = Flask(__name__)
app.json = IsoJSONProvider(app)
from webapi.cama_runtime import configure_cama_cohort
configure_cama_cohort(app)
# File sources travel inside the request; cap them per request.
app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024
@@ -72,15 +77,21 @@ def create_app() -> Flask:
app.register_blueprint(cacu_bp, url_prefix="/cacu")
app.register_blueprint(cama_bp, url_prefix="/cama")
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix="/cama")
app.register_blueprint(cama_analysis, url_prefix="/cama")
app.register_blueprint(tea_bp, url_prefix="/tea")
app.register_blueprint(imports_bp, url_prefix="/imports")
app.register_blueprint(data_bp, url_prefix="/data")
app.register_blueprint(governance_bp, url_prefix="/governance")
app.register_blueprint(reportes_bp, url_prefix="/reportes")
# Patient-level follow-up list: only in DEV, with simulated data.
if en_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(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu")
from webapi.patient_risk import patient_risk_blueprint
app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
return app
+42 -1
View File
@@ -4,9 +4,11 @@ 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
from indicadores_kit.registry.catalogos import CatalogoInvalido
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
@@ -14,6 +16,7 @@ from webapi.imports.connectors.pdf import PdfConnector
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.services.import_service import (
DatabaseRefused,
ImportRequestError,
@@ -251,11 +254,13 @@ 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?}`.
`files` may be `sql` instead: `{connection details, table|query, column,
key_column}`, one document per row (a PDF or plain-text column).
Each record comes back with per-field confidence and evidence, conflicts
between sources, and the images found on its pages."""
body = _json_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))
@@ -302,6 +307,41 @@ def validate():
)
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
"""For every `document` source in the request (uploaded, or reading a
SQL column — same connector either way), writes the captions no known
field claimed straight into the silver layer (`catalog_commit_service`),
matched or minted against the project's catalog. 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("source_type") != "document":
continue
target = raw.get("target") or ""
domain = target.split(".", 1)[0]
if not domain:
continue
payload = {**(raw.get("payload") or {}), "target": target}
try:
connector = build_connector("document", payload)
result = commit_discovered_fields(connector.records, proyecto=domain, estudio_id=payload.get("estudio_id"))
except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError) 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,
}
)
return reports
@imports_bp.post("/commit")
def commit():
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
@@ -333,6 +373,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,
+168
View File
@@ -0,0 +1,168 @@
"""Aggregate and select the breast cohort through the same configured reader."""
from datetime import date
import hashlib
import hmac
import json
from flask import Blueprint, current_app, jsonify, request
from webapi.cama_cohort import COHORT, SCENARIO, THRESHOLD
analysis = Blueprint('cama_analysis', __name__)
BIRADS = ('BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6')
AGES = ('MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO')
class SelectionError(Exception):
def __init__(self, message, status=400):
self.message, self.status = message, status
def read_cohort(cutoff):
reader = current_app.config.get('CAMA_COHORT_READER')
if not callable(reader):
raise SelectionError('Cohorte no disponible', 503)
try:
return reader(cutoff)
except Exception:
current_app.logger.exception('Breast cohort provider failed')
raise SelectionError('Cohorte no disponible', 503) from None
def cutoff_arg(args):
text = args.get('corte')
if not text:
raise SelectionError('Se requiere corte')
try:
value = date.fromisoformat(text)
if value.isoformat() != text or value.year == 9999:
raise ValueError()
return value
except ValueError:
raise SelectionError('Corte inválido') from None
def patient_access():
check = current_app.config.get('CAMA_COHORT_ACCESS')
if check is not None and (not callable(check) or not check(request)):
raise SelectionError('Acceso no autorizado', 403)
def revision_of(rows):
"""Identify the materialized cohort without exposing its patient identifiers."""
encoded = json.dumps(rows, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()
return hashlib.sha256(encoded).hexdigest()
def cohort_request(args):
allowed = {'cohorte', 'revision', 'escenario', 'corte', 'meses', 'page', 'page_size', 'birads', 'grupo_edad'}
if set(args) - allowed or any(len(args.getlist(k)) != 1 for k in args):
raise SelectionError('Parámetros desconocidos o repetidos')
if args.get('cohorte') != COHORT or args.get('escenario') != SCENARIO:
raise SelectionError('Cohorte o escenario desconocido')
revision = args.get('revision', '')
if len(revision) != 64 or any(c not in '0123456789abcdef' for c in revision):
raise SelectionError('Revisión de cohorte inválida')
cutoff = cutoff_arg(args)
try:
months = int(args.get('meses', '3'))
page = int(args.get('page', '1'))
size = int(args.get('page_size', '50'))
if months not in (0, 1, 3, 6, 12) or page < 1 or not 1 <= size <= 200:
raise ValueError()
except ValueError:
raise SelectionError('Ventana o paginación inválida') from None
filters = {key: args.get(key) for key in ('birads', 'grupo_edad')}
if filters['birads'] not in (None, *BIRADS) or filters['grupo_edad'] not in (None, *AGES):
raise SelectionError('Filtro inválido')
return cutoff, months, page, size, filters, revision
def selected(args):
patient_access()
from werkzeug.datastructures import MultiDict
args = MultiDict(args)
if 'cohorte' not in args:
if any(key in args for key in ('revision', 'escenario')):
raise SelectionError('Contexto de cohorte incompleto')
if 'corte' not in args:
args['corte'] = date.today().isoformat()
cutoff = cutoff_arg(args)
rows = read_cohort(cutoff)
args.update({'cohorte': COHORT, 'escenario': SCENARIO, 'revision': revision_of(rows)})
else:
rows = None
cutoff, months, page, size, filters, revision = cohort_request(args)
if rows is None:
rows = read_cohort(cutoff)
if not hmac.compare_digest(revision, revision_of(rows)):
raise SelectionError('La cohorte cambió; actualiza el análisis', 409)
selected_rows = [row for row in rows if all(v is None or row[k] == v for k, v in filters.items())]
if months:
from webapi.seguimiento_cama import _desde
try:
since = _desde(cutoff, months)
except (ValueError, OverflowError):
raise SelectionError('Ventana inválida') from None
else:
since = min((date.fromisoformat(r['mastografia_fecha']) for r in rows), default=cutoff)
selected_rows = [r for r in selected_rows if since <= date.fromisoformat(r['mastografia_fecha']) <= cutoff]
# Every filtered selection is checked on the server after applying the window.
if len(selected_rows) < THRESHOLD and (selected_rows or any(filters.values())):
raise SelectionError('Selección no disponible', 403)
return cutoff, months, page, size, filters, since, selected_rows, revision
def selection_response(args, mode, patient=None):
cutoff, months, page, size, filters, since, rows, revision = selected(args)
options = [('birads', 'Categoría BI-RADS', BIRADS), ('grupo_edad', 'Grupo de edad', AGES)]
columns = [
{'clave': 'pac_id', 'etiqueta': 'Identificador de paciente'},
{'clave': 'grupo_edad', 'etiqueta': 'Grupo de edad'},
{'clave': 'birads', 'etiqueta': 'Última mastografía', 'detalles': [{'clave': 'mastografia_fecha', 'etiqueta': 'Fecha'}]},
{'clave': 'biopsia', 'etiqueta': 'Resultado histopatológico', 'detalles': [{'clave': 'biopsia_fecha', 'etiqueta': 'Fecha de reporte'}]},
]
meta = {'simulado': True, 'cohorte': COHORT, 'revision': revision, 'escenario': SCENARIO, 'corte': cutoff.isoformat(),
'ventana': {'meses': months, 'desde': since.isoformat(), 'hasta': cutoff.isoformat()},
'campo_ventana': 'mastografia_fecha', 'filtros': filters,
'filtros_disponibles': [{'clave': k, 'etiqueta': label, 'opciones': [{'codigo': v, 'etiqueta': v} for v in values]}
for k, label, values in options], 'columnas': columns}
if mode == 'patient':
found = next((row for row in rows if row['pac_id'] == patient), None)
if found is None:
raise SelectionError('Paciente no encontrado', 404)
return jsonify(**meta, item=found)
if mode == 'export':
if len(rows) > 5000:
raise SelectionError('La exportación supera el límite de 5000 registros', 413)
return jsonify(**meta, total_items=len(rows), items=rows)
return jsonify(**meta, paginacion={'page': page, 'page_size': size, 'total_items': len(rows),
'total_pages': (len(rows) + size - 1) // size},
items=rows[(page - 1) * size:page * size])
@analysis.get('/analisis/indicadores')
def indicators():
try:
if set(request.args) != {'corte'} or len(request.args.getlist('corte')) != 1:
raise SelectionError('Se requiere únicamente corte')
cutoff = cutoff_arg(request.args)
rows = read_cohort(cutoff)
groups = []
for code in BIRADS:
count = sum(r['birads'] == code for r in rows)
groups.append({'codigo': code, 'n': count if count >= THRESHOLD else None, 'suprimido': count < THRESHOLD})
return jsonify(simulado=True, cohorte=COHORT, revision=revision_of(rows), escenario=SCENARIO, corte=cutoff.isoformat(),
horizonte_dias=0, umbral_supresion=THRESHOLD, unidad='paciente',
denominador='pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
indicadores=[], grupos=groups)
except SelectionError as e:
return jsonify(error=e.message), e.status
@analysis.after_request
def no_cache(response):
response.headers['Cache-Control'] = 'no-store'
return response
+136
View File
@@ -0,0 +1,136 @@
"""Read the breast screening cohort from the existing silver tables.
The current silver tables keep only the last version of each fact. Filtering by
load date prevents future facts from appearing at an earlier cutoff, but cannot
restore a previous value after an update.
"""
from datetime import date, datetime, time, timedelta, timezone
from sqlalchemy import select
from indicadores_kit.cama.consultas.plata import biopsias, mastografias
from indicadores_kit.cama.familias.histopatologia_birads.consulta import BIRADS
from indicadores_kit.cama.tablas import TABLAS
COHORT = "cama_birads_v1"
SCENARIO = "diagnostico"
THRESHOLD = 5
def _date(value):
return date.fromisoformat(value) if isinstance(value, str) else value
def _known(value, cutoff):
if value is None:
return False
if isinstance(value, str):
value = datetime.fromisoformat(value)
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value < datetime.combine(cutoff + timedelta(days=1), time.min, timezone.utc)
def _age_group(birth, cutoff):
if birth is None or birth > cutoff:
return "SIN_DATO"
age = cutoff.year - birth.year - ((cutoff.month, cutoff.day) < (birth.month, birth.day))
if age < 40:
return "MENOR_40"
if age >= 70:
return "70+"
return f"{age // 10 * 10}-{age // 10 * 10 + 9}"
class CamaCohort:
"""Materialize one row per eligible patient, using a caller-owned session."""
def __init__(self, session):
self.session = session
def rows(self, cutoff: date):
t = TABLAS
loads = {x.carga_id: x.inicio for x in self.session.execute(select(t.Carga)).scalars()}
procedures = {x.procedimiento_id: x for x in self.session.execute(select(t.Procedimiento)).scalars()}
observations = {(x.procedimiento_id, x.resultado_id): x for x in self.session.execute(select(t.Observacion)).scalars()}
people = {x.pac_id: x for x in self.session.execute(select(t.Persona)).scalars()}
def procedure_known(identifier):
p = procedures.get(identifier)
return bool(p and _known(loads.get(p.carga_id), cutoff))
def observation_known(identifier, result, patient):
o = observations.get((identifier, result))
return bool(o and o.pac_id == patient and _known(loads.get(o.carga_id), cutoff))
def load_time(record):
value = loads.get(record.carga_id) if record else None
return value.isoformat() if value else None
candidates = {}
for row in self.session.execute(select(mastografias(t))).mappings():
taken, reported = _date(row['fecha_toma']), _date(row['fecha_reporte'])
if not (taken and reported and taken <= reported <= cutoff and row['birads']
and procedure_known(row['procedimiento_id']) and procedure_known(row['reporte_id'])
and procedures[row['reporte_id']].pac_id == row['pac_id']
and observation_known(row['reporte_id'], 'mastografia.birads', row['pac_id'])):
continue
key = (taken, str(row['fuente_id']), reported, row['reporte_id'])
prior = candidates.get(row['pac_id'])
if prior is None or key > prior[0]:
candidates[row['pac_id']] = (key, row)
reports = {}
orders = {}
for p in procedures.values():
when = _date(p.fecha)
if (p.estudio_id != 'biopsia' or p.clase != 'orden' or not p.padre_id or not when
or when > cutoff or not procedure_known(p.procedimiento_id)):
continue
key = (p.pac_id, p.padre_id)
rank = (when, str(p.fuente_id), p.procedimiento_id)
if key not in orders or rank > orders[key][0]:
orders[key] = (rank, p)
for row in self.session.execute(select(biopsias(t))).mappings():
reported, ordered, taken = (_date(row['fecha_reporte']), _date(row['fecha_solicitud']),
_date(row['fecha_toma']))
procedure = procedures.get(row['procedimiento_id'])
order = procedures.get(procedure.padre_id) if procedure else None
if not (taken and reported and ordered and taken <= ordered <= reported <= cutoff and row['toma_id']
and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id'])
and order and order.pac_id == row['pac_id'] and procedure_known(order.procedimiento_id)):
continue
key = (row['pac_id'], row['toma_id'])
rank = (reported, str(row['fuente_id']), row['procedimiento_id'])
if key not in reports or rank > reports[key][0]:
reports[key] = (rank, row)
rows = []
for patient, (_, m) in candidates.items():
code = BIRADS.get(m['birads'])
if not code or patient not in people:
continue
b = reports.get((patient, m['procedimiento_id']))
b = b[1] if b and _date(b[1]['fecha_reporte']) >= _date(m['fecha_toma']) else None
order = procedures[procedures[b['procedimiento_id']].padre_id] if b else None
if not order:
found_order = orders.get((patient, m['procedimiento_id']))
order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None
grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None
rows.append({
'pac_id': str(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(),
'mastografia_reporte_fecha': _date(m['fecha_reporte']).isoformat(),
'birads': code, 'grupo_edad': _age_group(people[patient].fecha_nacimiento, cutoff),
'biopsia': grade, 'biopsia_fecha': _date(b['fecha_reporte']).isoformat() if b else None,
'biopsia_solicitud_fecha': _date(order.fecha).isoformat() if order else None,
'toma_carga_inicio': load_time(procedures[m['procedimiento_id']]),
'mastografia_reporte_carga_inicio': load_time(procedures[m['reporte_id']]),
'birads_carga_inicio': load_time(observations.get((m['reporte_id'], 'mastografia.birads'))),
'biopsia_solicitud_carga_inicio': load_time(order),
'biopsia_reporte_carga_inicio': load_time(procedures[b['procedimiento_id']]) if b else None,
'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado')))
if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None,
})
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id'])))
+12
View File
@@ -0,0 +1,12 @@
"""Configure the breast cohort using the shared persistence settings."""
from persistance.db import get_cama_session
from webapi.cama_cohort import CamaCohort
def configure_cama_cohort(app):
def read(cutoff):
with get_cama_session() as session:
return CamaCohort(session).rows(cutoff)
app.config['CAMA_COHORT_READER'] = read
+47 -8
View File
@@ -12,6 +12,7 @@ from extraction.segmentation import SEGMENTERS
from webapi.imports.connectors.base import decode_file
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.registry import ENTITY_REGISTRY
@@ -48,16 +49,49 @@ class _ResultCache:
_CACHE = _ResultCache()
def _files_from_sql(sql: dict[str, Any]) -> list[tuple[str, bytes]]:
"""One `(name, bytes)` per row of a SQL source (connected the same way
`SqlConnector` is): `column` is the field bundle (a `varbinary(max)`
PDF, or already a plain string — `read_document` reads either), and
`key_column` names the row (a patient or study id) for tracing. Any
column type `SqlConnector` can read works; it's not limited to PDFs."""
column = sql.get("column")
if not column:
raise ConnectorError("falta column")
if not sql.get("query") and not sql.get("table"):
raise ConnectorError("falta table o query")
key_column = sql.get("key_column") or column
if key_column == column:
raise ConnectorError("key_column debe ser distinta de column")
connector = SqlConnector.connect(sql)
connector = (
connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema"))
)
files = []
for row in connector.read_rows({column: "contenido", key_column: "clave"}):
raw = row.get("contenido")
if raw is None:
continue
name = str(row.get("clave", len(files) + 1))
files.append((name, raw if isinstance(raw, bytes) else str(raw).encode("utf-8")))
return files
@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.
@@ -65,7 +99,7 @@ class DocumentConnector(DataFrameConnector):
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())
@@ -103,7 +137,12 @@ class DocumentConnector(DataFrameConnector):
@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"):
files = _files_from_sql(payload["sql"])
else:
files = [
(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)
]
return cls(
files,
target=payload["target"],
+151
View File
@@ -0,0 +1,151 @@
"""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 indicadores_kit.plata.procedimiento import valor_de_observacion
from indicadores_kit.registry.catalogos import Catalogo, add_resultado
# `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
) -> list[MatchedField]:
"""One `MatchedField` per discovered caption, in order.
`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
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
@@ -0,0 +1,114 @@
"""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
or minted against the project's catalog (`catalog_matching`).
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.orquestacion`'s `cargar` 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 indicadores_kit.plata.procedimiento import LotePlata
from indicadores_kit.registry.catalogos import Catalogo, catalogo_desde_toml, ruta_de_catalogo
from indicadores_kit.tablas import tablas_de
from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint
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
def commit_discovered_fields(
records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None
) -> 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."""
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)
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.guardar_carga(
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.catalogo_repository.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores)
+49
View File
@@ -0,0 +1,49 @@
"""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, 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.
"""
from datetime import timezone
from flask import Blueprint, jsonify
COHORT_URL = "cacu/cohorte_vigilancia"
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"`. `repositories` is `persistance.cacu`."""
blueprint = Blueprint("cacu_patient_risk", __name__)
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
def get_patient_risk(pac_id: int):
"""A patient's cohort membership and risks in the current batch (DEV only, simulated data)."""
if repositories.persona_repository.get(pac_id) is None:
return jsonify({"error": f"no existe la paciente {pac_id}"}), 404
membership = repositories.cohorte_repository.membership(pac_id, COHORT_URL)
risk = repositories.cohorte_repository.current_risk(pac_id)
return jsonify({"simulado": True, "cohorte": _cohort(membership), "riesgo": _risk(risk)})
return blueprint
def _cohort(membership) -> dict | None:
if membership is None:
return None
return {"url": membership.url, "version": membership.version, "fecha_indice": membership.fecha_indice.isoformat(),
**{name: membership.variables.get(name) for name in COHORT_VARIABLES}}
def _risk(risk) -> dict | None:
if risk is None:
return None
evaluated = risk.evaluado_en if risk.evaluado_en.tzinfo else risk.evaluado_en.replace(tzinfo=timezone.utc)
return {"lote_id": risk.lote_id, "modelo_nombre": risk.modelo_nombre, "modelo_version": risk.modelo_version,
"evaluado_en": evaluated.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"estado_lote": risk.estado_lote,
"horizontes": [{"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
"ic_alto": h.ic_alto, "estado": h.estado} for h in risk.horizontes]}
+8 -8
View File
@@ -1,16 +1,16 @@
"""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 (`indicadores_kit.serving.seguimiento`); aquí solo se valida,
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. La lista la arma el kit (`indicadores_kit.serving.seguimiento`); 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 +19,16 @@ from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seg
from sqlmodel import Session
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
SAL_POR_OMISION = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
def en_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("en_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2)
return bool(os.environ.get("DEV_REVISION"))
def blueprint_de_seguimiento(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 +39,7 @@ def blueprint_de_seguimiento(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", SAL_POR_OMISION), **pedido)
cuerpo = seguimiento_de(sesion, **pedido)
except PedidoInvalido as error:
return jsonify({"error": str(error)}), 400
except PaginaFuera as error:
+46
View File
@@ -0,0 +1,46 @@
"""Patient follow-up for the configured breast cohort."""
import calendar
from datetime import date, timedelta
from flask import Blueprint, jsonify, request
from webapi.cama_analysis import SelectionError, selection_response
def _desde(corte, meses):
indice = corte.year * 12 + corte.month - 1 - meses
anio, mes = divmod(indice, 12)
if anio < 1:
raise ValueError("la ventana excede el rango de fechas admitido")
anterior = date(anio, mes + 1, min(corte.day, calendar.monthrange(anio, mes + 1)[1]))
return anterior + timedelta(days=1)
def blueprint_seguimiento_cama():
blueprint = Blueprint("cama_seguimiento", __name__)
@blueprint.after_request
def no_cache(response):
response.headers["Cache-Control"] = "no-store"
return response
def respond(mode, patient=None):
try:
return selection_response(request.args, mode, patient)
except SelectionError as error:
return jsonify(error=error.message), error.status
@blueprint.get("/seguimiento")
def seguimiento():
return respond('list')
@blueprint.get("/seguimiento/exportacion")
def exportacion():
return respond('export')
@blueprint.get("/pacientes/<pac_id>")
def paciente(pac_id):
return respond('patient', pac_id)
return blueprint