Integrate CaMa follow-up, descriptive analysis and L3 with dev

Preserve dev risk batches and governance, individual patient selection, optional access and explicit cohort reader overrides. Register one CaMa implementation and retain legacy Python blueprint consumers. Validated with 681 WebApi tests on the integrated parent and submodules.
This commit is contained in:
Angel Capetillo Zavala
2026-11-17 10:44:07 -06:00
parent 0571b5e6af
commit b1bbbc25b4
27 changed files with 2729 additions and 12 deletions
+9
View File
@@ -0,0 +1,9 @@
"""CaMa's follow-up list (`GET /cama/seguimiento`): the patients of the BI-RADS cohort at a cut-off, one row each.
cohort.py who is in the cohort at a cut-off and what each row shows
listing.py the selection (window, filters, suppression), the pages, the file and the revision
routes.py the routes: validate the request and answer
The cohort is read from dbt's `cama_cohorte_birads` view. Every response is marked `simulado`: the list holds
patient-level rows, and who may read it on real data is an access rule still to be defined.
"""
+8
View File
@@ -0,0 +1,8 @@
"""Retain dev's optional access callback; no new authentication policy."""
from flask import current_app, jsonify, request
def configured_access():
check = current_app.config.get('CAMA_COHORT_ACCESS')
if check is not None and (not callable(check) or not check(request)):
return jsonify(error='Acceso no autorizado'), 403
+146
View File
@@ -0,0 +1,146 @@
"""The BI-RADS cohort at a cut-off.
Each patient counts once, through her latest mammogram whose report (with a BI-RADS) is dated on or before the cut-off;
she belongs to the cohort when that BI-RADS is one of `cama.birads_4_a_6`. The latest is the one with the latest
date taken, then the greatest source id, then the latest report date, then the greatest report id, so the same data
always gives the same cohort. A report that carries two different BI-RADS counts through the more severe one
(`cama.birads_gravedad`), and a biopsy report with two different grades through the more severe grade. The biopsy
shown is the latest report, on or before the cut-off and not before the mammogram, of a biopsy that mammogram led to.
Facts are read as silver holds them now: the list is not a reconstruction of what was known on the cut-off.
"""
from dataclasses import dataclass
from datetime import date
from sqlalchemy import Date, Integer, String, column, func, inspect, select, table
from sqlmodel import Session
from webapi.orchestration.reference.age_groups import grupos_de_cortes
from webapi.orchestration.reference.rules import valor_de
from webapi.orchestration.tables.cama import TABLAS
COHORTE = "cama_birads_v1"
ESCENARIO = "diagnostico"
VERSION = "0.1.0"
SIN_DATO = "SIN_DATO"
SIN_BIOPSIA = "SIN_BIOPSIA"
# Grades from least to most severe, for two contradictory results of the same report; any other grade ranks lowest.
GRADOS_POR_GRAVEDAD = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR")
CANDIDATOS = table(
"cama_cohorte_birads",
column("pac_id", Integer), column("procedimiento_id", Integer), column("fuente_id", String),
column("fecha_toma", Date), column("reporte_id", Integer), column("fecha_reporte", Date), column("birads", String),
column("fecha_nacimiento", Date), column("biopsia_id", Integer), column("biopsia_fuente_id", String),
column("biopsia_fecha_reporte", Date), column("biopsia_grado", String),
)
class CohorteNoDisponible(RuntimeError):
"""The cohort's view isn't in the database: the indicator cycle that creates the event views hasn't run (503)."""
def disponible(sesion: Session) -> bool:
return inspect(sesion.get_bind()).has_table(CANDIDATOS.name)
@dataclass(frozen=True)
class Fila:
"""One patient of the cohort: the codes the list shows and filters by."""
pac_id: int
mastografia_fecha: date
birads: str
grupo_edad: str
biopsia: str | None
biopsia_fecha: date | None
# The earliest eligible biopsy report, and the earliest one whose grade counts as cancer (`cama.biopsia_cancer`).
primera_biopsia_fecha: date | None = None
primer_maligno_fecha: date | None = None
@property
def resultado(self) -> str:
"""The value the biopsy filter compares: the grade, `SIN_DATO` for a report without one, `SIN_BIOPSIA` for none."""
if self.biopsia_fecha is None:
return SIN_BIOPSIA
return self.biopsia or SIN_DATO
def _rango_de_grado(grado: str | None) -> int:
return GRADOS_POR_GRAVEDAD.index(grado) if grado in GRADOS_POR_GRAVEDAD else -1
def codigo_birads(fuente: str) -> str:
"""`B4A` as the list names it: `BIRADS_4A`."""
return "BIRADS_" + fuente[1:]
def grupos_de_edad(sesion: Session) -> list[str]:
"""The age groups of `cama.grupos_edad` in order, with the open ones at both ends (`<40`, `40-49`, ..., `70+`)."""
cortes = valor_de(sesion, "cama.grupos_edad", tablas=TABLAS)
return [g.etiqueta for g in sorted(grupos_de_cortes(cortes, tablas=TABLAS), key=lambda g: g.edad_min)]
def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str:
"""The completed age at the cut-off in its group; `SIN_DATO` without a birth date or with one after the cut-off."""
if nacimiento is None or nacimiento > corte:
return SIN_DATO
edad = corte.year - nacimiento.year - ((corte.month, corte.day) < (nacimiento.month, nacimiento.day))
for grupo in grupos:
if grupo.edad_min <= edad <= grupo.edad_max:
return grupo.etiqueta
return SIN_DATO
def cohorte_al(sesion: Session, corte: date) -> list[Fila]:
"""The cohort at `corte`, latest mammogram first, then by `pac_id`."""
admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS))
malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS))
grupos = grupos_de_cortes(valor_de(sesion, "cama.grupos_edad", tablas=TABLAS), tablas=TABLAS)
c = CANDIDATOS.c
candidatas = sesion.execute(
select(CANDIDATOS).where(c.fecha_reporte <= corte, c.fecha_toma <= c.fecha_reporte)
).mappings().all()
gravedad = {codigo: rango for rango, codigo in enumerate(valor_de(sesion, "cama.birads_gravedad", tablas=TABLAS))}
por_mastografia: dict[tuple, dict] = {}
for fila in candidatas:
mastografia = por_mastografia.setdefault(
(fila["pac_id"], fila["procedimiento_id"], fila["reporte_id"], fila["birads"]), {"fila": fila, "biopsias": []})
# A biopsy report dated after the cut-off, or before the mammogram, doesn't exist for this list.
if fila["biopsia_id"] is not None and fila["fecha_toma"] <= fila["biopsia_fecha_reporte"] <= corte:
mastografia["biopsias"].append(fila)
mastografias: dict[int, tuple] = {}
for mastografia in por_mastografia.values():
fila = mastografia["fila"]
llave = (fila["fecha_toma"], str(fila["fuente_id"]), fila["fecha_reporte"], fila["reporte_id"],
gravedad.get(fila["birads"], -1))
if fila["pac_id"] not in mastografias or llave > mastografias[fila["pac_id"]][0]:
mastografias[fila["pac_id"]] = (llave, mastografia)
cohorte = []
for pac_id, (_, elegida) in mastografias.items():
fila = elegida["fila"]
if fila["birads"] not in admitidos:
continue
biopsia = max(elegida["biopsias"], key=lambda b: (b["biopsia_fecha_reporte"], str(b["biopsia_fuente_id"]), b["biopsia_id"],
_rango_de_grado(b["biopsia_grado"])), default=None)
cohorte.append(Fila(
pac_id=pac_id, mastografia_fecha=fila["fecha_toma"], birads=codigo_birads(fila["birads"]),
grupo_edad=grupo_de_edad(fila["fecha_nacimiento"], corte, grupos),
biopsia=biopsia["biopsia_grado"] if biopsia else None,
biopsia_fecha=biopsia["biopsia_fecha_reporte"] if biopsia else None,
primera_biopsia_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"]), default=None),
primer_maligno_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"] if b["biopsia_grado"] in malignos), default=None),
))
return sorted(cohorte, key=lambda f: (-f.mastografia_fecha.toordinal(), f.pac_id))
def construccion(sesion: Session) -> str:
"""The data the cohort stands on: the last load that added or changed rows (`carga-<id>`, `carga-0` without any)."""
carga = TABLAS.Carga
ultima = sesion.execute(
select(func.max(carga.carga_id)).where((carga.filas_nuevas > 0) | (carga.filas_cambiadas > 0))
).scalar()
return f"carga-{ultima or 0}"
+190
View File
@@ -0,0 +1,190 @@
"""The follow-up list and its file: the cohort at a cut-off, narrowed by a window and filters, in pages.
A selection of fewer patients than `comun.umbral_supresion` is never served: not as a page, not as a file, and not
through any combination of window and filters, which is what lets a small group be isolated. The whole cohort, with no
window and no filter, is the one selection that can be empty. The revision names the cohort, its version, the data it
stands on and the cut-off; a client that quotes another one is refused, so a page or a file always comes from the
cohort that was counted.
"""
import calendar
import hashlib
from datetime import date, timedelta
from sqlmodel import Session
from webapi.cama_follow_up.cohort import (
COHORTE, ESCENARIO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion,
disponible, grupos_de_edad,
)
from webapi.orchestration.reference.rules import valor_de
from webapi.orchestration.tables.cama import TABLAS
VENTANAS = (0, 1, 3, 6, 12)
VENTANA_POR_OMISION = 3
PAGINA_MAXIMA = 200
EXPORTACION_MAXIMA = 5000
GRADOS = {"BENIGNO": "Benigno", "CARCINOMA_IN_SITU": "Carcinoma in situ", "CARCINOMA_INVASOR": "Carcinoma invasor"}
COLUMNAS = [
{"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"}]},
]
class PedidoInvalido(ValueError):
"""A parameter outside what the contract admits (400)."""
class RevisionDistinta(ValueError):
"""The cohort, scenario or revision quoted is not the one the server holds (409)."""
class GrupoPequeno(ValueError):
"""The selection has too few patients to be published (403)."""
class PaginaFuera(LookupError):
"""A page past the last one, with patients (404)."""
class ExportacionGrande(ValueError):
"""More patients than a file may hold (413)."""
def _desde(corte: date, meses: int) -> date:
indice = corte.year * 12 + corte.month - 1 - meses
anio, mes = divmod(indice, 12)
if anio < 1:
raise PedidoInvalido("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 revision_de(construido: str, corte: date) -> str:
"""The digest of the cohort, its version, its data and the cut-off."""
return hashlib.sha256(f"{COHORTE}|{VERSION}|{construido}|{corte.isoformat()}".encode()).hexdigest()
def filtros_disponibles(sesion: Session) -> list[dict]:
"""The filters the list offers, with every value it accepts."""
edades = [*grupos_de_edad(sesion), SIN_DATO]
return [
{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [
{"codigo": codigo_birads(b), "etiqueta": "BI-RADS " + b[1:]}
for b in valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS)]},
{"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [
{"codigo": e, "etiqueta": "Sin dato" if e == SIN_DATO else e} for e in edades]},
{"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [
*({"codigo": g, "etiqueta": e} for g, e in GRADOS.items()),
{"codigo": SIN_DATO, "etiqueta": "Biopsia reportada sin resultado"},
{"codigo": SIN_BIOPSIA, "etiqueta": "Sin biopsia reportada"}]},
]
def _validar(sesion: Session, *, corte: date | None, meses: int | None, filtros: dict, hoy: date, page: int,
page_size: int) -> tuple[date, int, dict, list[dict]]:
meses = VENTANA_POR_OMISION if meses is None else meses
if meses not in VENTANAS:
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
corte = hoy if corte is None else corte
if corte > hoy:
raise PedidoInvalido(f"corte {corte.isoformat()} es posterior a hoy ({hoy.isoformat()}).")
disponibles = filtros_disponibles(sesion)
permitidos = {f["clave"]: {o["codigo"] for o in f["opciones"]} for f in disponibles}
for clave, valor in filtros.items():
if clave not in permitidos:
raise PedidoInvalido(f"filtro desconocido {clave!r}; hay {sorted(permitidos)}.")
if valor not in permitidos[clave]:
raise PedidoInvalido(f"{clave} desconocido: {valor!r}.")
return corte, meses, {c: filtros.get(c) for c in permitidos}, disponibles
def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict) -> tuple[list[Fila], date]:
desde = min((f.mastografia_fecha for f in cohorte), default=corte) if meses == 0 else _desde(corte, meses)
elegidas = [f for f in cohorte if desde <= f.mastografia_fecha <= corte
and all(valor is None or getattr(f, "resultado" if clave == "biopsia" else clave) == valor
for clave, valor in filtros.items())]
return elegidas, desde
def _item(f: Fila) -> dict:
return {"pac_id": str(f.pac_id), "grupo_edad": f.grupo_edad, "birads": f.birads,
"mastografia_fecha": f.mastografia_fecha.isoformat(), "biopsia": f.biopsia,
"biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None}
def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]:
if not disponible(sesion):
raise CohorteNoDisponible("la cohorte aún no está disponible: falta correr el ciclo de indicadores de CaMa")
corte, meses, filtros, disponibles = _validar(sesion, corte=corte, meses=meses, filtros=filtros,
hoy=hoy or date.today(), page=page, page_size=page_size)
actual = revision_de(construccion(sesion), corte)
if any(contexto) and not all(contexto):
raise PedidoInvalido("el contexto de la cohorte lleva cohorte, escenario y revisión juntos.")
if any(contexto) and contexto != (COHORTE, ESCENARIO, actual):
raise RevisionDistinta("la cohorte, el escenario o la revisión no son los que sirve el servidor para este corte")
elegidas, desde = _selecciona(cohorte_al(sesion, corte), corte=corte, meses=meses, filtros=filtros)
umbral = valor_de(sesion, "comun.umbral_supresion", tablas=TABLAS)
acotada = meses != 0 or any(v is not None for v in filtros.values())
if (elegidas and len(elegidas) < umbral) or (acotada and not elegidas):
raise GrupoPequeno(f"la selección tiene menos de {umbral} pacientes: su lista no se publica.")
cabecera = {
"simulado": True, "cohorte": COHORTE, "escenario": ESCENARIO, "revision": actual, "corte": corte.isoformat(),
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
"filtros": filtros, "filtros_disponibles": disponibles, "columnas": COLUMNAS,
}
return cabecera, elegidas
def seguimiento_de(sesion: Session, *, corte: date | None = None, meses: int | None = None, filtros: dict | None = None,
cohorte: str | None = None, escenario: str | None = None, revision: str | None = None,
page: int = 1, page_size: int = 50, hoy: date | None = None) -> dict:
"""A page of the list, ready for `json.dumps`.
Raises:
PedidoInvalido: a parameter out of range or unknown.
RevisionDistinta: the context quoted is not the server's.
GrupoPequeno: the selection has fewer patients than the suppression threshold.
PaginaFuera: `page` past the last page, with patients.
"""
cabecera, elegidas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {}, hoy=hoy, page=page,
page_size=page_size, contexto=(cohorte, escenario, revision))
total = len(elegidas)
paginas = -(-total // page_size)
if total and page > paginas:
raise PaginaFuera(f"page {page} pasa de la última ({paginas}).")
cabecera["paginacion"] = {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas}
cabecera["items"] = [_item(f) for f in elegidas[(page - 1) * page_size: page * page_size]]
return cabecera
def paciente_de(sesion: Session, pac_id: str, *, corte=None, meses=None, filtros=None,
cohorte=None, escenario=None, revision=None, page=1, page_size=50) -> dict:
"""dev's individual route, after the same full-selection suppression and revision checks."""
cabecera, filas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {},
contexto=(cohorte, escenario, revision), hoy=None, page=page, page_size=page_size)
fila = next((f for f in filas if str(f.pac_id) == pac_id), None)
if fila is None:
raise PaginaFuera('Paciente no encontrado en la selección')
return {**cabecera, 'item': _item(fila)}
def exportacion_de(sesion: Session, *, corte: date | None = None, meses: int | None = None, filtros: dict | None = None,
cohorte: str | None = None, escenario: str | None = None, revision: str | None = None,
hoy: date | None = None) -> dict:
"""Every row of the selection, with the same header, selection rules and context as the list.
Raises:
ExportacionGrande: more than `EXPORTACION_MAXIMA` patients.
"""
cabecera, elegidas = _consulta(sesion, corte=corte, meses=meses, filtros=filtros or {}, hoy=hoy, page=1,
page_size=1, contexto=(cohorte, escenario, revision))
if len(elegidas) > EXPORTACION_MAXIMA:
raise ExportacionGrande(f"la exportación admite hasta {EXPORTACION_MAXIMA} pacientes; la selección tiene {len(elegidas)}.")
cabecera["total_items"] = len(elegidas)
cabecera["items"] = [_item(f) for f in elegidas]
return cabecera
+113
View File
@@ -0,0 +1,113 @@
"""The routes of CaMa's follow-up list: `GET /cama/seguimiento` and `GET /cama/seguimiento/exportacion`."""
import json
import re
from collections.abc import Callable
from datetime import date
from flask import Blueprint, Response, current_app, jsonify, request
from sqlmodel import Session
from webapi.cama_follow_up.cohort import CohorteNoDisponible
from webapi.cama_follow_up.access import configured_access
from webapi.cama_follow_up.listing import (
ExportacionGrande, GrupoPequeno, PaginaFuera, PedidoInvalido, RevisionDistinta, exportacion_de, seguimiento_de, paciente_de,
)
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
FILTROS = ("birads", "grupo_edad", "biopsia")
CONTEXTO = ("cohorte", "escenario", "revision")
ENTEROS = ("meses", "page", "page_size")
def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
"""The blueprint of the list and its file, to register with `url_prefix="/cama"`."""
blueprint = Blueprint("cama_seguimiento", __name__)
blueprint.before_request(configured_access)
@blueprint.after_request
def no_store(response):
response.headers["Cache-Control"] = "no-store"
return response
def answer(build, admitidos: tuple[str, ...], legacy_mode=None, patient=None):
reader = current_app.config.get('CAMA_COHORT_READER')
if legacy_mode and 'CAMA_COHORT_READER' in current_app.config and not getattr(reader, '_cama_default_reader', False):
from webapi.cama_analysis_legacy import SelectionError, selection_response
try:
return selection_response(request.args, legacy_mode, patient)
except SelectionError as error:
return jsonify(error=error.message), error.status
try:
pedido = _requested(request.args, admitidos)
except ValueError as error:
return jsonify({"error": str(error)}), 400
sesion = get_session()
try:
cuerpo = build(sesion, **pedido)
except PedidoInvalido as error:
return jsonify({"error": str(error)}), 400
except GrupoPequeno as error:
return jsonify({"error": str(error), "motivo": "supresion"}), 403
except PaginaFuera as error:
return jsonify({"error": str(error)}), 404
except RevisionDistinta as error:
return jsonify({"error": str(error), "motivo": "revision"}), 409
except ExportacionGrande as error:
return jsonify({"error": str(error)}), 413
except CohorteNoDisponible as error:
return jsonify({"error": str(error), "motivo": "cohorte"}), 503
finally:
sesion.close()
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
@blueprint.get("/seguimiento")
def get_seguimiento():
"""The BI-RADS cohort's follow-up list at a cut-off, one page."""
return answer(seguimiento_de, ("corte", *ENTEROS, *CONTEXTO, *FILTROS), 'list')
@blueprint.get("/seguimiento/exportacion")
def get_exportacion():
"""Every row of the same selection, for a file."""
return answer(exportacion_de, ("corte", "meses", *CONTEXTO, *FILTROS), 'export')
@blueprint.get('/pacientes/<pac_id>')
def paciente(pac_id):
return answer(lambda session, **pedido: paciente_de(session, pac_id, **pedido),
('corte', *ENTEROS, *CONTEXTO, *FILTROS), 'patient', pac_id)
return blueprint
def _requested(args, admitidos: tuple[str, ...]) -> dict:
"""The query's parameters, typed. `ValueError` for an unknown, repeated or badly written one."""
for nombre in args:
if nombre not in admitidos:
raise ValueError(f"parámetro desconocido {nombre!r}; se admite {list(admitidos)}.")
if len(args.getlist(nombre)) > 1:
raise ValueError(f"parámetro repetido {nombre!r}.")
pedido: dict = {}
if (corte := args.get("corte")) is not None:
if not FECHA.fullmatch(corte):
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
try:
pedido["corte"] = date.fromisoformat(corte)
except ValueError:
raise ValueError(f"corte {corte!r} no es una fecha") from None
for nombre in ENTEROS:
if nombre in args:
if not re.fullmatch(r"\d{1,6}", args[nombre]):
raise ValueError(f"{nombre} debe ser un entero; llegó {args[nombre]!r}")
pedido[nombre] = int(args[nombre])
contexto = {n: args[n] for n in CONTEXTO if n in args}
if contexto and len(contexto) != len(CONTEXTO):
raise ValueError(f"el contexto de la cohorte lleva {list(CONTEXTO)} juntos.")
if any(not v for v in contexto.values()):
raise ValueError("el contexto de la cohorte no puede ir vacío.")
pedido.update(contexto)
filtros = {n: args[n] for n in FILTROS if n in args}
if any(not v for v in filtros.values()):
raise ValueError("un filtro no puede ir vacío.")
if filtros:
pedido["filtros"] = filtros
return pedido