Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 10f0c59975 | |||
| 1d8cd264b8 | |||
| 46eb3dfc31 | |||
| 9c0e03f947 | |||
| 6d32115eca | |||
| 06dd74cdb6 | |||
| eeb55c4255 | |||
| 2ca86232c9 | |||
| 8b47f1522d | |||
| 7bc214b50c | |||
| 1d5f1e0cc4 | |||
| ca54656124 | |||
| 102999c8de | |||
| 7798d007d1 | |||
| c72c03988e | |||
| 91537e9efd | |||
| f11abd8f6e | |||
| 6afe329e52 | |||
| 96a29cfb19 | |||
| b9adedbf6f | |||
| 0cbe390b25 | |||
| 0f00a975fa |
@@ -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).
|
||||
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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": []
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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'}
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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"])
|
||||
+19
-20
@@ -2,9 +2,8 @@
|
||||
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
|
||||
there.
|
||||
|
||||
Fixtures: `client`, a DEV client over the kit's CaCu demonstration database (`conftest.cliente_de`) plus `seeded`:
|
||||
a surveillance build with two of its patients, one of them with variables and a confirmed batch; `fuera_de_dev`, the
|
||||
same app without `DEV_REVISION`.
|
||||
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
|
||||
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
@@ -19,8 +18,9 @@ HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@@ -55,17 +55,11 @@ def seeded(client):
|
||||
return scored, unscored, outside
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
||||
"""Pins down: the body has `simulado`, `cohorte` and `riesgo` with exactly the contract's fields, the horizons in
|
||||
ascending order, probabilities in 0..1 and the date as ISO-8601 UTC. Fails if a field is renamed or dropped, which
|
||||
would break the WebApp's validation."""
|
||||
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
|
||||
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
|
||||
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
|
||||
the WebApp's validation."""
|
||||
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
|
||||
|
||||
body = response.get_json()
|
||||
@@ -78,6 +72,17 @@ def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
||||
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."""
|
||||
@@ -91,9 +96,3 @@ def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
|
||||
def test_an_unknown_patient_is_404(client, seeded):
|
||||
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
|
||||
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
|
||||
|
||||
|
||||
def test_outside_dev_the_route_does_not_exist(fuera_de_dev):
|
||||
"""Pins down: without `DEV_REVISION` the route isn't registered. Fails if patient-level risks are served outside
|
||||
the simulated DEV deployment."""
|
||||
assert fuera_de_dev.get("/cacu/pacientes/1/riesgo").status_code == 404
|
||||
|
||||
+16
-14
@@ -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()
|
||||
|
||||
@@ -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'}
|
||||
+15
-9
@@ -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,20 +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 and individual risk: 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 persistance import cacu as cacu_repositories
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
from webapi.patient_risk import patient_risk_blueprint
|
||||
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu")
|
||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -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'])))
|
||||
@@ -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
|
||||
@@ -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"],
|
||||
|
||||
@@ -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)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`, only in DEV.
|
||||
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`.
|
||||
|
||||
The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance
|
||||
cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed
|
||||
evaluation. Patient data: **registered only in DEV** (`DEV_REVISION`), on simulated data, and every response carries
|
||||
`simulado: true`. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
|
||||
evaluation. Patient data, on simulated data: every response carries `simulado: true`. The route is always registered;
|
||||
who may see it is an access rule still to be defined. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
|
||||
removed or renamed, only added.
|
||||
"""
|
||||
|
||||
@@ -16,7 +16,7 @@ COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0")
|
||||
|
||||
|
||||
def patient_risk_blueprint(repositories) -> Blueprint:
|
||||
"""The blueprint, to register with `url_prefix="/cacu"` only in DEV. `repositories` is `persistance.cacu`."""
|
||||
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
|
||||
blueprint = Blueprint("cacu_patient_risk", __name__)
|
||||
|
||||
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user