Compare commits

..

3 Commits

Author SHA1 Message Date
Roberto Treviño Cervantes f9d3b8f67e reorganization 2026-10-31 12:48:09 -06:00
Roberto Treviño Cervantes 6e8ed1003d drop cohort builder plumbing; use kit cohorte_armado builds for MLflow lineage 2026-10-30 11:19:21 -06:00
Roberto Treviño Cervantes cbb3b9c7b6 integration layer; merge work on indicators from forks with existing ingestion pipeline 2026-10-23 00:00:13 -06:00
23 changed files with 1467 additions and 544 deletions
+6
View File
@@ -6,3 +6,9 @@ __pycache__/
*.egg-info/
.env
uv.lock
# MLflow's own default local stores, used only when MLFLOW_TRACKING_URI
# isn't set (dev/tests point it elsewhere, e.g. a tmp_path file store).
mlflow.db
mlruns/
mlartifacts/
+20 -56
View File
@@ -1,62 +1,26 @@
# models
Python package with the standard `train()`/`predict()` interface for the
three screening models — CaCu, CaMa and TEA. Consumed by `WebApi`, but
independent of it: this package can read its own training/inference data
directly from `Persistance`, without going through `WebApi` at all.
Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de
versiones en MLflow con requisitos de promoción, registro de predicciones y
los trabajos de OCR de reportes. Las cohortes con que se entrena son los
armados del kit de indicadores (`cohorte_armado`, en la base de cada
dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa
WebApi.
## Structure
| Módulo | Qué hace |
|---|---|
| `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. |
| `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. |
| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). |
| `registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. |
| `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. |
- `models/base.py` — `ScreeningModel`, the abstract base every model
implements (`train(data)` / `predict(data)`).
- `models/cacu.py`, `models/cama.py`, `models/tea.py` — one concrete
class per domain.
MLflow se configura con sus propias variables (`MLFLOW_TRACKING_URI`).
`MLFLOW_ARTIFACT_ROOT`, si existe, es la carpeta donde los experimentos nuevos
guardan sus artefactos.
## How entities are accessed from models
This package depends on `../Persistance` (a local `uv` path dependency —
see `pyproject.toml`), and through it on `../Core`. **As of now this is
wiring, not usage**: `train()`/`predict()` in `cacu.py`/`cama.py`/`tea.py`
just raise `NotImplementedError` — no model imports `persistance` yet.
When real training/inference logic is added, the access pattern is the
same repository instances `WebApi` reads from — no separate data layer
for `models` to maintain:
```python
# models/models/cacu.py
from typing import Any
from persistance.cacu import citologia_cervical_repository
from models.base import ScreeningModel
class CaCuModel(ScreeningModel):
def train(self, data: Any = None) -> None:
if data is None:
data = citologia_cervical_repository.list(limit=10_000)
# ... fit on `data`
def predict(self, data: Any) -> Any:
raise NotImplementedError("CaCu prediction is not implemented yet.")
```bash
uv run pytest -q
```
The `data: Any = None` default on `train()`/`predict()` is what lets a
caller (e.g. `WebApi`) optionally hand over already-fetched rows instead
of forcing every call to hit the database — but a model implementation is
just as free to call `persistance.<domain>` itself when `data` is `None`,
exactly like the example above.
Each domain's available repositories (`paciente_repository`,
`citologia_cervical_repository`, etc.) and how to extend one with
table-specific business logic are documented in
`../Persistance/README.md`.
## Riesgos (ADR-MD-008)
`models/riesgo.py` es el contrato con que Orquestacion pide riesgos a un modelo: `EstimadorDeRiesgo`
(recibe el marco ancho de un armado de cohorte y devuelve un `Riesgo` por miembro y horizonte, más su
`Procedencia`, las llaves para conciliar con MLflow). `RiesgoSintetico` es un sustituto determinista, sin
MLflow, para pruebas y para desplegar sin el modelo real; no es un modelo clínico. El modelo real
(Modelo-cacu, con su artefacto de MLflow) entra como otra clase que cumple el contrato (MD-Q6).
+27 -7
View File
@@ -1,17 +1,37 @@
import importlib
from abc import ABC, abstractmethod
from typing import Any
from typing import Any, ClassVar, Iterator
from persistance.repository import Repository
def resolve_repository(domain: str, entity: str) -> Repository:
"""`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
module = importlib.import_module(f"persistance.{domain}")
try:
return getattr(module, f"{entity}_repository")
except AttributeError as exc:
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
class ScreeningModel(ABC):
"""Standard train()/predict() interface every screening model implements,
regardless of which of the three data marts (CaCu/CaMa/TEA) it targets.
"""Common train()/predict() interface for the CaCu, CaMa and TEA models.
Implementations are free to pull their own data straight from
`persistance.<domain>` — the same standard repository API WebApi uses —
or accept already-fetched rows from a caller; `data` is intentionally
untyped at this scaffolding stage.
Data is read through the same `persistance.<domain>.<entity>_repository`
objects WebApi writes with, so anything loaded through the import flow
is visible here. `train` may also be given rows fetched by the caller.
"""
domain: ClassVar[str]
def repository(self, entity: str) -> Repository:
return resolve_repository(self.domain, entity)
def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]:
"""Every row of `entity` as plain dicts, read in batches."""
return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters))
@abstractmethod
def train(self, data: Any = None) -> None:
"""Fit the model, optionally on `data` passed in by the caller."""
+3 -1
View File
@@ -9,9 +9,11 @@ class CaCuModel(ScreeningModel):
Can pull its own training data straight from `persistance.cacu`'s
repositories (`paciente_repository`, `citologia_cervical_repository`,
`biopsia_cervical_repository`, ...) or be handed already-fetched rows.
No real model yet — this is interface scaffolding only.
No real model yet; this is interface scaffolding only.
"""
domain = "cacu"
def train(self, data: Any = None) -> None:
raise NotImplementedError("CaCu training is not implemented yet.")
+3 -1
View File
@@ -9,9 +9,11 @@ class CaMaModel(ScreeningModel):
Can pull its own training data straight from `persistance.cama`'s
repositories (`paciente_repository`, `mastografia_repository`,
`biopsia_mama_repository`, ...) or be handed already-fetched rows.
No real model yet — this is interface scaffolding only.
No real model yet; this is interface scaffolding only.
"""
domain = "cama"
def train(self, data: Any = None) -> None:
raise NotImplementedError("CaMa training is not implemented yet.")
+34
View File
@@ -0,0 +1,34 @@
"""ONNX checkpoint inspection (ML-01b, MLD-03).
Writing/storing a checkpoint is `models.training.TrainingRun.log_artifact`,
which hands it to MLflow directly — nothing here manages storage paths.
`onnx` is an optional dependency (`models[export]`); without it
`inspect_onnx_metadata` returns `{"available": False}`.
"""
from pathlib import Path
from typing import Any
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
`{"available": False}` when the optional `onnx` package isn't installed;
`ValueError` when it is and the file isn't a valid ONNX model."""
try:
import onnx
except ImportError:
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
try:
model = onnx.load(str(path))
onnx.checker.check_model(model)
except Exception as exc:
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
return {
"available": True,
"ir_version": model.ir_version,
"producer_name": model.producer_name,
"producer_version": model.producer_version,
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
"graph_inputs": [i.name for i in model.graph.input],
"graph_outputs": [o.name for o in model.graph.output],
}
+267
View File
@@ -0,0 +1,267 @@
"""Extraction of results from the PDF reports stored with each study
(VAR-01..09, VARM-01..05).
Each `OcrJob` says which table, which stored PDF and which result columns
an extraction fills; `OCR_JOBS` lists them all. Adding a job is adding an
`OcrExtractor` (usually a `ReportOcrExtractor` with its `fields`) and an
entry in `OCR_JOBS`.
Extraction method (VAR-04, VARM-05): the PDF's text layer is read with
pdfplumber; pages without one are recognized with Tesseract 5's LSTM engine
(Smith, R. "An Overview of the Tesseract OCR Engine", ICDAR 2007). Values
are then located by caption matching tolerant to OCR errors, and by
lexicon matching over the narrative with NegEx-style negation handling
(Chapman, W. et al. "A Simple Algorithm for Identifying Negated Findings and
Diseases in Discharge Summaries", J Biomed Inform 34(5), 2001). Every
value carries a 0..1 confidence: caption match quality x parse quality x
Tesseract's word confidence.
"""
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, ClassVar
from sqlalchemy import func, or_
from sqlmodel import select
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN, ResultadoVPH
from core.cama.enums import GradoHistologicoMama
from core.ocr import OcrEstatus
from extraction import FieldKind, FieldSpec, read_document
from extraction.nlp import RecordExtractor, SegmentLine
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
from extraction.ocr import TesseractOcr
from models.base import resolve_repository
from persistance.repository import Repository
# Below this confidence a value is stored but flagged for manual review.
REVIEW_THRESHOLD = 0.8
@dataclass
class OcrExtractionResult:
"""VAR-03/VARM-04a: the values plus their confidence and provenance."""
values: dict[str, Any]
confianza: float
estatus: OcrEstatus
requiere_revision: bool
metodo_principal: str
metodo_alternativo: str | None = None
quality_validation: str | None = None
@dataclass
class OcrColumnSpec:
"""The columns of one extraction on its table: the stored PDF, the
five traceability columns, and extractor result key -> result column."""
blob_field: str
confianza_field: str
estatus_field: str
requiere_revision_field: str
metodo_principal_field: str
metodo_alternativo_field: str
result_field_map: dict[str, str] = field(default_factory=dict)
class OcrExtractor(ABC):
@abstractmethod
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
"""Reads `pdf_blob`. A document that can be read but where nothing
is found returns estatus FALLIDO with requiere_revision; an
unreadable one may raise, and the driver records FALLIDO."""
class ReportOcrExtractor(OcrExtractor):
"""Reads a report and looks for `fields` (result key -> FieldSpec)."""
fields: ClassVar[dict[str, FieldSpec]]
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
document = read_document("reporte.pdf", pdf_blob)
lines = [SegmentLine(document.name, page.number, line) for page in document.pages for line in page.lines]
found = RecordExtractor(list(self.fields.values())).extract(lines)
by_key = {key: found[spec.name] for key, spec in self.fields.items() if spec.name in found}
sources = {page.source for page in document.pages}
principal = "pdf-texto" if "text" in sources else TesseractOcr().name
alternativo = TesseractOcr().name if sources == {"text", "ocr"} else None
evidence = {key: value.to_dict() for key, value in by_key.items()}
missing = [key for key in self.fields if key not in by_key]
if missing:
evidence["faltantes"] = missing
if not by_key:
return OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, principal, alternativo, json.dumps(evidence, ensure_ascii=False))
confianza = round(min(value.confidence for value in by_key.values()) * len(by_key) / len(self.fields), 3)
return OcrExtractionResult(
values={key: value.value for key, value in by_key.items()},
confianza=confianza,
estatus=OcrEstatus.REALIZADO,
requiere_revision=bool(missing) or confianza < REVIEW_THRESHOLD,
metodo_principal=principal,
metodo_alternativo=alternativo,
quality_validation=json.dumps(evidence, ensure_ascii=False, default=str),
)
def choice_field(column: str, values: dict[str, Any], **options) -> FieldSpec:
return FieldSpec(column, FieldKind.CHOICE, labels=labels_for(column), choices={**values, **CLINICAL_TERMS.get(column, {})}, **options)
class VphOcrExtractor(ReportOcrExtractor):
"""VAR-01: VPH result and genotypes 16/18 from `cit_vph_pdf_blob`."""
fields = {
"resultado": choice_field("cit_vph_resultado", {m.value: m.value for m in ResultadoVPH}, scan_free_text=True),
"genotipo_16": choice_field("cit_vph_genotipo_16", {}),
"genotipo_18": choice_field("cit_vph_genotipo_18", {}),
}
class CinGradoOcrExtractor(ReportOcrExtractor):
"""VAR-02: CIN grade from the cervical biopsy report `bx_pdf_blob`."""
fields = {"grado": choice_field("bx_cin_grado", {**{m.value: m.value for m in GradoCIN}, **GRADO_CIN_ALIAS}, scan_free_text=True)}
class GradoHistologicoOcrExtractor(ReportOcrExtractor):
"""VARM-03: histological grade from the breast biopsy report `bx_pdf_blob`."""
fields = {
"grado": choice_field(
"bx_grado_histologico",
{m.value.replace("_", " "): m.value for m in GradoHistologicoMama},
scan_free_text=True,
)
}
def _ocr_columns(prefix: str, blob_field: str, results: dict[str, str]) -> OcrColumnSpec:
return OcrColumnSpec(
blob_field=blob_field,
confianza_field=f"{prefix}_ocr_confianza",
estatus_field=f"{prefix}_ocr_estatus",
requiere_revision_field=f"{prefix}_ocr_requiere_revision",
metodo_principal_field=f"{prefix}_ocr_metodo_principal",
metodo_alternativo_field=f"{prefix}_ocr_metodo_alternativo",
result_field_map=results,
)
CIT_VPH_COLUMNS = _ocr_columns(
"cit_vph",
"cit_vph_pdf_blob",
{"resultado": "cit_vph_resultado", "genotipo_16": "cit_vph_genotipo_16", "genotipo_18": "cit_vph_genotipo_18"},
)
BX_CIN_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_cin_grado"})
BX_GRADO_HISTOLOGICO_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_grado_histologico"})
@dataclass(frozen=True)
class OcrJob:
domain: str
entity: str # repository name in persistance.<domain>, without `_repository`
label: str
columns: OcrColumnSpec
extractor: type[OcrExtractor]
@property
def repository(self) -> Repository:
"""Resolved on use, so it follows whatever database URL is active."""
return resolve_repository(self.domain, self.entity)
OCR_JOBS: dict[tuple[str, str], OcrJob] = {
(job.domain, job.entity): job
for job in (
OcrJob("cacu", "citologia_cervical", "CaCu · Resultado de VPH (citología cervical)", CIT_VPH_COLUMNS, VphOcrExtractor),
OcrJob("cacu", "biopsia_cervical", "CaCu · Grado CIN (biopsia cervical)", BX_CIN_COLUMNS, CinGradoOcrExtractor),
OcrJob("cama", "biopsia_mama", "CaMa · Grado histológico (biopsia de mama)", BX_GRADO_HISTOLOGICO_COLUMNS, GradoHistologicoOcrExtractor),
)
}
@dataclass
class OcrRunSummary:
processed: int = 0
skipped_already_done: int = 0
failed: int = 0
needs_review: int = 0
def run_pending_extractions(
repository: Repository,
spec: OcrColumnSpec,
extractor: OcrExtractor,
*,
domain: str,
entity: str,
governance_repository: Repository | None = None,
source_description: str | None = None,
limit: int = 500,
) -> OcrRunSummary:
"""VAR-09: rows whose status is already REALIZADO are skipped, so the
persisted result is what prevents duplicate runs. A failing row is
stored as FALLIDO and the batch continues. With `governance_repository`,
every processed row is logged as an `ExtractionRun` (VAR-07/08)."""
from core.governance.enums import EstatusExtraccion
from core.governance.models import ExtractionRun
summary = OcrRunSummary()
model = repository.model
primary_key = list(model.__table__.primary_key.columns)
estatus = getattr(model, spec.estatus_field)
with_report = getattr(model, spec.blob_field).is_not(None)
done = estatus == OcrEstatus.REALIZADO.value
with repository.open_session() as session:
summary.skipped_already_done = session.exec(select(func.count()).select_from(model).where(with_report, done)).one()
pending = select(model).where(with_report, or_(estatus.is_(None), ~done)).order_by(*primary_key).limit(limit)
for tracked in session.exec(pending).all():
pk_value = getattr(tracked, primary_key[0].name)
started_at = datetime.now(timezone.utc)
try:
result = extractor.extract(getattr(tracked, spec.blob_field))
except NotImplementedError:
raise
except Exception as exc: # noqa: BLE001 -- one unreadable report must not stop the batch
result = OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, type(extractor).__name__, None, f"error: {exc}")
for result_key, column in spec.result_field_map.items():
if result_key in result.values:
setattr(tracked, column, result.values[result_key])
setattr(tracked, spec.confianza_field, result.confianza)
setattr(tracked, spec.estatus_field, OcrEstatus(result.estatus).value)
setattr(tracked, spec.requiere_revision_field, result.requiere_revision)
setattr(tracked, spec.metodo_principal_field, result.metodo_principal)
setattr(tracked, spec.metodo_alternativo_field, result.metodo_alternativo)
session.add(tracked)
if result.estatus == OcrEstatus.FALLIDO:
summary.failed += 1
else:
summary.processed += 1
if result.requiere_revision:
summary.needs_review += 1
if governance_repository is not None:
governance_repository.create(
ExtractionRun(
domain=domain,
entity=entity,
entity_pk=str(pk_value),
column_extracted=",".join(spec.result_field_map.values()),
source_description=source_description,
source_started_at=started_at,
source_ended_at=datetime.now(timezone.utc),
transform_description=f"{type(extractor).__name__}: {result.metodo_principal}"
+ (f" + {result.metodo_alternativo}" if result.metodo_alternativo else ""),
quality_validation=result.quality_validation,
estatus=(
EstatusExtraccion.COMPLETADA if result.estatus == OcrEstatus.REALIZADO else EstatusExtraccion.FALLIDA
).value,
)
)
session.commit()
return summary
+127
View File
@@ -0,0 +1,127 @@
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
produced it. Callers go through `PredictionService` rather than calling
`model.predict(...)` directly.
"""
import hashlib
import json
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from core.governance.models import ModelPrediction
from mlflow import MlflowException
from persistance.governance import model_prediction_repository
from models.base import ScreeningModel
from models.registry import PRODUCTION_ALIAS, registered_name, registry
@dataclass
class Interpretability:
"""MLD-03: the minimum a prediction reports for clinical interpretation.
Each model fills the ones its method has (odds ratio for a logistic
regression, hazard ratio for a survival model)."""
odds_ratio: float | None = None
hazard_ratio: float | None = None
probabilidad_acumulada: float | None = None
def to_json(self) -> str:
return json.dumps(
{
"odds_ratio": self.odds_ratio,
"hazard_ratio": self.hazard_ratio,
"probabilidad_acumulada": self.probabilidad_acumulada,
}
)
class ApplicabilityRejected(Exception):
"""Raised when the EL-04b applicability gate rejects a row. Callers
should report it as a client error (4xx), not a server error."""
class PredictionService:
"""Runs a `ScreeningModel` and records its predictions against the
MLflow version holding the `produccion` alias for `(domain, scenario)`.
If `aplicable` is given, each row (a dict of fields) is checked with it
(EL-04b). Inapplicable rows are still scored but stored with
`applicability_passed=False`, unless `reject_inapplicable` is set.
"""
def __init__(
self,
model: ScreeningModel,
*,
domain: str,
scenario: str,
aplicable: Callable[[dict], bool] | None = None,
reject_inapplicable: bool = False,
):
self.model = model
self.domain = domain
self.scenario = scenario
self.aplicable = aplicable
self.reject_inapplicable = reject_inapplicable
def active_model_version(self):
"""The MLflow model version currently holding the `produccion`
alias for this (domain, scenario), or `None`."""
name = registered_name(self.domain, self.scenario)
try:
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
return None
def predict_and_record(
self,
data: Any,
*,
pac_id_hospital: str,
episodio_id: int | None = None,
interpretability: Interpretability | None = None,
) -> ModelPrediction:
"""Scores `data` and stores the result (MLD-5) tagged with the active
MLflow model version (MLD-4). `NotImplementedError` from the model is
propagated unchanged.
"""
applicability_passed = True
if self.aplicable is not None:
if not isinstance(data, dict):
raise TypeError("the applicability check needs the input as a dict of fields")
applicability_passed = self.aplicable(data)
if not applicability_passed and self.reject_inapplicable:
raise ApplicabilityRejected(
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
)
# Predict first, so an unimplemented model raises NotImplementedError
# even when no version is in production.
output = self.model.predict(data)
model_version = self.active_model_version()
if model_version is None:
raise RuntimeError(
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
"promueva una con models.registry.registry.promote antes de predecir"
)
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
prediction = model_prediction_repository.create(
ModelPrediction(
mlflow_run_id=model_version.run_id,
modelo_nombre=model_version.name,
modelo_version=str(model_version.version),
domain=self.domain,
pac_id_hospital=pac_id_hospital,
episodio_id=episodio_id,
input_hash=input_hash,
output=json.dumps(output, default=str),
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
confianza=output.get("confianza") if isinstance(output, dict) else None,
interpretability=interpretability.to_json() if interpretability else None,
applicability_passed=applicability_passed,
)
)
return prediction
+249
View File
@@ -0,0 +1,249 @@
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
about on its own: the promotion checks tied to the cohort a version was
trained on and to the validation-report convention.
Training, versioning, artifact storage and stage live in MLflow itself
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
of its versions, never stored here and read from MLflow on every call.
Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
database). A version points to its build with the `kit.armado_id` tag, and
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
"""
import re
import tempfile
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from importlib import import_module
from pathlib import Path
from typing import Any
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient, MlflowException
from persistance.governance import model_prediction_repository
from sqlmodel import select
from models.export import inspect_onnx_metadata
DOMAINS = ("cacu", "cama", "tea")
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
PRODUCTION_ALIAS = "produccion"
ARMADO_TAG = "kit.armado_id"
@dataclass(frozen=True)
class PromotionCheck:
code: str
requirement: str
passed: bool
detail: str = ""
class PromotionBlocked(Exception):
def __init__(self, checks: list[PromotionCheck]):
self.checks = checks
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
super().__init__(f"la versión no cumple: {failed}")
def registered_name(domain: str, scenario: str) -> str:
return f"{domain}-{scenario}"
class ModelRegistry:
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
def __init__(self, client: MlflowClient | None = None):
self._client = client
@property
def client(self) -> MlflowClient:
return self._client or MlflowClient()
def get(self, domain: str, scenario: str, version: str):
try:
return self.client.get_model_version(registered_name(domain, scenario), version)
except MlflowException as exc:
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
"""Every version, newest first. `scenario` needs `domain`; `domain`
alone matches every scenario of that domain (MLflow's own
`search_registered_models` LIKE filter); neither matches everything."""
if domain and domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
if scenario and not re.fullmatch(r"[\w-]+", scenario):
raise ValueError(f"escenario inválido: {scenario!r}")
if domain and scenario:
names = [registered_name(domain, scenario)]
elif domain:
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
else:
return [self._describe(mv) for mv in self.client.search_model_versions()]
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
def _status(self, mv) -> str:
try:
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
if str(production.version) == str(mv.version):
return "produccion"
except MlflowException:
pass
if mv.tags.get("retirada_en"):
return "retirada"
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
def status(self, domain: str, scenario: str, version: str) -> str:
return self._status(self.get(domain, scenario, version))
def register(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohorte_armado_id: int | None = None,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""For training code that runs elsewhere and reports over the API.
In-process training uses `models.training.TrainingRun` directly."""
from models.training import TrainingRun
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
"""MLD-01/01b/03 documents are usually written after training."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
name = registered_name(domain, scenario)
for tag, uri in reports.items():
self.client.set_model_version_tag(name, version, tag, uri or "")
def add_artifact(self, domain: str, scenario: str, version: str, *, kind, filename: str, data: bytes) -> None:
"""Logs an artifact file to the run behind an already-registered
version (ML-01a/b), e.g. a checkpoint exported after training.
An `ONNX_CHECKPOINT` is parsed first, so a corrupt export is
rejected (400) instead of silently stored."""
mv = self.get(domain, scenario, version)
kind_value = kind.value if hasattr(kind, "value") else str(kind)
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / filename
path.write_bytes(data)
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
def _describe(self, mv) -> dict[str, Any]:
run = self.client.get_run(mv.run_id)
return {
"name": mv.name,
"version": str(mv.version),
"run_id": mv.run_id,
"tags": dict(mv.tags),
"metrics": dict(run.data.metrics),
"created_at": _iso(mv.creation_timestamp),
"status": self._status(mv),
}
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
return self._describe(self.get(domain, scenario, version))
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
"""Everything a version came from and produced: its cohort build (with
its attrition), logged artifacts and predictions."""
mv = self.get(domain, scenario, version)
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
return {
"model_version": self.describe(domain, scenario, version),
"cohorte_armado": armado,
"cohorte_exclusiones": exclusiones,
"artifacts": [a.path for a in self.client.list_artifacts(mv.run_id)],
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
}
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
mv = self.get(domain, scenario, version)
run = self.client.get_run(mv.run_id)
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
metrics = run.data.metrics
artifacts = self.client.list_artifacts(mv.run_id)
return [
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
PromotionCheck(
"ML-03",
"enlazada al armado de cohorte con el que se entrenó",
armado is not None,
f"huella {armado['huella'][:12]}" if armado else "sin cohorte",
),
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
PromotionCheck("ML-01b", "artefactos registrados en la corrida", bool(artifacts), f"{len(artifacts)} artefacto(s)"),
]
def promote(self, domain: str, scenario: str, version: str):
"""Makes this the production version of its scenario, tagging the
previous one `retirada_en`. Promotion is always a manual step
(MLD-01/01b)."""
checks = self.checks(domain, scenario, version)
if not all(check.passed for check in checks):
raise PromotionBlocked(checks)
name = registered_name(domain, scenario)
try:
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
if str(previous.version) != str(version):
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
except MlflowException:
pass
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
return self.get(domain, scenario, version)
def retire(self, domain: str, scenario: str, version: str):
"""Withdraws a version from production; its scenario has no active
model until another one is promoted, so predictions stop."""
name = registered_name(domain, scenario)
try:
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
active = None
if active is None or str(active.version) != str(version):
raise ValueError("la versión no está en producción")
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
return self.get(domain, scenario, version)
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _iso(epoch_millis: int) -> str:
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
registry = ModelRegistry()
def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]:
"""The kit cohort build a version was trained on, and its attrition steps."""
if not armado_id:
return None, []
cohortes = import_module(f"persistance.{domain}").cohorte_repository
armado = cohortes.get(int(armado_id))
if armado is None:
return None, []
exclusion = cohortes.cohortes.CohorteExclusion
pasos = cohortes.leer(lambda sesion: sesion.exec(
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
"armado_en": armado.armado_en.isoformat()},
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
-176
View File
@@ -1,176 +0,0 @@
"""El contrato con que se le pide a un modelo el riesgo de los miembros de una cohorte (ADR-MD-008).
Quien llama (la arista `estimar` de Orquestacion) le da al estimador el marco de un armado
de cohorte, ancho: `(columnas, filas)`, con `columnas = ["pac_id", "fecha_indice", <variables>]`
(lo que devuelve `indicadores_kit.cohortes.armado.leer_marco`). El estimador devuelve un
`Riesgo` por miembro y horizonte, y su `Procedencia`: las llaves con que se concilia con
MLflow (opción A del prototipo; MLflow no guarda filas ni pacientes).
Este módulo no importa al kit, a Persistance ni a Orquestacion: recibe listas.
"""
import hashlib
import json
from dataclasses import asdict, dataclass
from typing import NamedTuple, Protocol, runtime_checkable
class Riesgo(NamedTuple):
"""El riesgo de un miembro a un horizonte (FHIR `RiskAssessment.prediction`)."""
pac_id: int
horizonte_anios: float # años desde la fecha índice; 0 = prevalente
probabilidad: float # de 0 a 1
ic_bajo: float | None = None
ic_alto: float | None = None
@dataclass(frozen=True)
class Procedencia:
"""De qué modelo salen los riesgos: las llaves que guarda el lote (`PROCEDENCIA` de Persistance)."""
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str
def como_dict(self) -> dict[str, str]:
return asdict(self)
@runtime_checkable
class EstimadorDeRiesgo(Protocol):
"""Lo que cumple todo modelo de riesgo que Orquestacion puede llamar."""
cohorte_url: str # la cohorte cuyo marco consume ("cacu/cohorte_vigilancia")
desenlace: str # lo que predice ("cin2_mas")
def procedencia(self) -> Procedencia: ...
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]: ...
# La regla del sustituto: una probabilidad base y lo que suma cada predictor basal.
REGLA_SINTETICA = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
PAP_NORMALES = ("NORMAL",)
class RiesgoSintetico:
"""Un estimador sustituto determinista, sin MLflow: para pruebas y para desplegar sin el modelo real.
La probabilidad sale de una tabla fija por los predictores basales: `REGLA_SINTETICA["base"]`,
más `pap_anormal` si `pap_0` no es `NORMAL` ni nulo, más `vph_positivo` si `hpv_0` es
`POSITIVO`, con tope. Sin intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "cacu/cohorte_vigilancia", desenlace: str = "cin2_mas",
horizontes: tuple[float, ...] = (0.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA, "pap_normales": PAP_NORMALES, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
faltan = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_pap, i_vph = (columnas.index(c) for c in ("pac_id", "pap_0", "hpv_0"))
riesgos = []
for fila in filas:
p = REGLA_SINTETICA["base"]
if fila[i_pap] is not None and fila[i_pap] not in PAP_NORMALES:
p += REGLA_SINTETICA["pap_anormal"]
if fila[i_vph] == "POSITIVO":
p += REGLA_SINTETICA["vph_positivo"]
p = min(p, REGLA_SINTETICA["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
# La regla del sustituto de TEA: lo que suma la interpretación del M-CHAT índice y lo perinatal.
REGLA_SINTETICA_TEA = {"base": 0.02, "mchat_medio": 0.10, "mchat_alto": 0.30, "ucin": 0.05, "apgar_bajo": 0.05,
"apgar_corte": 7, "tope": 0.95}
class RiesgoSinteticoTea:
"""El sustituto determinista de TEA, sobre el marco de `tea/cohorte_tamizaje` (T-21e). Sin MLflow.
La probabilidad de un diagnóstico de TEA al horizonte (4 años = 48 meses, el de la cohorte) es
`REGLA_SINTETICA_TEA["base"]`, más `mchat_medio` o `mchat_alto` según `mchat_0`, más `ucin` si
`ingreso_ucin` es 1, más `apgar_bajo` si `apgar_5min` es menor que `apgar_corte`, con tope. Sin
intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "tea/cohorte_tamizaje", desenlace: str = "d",
horizontes: tuple[float, ...] = (4.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA_TEA, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto_tea", modelo_version="1", mlflow_run_id="sin-mlflow",
modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
necesarias = ("pac_id", "mchat_0", "ingreso_ucin", "apgar_5min")
faltan = [c for c in necesarias if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_mchat, i_ucin, i_apgar = (columnas.index(c) for c in necesarias)
r = REGLA_SINTETICA_TEA
riesgos = []
for fila in filas:
p = r["base"] + {"RIESGO_MEDIO": r["mchat_medio"], "RIESGO_ALTO": r["mchat_alto"]}.get(fila[i_mchat], 0.0)
if fila[i_ucin] == 1:
p += r["ucin"]
if fila[i_apgar] is not None and fila[i_apgar] < r["apgar_corte"]:
p += r["apgar_bajo"]
p = min(p, r["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
# La regla del sustituto de CaMa: lo que suma el BI-RADS índice.
REGLA_SINTETICA_CAMA = {"base": 0.005, "birads_0": 0.03, "birads_3": 0.02, "birads_4": 0.30, "birads_5": 0.80,
"tope": 0.95}
BIRADS_SUSPECHA = {"B0": "birads_0", "B3": "birads_3", "B4": "birads_4", "B4A": "birads_4", "B4B": "birads_4",
"B4C": "birads_4", "B5": "birads_5"}
class RiesgoSinteticoCama:
"""El sustituto determinista de CaMa, sobre el marco de `cama/cohorte_tamizaje` (T-21g). Sin MLflow.
La probabilidad de cáncer de mama por biopsia al horizonte (1 año, el de la cohorte) es
`REGLA_SINTETICA_CAMA["base"]` más lo que suma la categoría del BI-RADS índice (`birads_0`), con
tope. Las subcategorías 4A, 4B y 4C suman como 4. Sin intervalo. No es un modelo clínico.
"""
def __init__(self, cohorte_url: str = "cama/cohorte_tamizaje", desenlace: str = "d",
horizontes: tuple[float, ...] = (1.0,)):
self.cohorte_url = cohorte_url
self.desenlace = desenlace
self.horizontes = tuple(horizontes)
def procedencia(self) -> Procedencia:
regla = {"regla": REGLA_SINTETICA_CAMA, "birads": BIRADS_SUSPECHA, "horizontes": self.horizontes}
sha = hashlib.sha256(json.dumps(regla, sort_keys=True).encode("utf-8")).hexdigest()
return Procedencia(modelo_nombre="sustituto_cama", modelo_version="1", mlflow_run_id="sin-mlflow",
modelo_sha=sha)
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[Riesgo]:
faltan = [c for c in ("pac_id", "birads_0") if c not in columnas]
if faltan:
raise ValueError(f"El marco no trae las columnas {faltan}: el sustituto las necesita.")
i_pac, i_birads = columnas.index("pac_id"), columnas.index("birads_0")
r = REGLA_SINTETICA_CAMA
riesgos = []
for fila in filas:
p = min(r["base"] + r.get(BIRADS_SUSPECHA.get(fila[i_birads]), 0.0), r["tope"])
riesgos += [Riesgo(int(fila[i_pac]), float(h), round(p, 6)) for h in self.horizontes]
return riesgos
-187
View File
@@ -1,187 +0,0 @@
"""Prueba de concepto: un modelo de riesgo de CIN2+ con MLflow, de `toy-model/riesgo_juguete.py`.
Entrena una logística sobre el marco de `cacu/cohorte_vigilancia`, la registra en MLflow
(`MLFLOW_TRACKING_URI`; en el despliegue, `http://<host>:9705`) y la sirve a la arista `estimar` con
`EstimadorMlflow`, que cumple `EstimadorDeRiesgo`. Lo corre Orquestacion:
uv run python -m orquestacion modelos entrenar [--horizonte 1] [--armado 3]
uv run python -m orquestacion ciclo cacu --desde 2025 --hasta 2025 --solo estimar --modelo cacu_cin2_mas --version 1
Sin pacientes en MLflow (ADR-MD-008): ni filas ni `input_example`. `ModeloCin2Mas` se serializa por
referencia a este módulo: cargarlo pide `models` instalado.
"""
import hashlib
import tempfile
from pathlib import Path
import mlflow
import numpy as np
import pandas as pd
from mlflow.models import ModelSignature
from mlflow.types import ColSpec, Schema
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from indicadores_kit.cacu.tablas import COHORTES
from indicadores_kit.oro.cohortes.armado import leer_marco, linaje, ultimo_armado
from indicadores_kit.oro.cohortes.definicion import leer_definicion, ruta_de_cohorte
from models.riesgo import Procedencia, Riesgo
EXPERIMENTO = "cacu-cin2"
NOMBRE_MODELO = "cacu_cin2_mas"
COHORTE_URL = "cacu/cohorte_vigilancia"
DESENLACE = "cin2_mas"
COVARIABLES = ["pap_0", "hpv_0"]
SIN_ESTADO = -999
HORIZONTE = 1.0
# 1 · descargar ---------------------------------------------------------------------------
def descargar(repositorio, armado_id=None):
"""El marco del armado (el último si no se dice) y su linaje `kit.*`, en una sesión de `repositorio`. Solo lee."""
d = leer_definicion(ruta_de_cohorte("cacu", "cohorte_vigilancia"))
def leer(sesion):
aid = armado_id if armado_id is not None else ultimo_armado(sesion, d.url, cohortes=COHORTES)
if aid is None:
raise LookupError(f"No hay armados de {d.url}: corre antes la arista `cohortes`.")
columnas, filas = leer_marco(sesion, aid, d, cohortes=COHORTES)
return pd.DataFrame(filas, columns=columnas), linaje(sesion, aid, d, cohortes=COHORTES)
return repositorio.leer(leer)
# 2 · preparar ----------------------------------------------------------------------------
def a_nulos(df):
"""`-999` es nulo, en números y en códigos."""
return df.replace({SIN_ESTADO: np.nan, float(SIN_ESTADO): np.nan, str(SIN_ESTADO): np.nan})
def preparar(marco, horizonte=HORIZONTE):
"""El marco con la etiqueta `y` a `horizonte` años, sin las filas no etiquetables.
Provisional (MD-Q6): y = 1 si `c == 1` o `r <= h`; y = 0 si `c == 0` y `l >= h`; lo demás se excluye.
"""
df = a_nulos(marco)
df["fecha_indice"] = pd.to_datetime(df["fecha_indice"])
positivo = (df["c"] == 1) | (df["r"] <= horizonte)
negativo = (df["c"] == 0) & (df["l"] >= horizonte) & ~positivo
df["y"] = np.where(positivo, 1, np.where(negativo, 0, -1))
return df[df["y"] >= 0].sort_values(["fecha_indice", "pac_id"]).reset_index(drop=True)
# 3 · entrenar y evaluar ------------------------------------------------------------------
def dividir(df, fraccion=0.7):
"""Partición temporal: las fechas índice más antiguas entrenan. Nunca al azar."""
corte = df["fecha_indice"].iloc[int(len(df) * fraccion)]
return df[df["fecha_indice"] < corte], df[df["fecha_indice"] >= corte], corte
class ModeloCin2Mas(mlflow.pyfunc.PythonModel):
"""El pyfunc: indicadoras de las covariables y una logística. Recibe el marco, devuelve P(CIN2+) por fila.
Un nulo o un nivel que no se vio al ajustar da ceros en sus indicadoras.
"""
def __init__(self, horizonte=HORIZONTE, C=1.0):
self.horizonte, self.C = float(horizonte), C
self.niveles, self.logistica = {}, None
def indicadoras(self, df):
df = a_nulos(df)
return pd.DataFrame(
{f"{c}={n}": (df[c].astype("string") == n).fillna(False).astype(float).to_numpy()
for c in COVARIABLES for n in self.niveles[c]},
index=df.index,
)
def ajustar(self, df):
self.niveles = {c: sorted(a_nulos(df)[c].dropna().astype(str).unique()) for c in COVARIABLES}
self.logistica = LogisticRegression(C=self.C, max_iter=1000).fit(self.indicadoras(df), df["y"])
return self
def predict(self, context, model_input, params=None):
return self.logistica.predict_proba(self.indicadoras(model_input))[:, 1]
def evaluar(modelo, entrena, prueba):
p = modelo.predict(None, prueba)
return {
"brier": brier_score_loss(prueba["y"], p, labels=[0, 1]),
"auc": roc_auc_score(prueba["y"], p) if prueba["y"].nunique() == 2 else float("nan"),
"n_entrenamiento": len(entrena), "n_prueba": len(prueba),
"positivos_entrenamiento": int(entrena["y"].sum()), "positivos_prueba": int(prueba["y"].sum()),
}
# 4 · registrar ---------------------------------------------------------------------------
def sha_del_artefacto(model_uri):
"""sha256 de `python_model.pkl` (preprocesamiento + logística); el `MLmodel` lleva ids y fechas."""
with tempfile.TemporaryDirectory() as tmp:
ruta = Path(mlflow.artifacts.download_artifacts(model_uri, dst_path=tmp)) / "python_model.pkl"
return hashlib.sha256(ruta.read_bytes()).hexdigest()
def registrar(modelo, metricas, parametros, linaje):
"""Una corrida con el linaje, los parámetros, las métricas y el pyfunc registrado. Sin pacientes."""
firma = ModelSignature(inputs=Schema([ColSpec("string", c, required=False) for c in COVARIABLES]))
mlflow.set_experiment(EXPERIMENTO)
with mlflow.start_run() as corrida:
mlflow.set_tags({**linaje, "desenlace": DESENLACE})
mlflow.log_params(parametros)
mlflow.log_metrics(metricas)
info = mlflow.pyfunc.log_model(name="modelo", python_model=modelo, signature=firma,
registered_model_name=NOMBRE_MODELO)
mlflow.set_tag("modelo_sha", sha_del_artefacto(info.model_uri))
return corrida.info.run_id, str(info.registered_model_version)
def entrenar(repositorio, horizonte=HORIZONTE, armado_id=None):
"""Pasos 1-4. Devuelve (`run_id`, versión registrada, métricas)."""
marco, linaje = descargar(repositorio, armado_id)
df = preparar(marco, horizonte)
entrena, prueba, corte = dividir(df)
if entrena["y"].nunique() < 2:
raise ValueError(f"La partición de entrenamiento tiene una sola clase ({len(entrena)} etiquetados).")
modelo = ModeloCin2Mas(horizonte).ajustar(entrena)
metricas = evaluar(modelo, entrena, prueba)
# El corte es la fecha índice de una paciente: a MLflow va solo su mes.
parametros = {"horizonte_anios": horizonte, "C": modelo.C, "corte_temporal_mes": corte.strftime("%Y-%m"),
"covariables": ",".join(COVARIABLES), "etiqueta": "provisional MD-Q6"}
run_id, version = registrar(modelo, metricas, parametros, linaje)
return run_id, version, metricas
# 6b · el estimador de la arista `estimar` -------------------------------------------------
class EstimadorMlflow:
"""Cumple `EstimadorDeRiesgo` con una versión registrada de `NOMBRE_MODELO`."""
cohorte_url = COHORTE_URL
desenlace = DESENLACE
def __init__(self, version):
cliente = mlflow.MlflowClient()
mv = cliente.get_model_version(NOMBRE_MODELO, str(version))
uri = f"models:/{NOMBRE_MODELO}/{mv.version}"
sha = sha_del_artefacto(uri)
if sha != cliente.get_run(mv.run_id).data.tags.get("modelo_sha"):
raise ValueError(f"El artefacto de {uri} no es el que se registró.")
self.pyfunc = mlflow.pyfunc.load_model(uri)
self.horizonte = self.pyfunc.unwrap_python_model().horizonte
self._procedencia = Procedencia(NOMBRE_MODELO, str(mv.version), mv.run_id, sha)
def procedencia(self):
return self._procedencia
def estimar(self, columnas, filas):
marco = pd.DataFrame(filas, columns=columnas)
entrada = a_nulos(marco)[COVARIABLES].astype(object)
p = self.pyfunc.predict(entrada.where(entrada.notna(), None))
return [Riesgo(int(pac), self.horizonte, round(float(q), 6)) for pac, q in zip(marco["pac_id"], p)]
+3 -1
View File
@@ -8,10 +8,12 @@ class TeaModel(ScreeningModel):
Can pull its own training data straight from `persistance.tea`'s
repositories (`pacientes_repository`, `evaluacion_psicologica_repository`,
...) or be handed already-fetched rows. No real model yet — this is
...) or be handed already-fetched rows. No real model yet; this is
interface scaffolding only.
"""
domain = "tea"
def train(self, data: Any = None) -> None:
raise NotImplementedError("TEA training is not implemented yet.")
+143
View File
@@ -0,0 +1,143 @@
"""Bookkeeping around a training run (ML-01..ML-05).
Does not train anything. It opens an MLflow run, records which cohort
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped
methods instead of the fluent API's global active run, so two runs in one
process never interfere.
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
"""
import json
import os
from pathlib import Path
from typing import Any
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient, MlflowException
from persistance.repository import Repository
from models.base import resolve_repository
from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
class ReadOnlyRepository:
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
Write methods raise `PermissionError` so a training routine cannot
modify clinical data."""
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
def __init__(self, repository: Repository):
self._repository = repository
self.model = repository.model
def get(self, id_):
return self._repository.get(id_)
def list(self, *, limit: int = 100, offset: int = 0, **filters):
return self._repository.list(limit=limit, offset=offset, **filters)
def count(self, **filters) -> int:
return self._repository.count(**filters)
def __getattr__(self, name: str):
if name in self._WRITE_METHODS:
raise PermissionError(
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
)
raise AttributeError(name)
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs require `cohorte_armado_id`, the indicator kit cohort build they were
trained on, so their metrics trace back to that data (ML-03); dev runs may
omit it.
"""
def __init__(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohorte_armado_id: int | None = None,
):
if domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
environment = Environment(environment)
if environment is Environment.PROD and cohorte_armado_id is None:
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).")
self.domain = domain
self.scenario = scenario
self.environment = environment
self.cohorte_armado_id = cohorte_armado_id
self.client = MlflowClient()
experiment_id = self._experiment_id()
run = self.client.create_run(
experiment_id,
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
)
self.run_id = run.info.run_id
if cohorte_armado_id is not None:
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
def _experiment_id(self) -> str:
name = registered_name(self.domain, self.scenario)
experiment = self.client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
def repository(self, entity: str) -> ReadOnlyRepository:
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
return ReadOnlyRepository(resolve_repository(self.domain, entity))
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
named for its kind."""
kind = ArtifactKind(kind)
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
if metadata:
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
def finish(
self,
*,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""Logs metrics/params to the run, registers it as a new version of
`<domain>-<scenario>` tagged with `models.registry`'s promotion
inputs (environment, cohort link, report URIs), and returns the new
version string. Call once, after training (and artifact logging)
completes."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
for key, value in (metrics or {}).items():
self.client.log_metric(self.run_id, key, value)
for key, value in (hyperparameters or {}).items():
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
name = registered_name(self.domain, self.scenario)
try:
self.client.create_registered_model(name)
except MlflowException as exc:
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
raise
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
if self.cohorte_armado_id is not None:
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
version_tags.update({key: uri for key, uri in reports.items() if uri})
model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags)
self.client.set_terminated(self.run_id)
return str(model_version.version)
+13 -10
View File
@@ -5,18 +5,21 @@ description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening
requires-python = ">=3.11"
dependencies = [
"persistance",
# El marco y el linaje de las cohortes (`leer_marco`, `linaje`): `riesgo_logistico`.
"indicadores-kit",
# Solo el cliente: registra y carga contra el servidor del despliegue (9705), fijado a su versión.
"mlflow-skinny==3.16.1",
"scikit-learn==1.9.1",
"pandas==3.0.6",
"extraction",
"mlflow>=2.9",
]
[project.optional-dependencies]
# Only needed to read back a checkpoint's own metadata (opset, producer) in
# models.export.inspect_onnx_metadata — writing/logging a checkpoint never
# requires it, see that module's docstring.
export = [
"onnx>=1.15",
]
[tool.uv.sources]
core = { path = "../Core", editable = true }
persistance = { path = "../Persistance", editable = true }
indicadores-kit = { path = "../indicadores_kit", editable = true }
extraction = { path = "../Extraction", editable = true }
[build-system]
requires = ["hatchling"]
@@ -28,6 +31,6 @@ packages = ["models"]
[dependency-groups]
dev = [
"pytest>=8.0.0",
# Las pruebas registran en un sqlite temporal, que el cliente `skinny` no admite.
"mlflow==3.16.1",
"onnx>=1.15",
"reportlab>=4.0",
]
+93
View File
@@ -0,0 +1,93 @@
import pytest
def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str):
import importlib
from persistance import db as persistance_db
from persistance import settings as persistance_settings
monkeypatch.setattr(persistance_settings.settings, f"{domain}_database_url", f"sqlite:///{tmp_path / f'{domain}.db'}")
engine = getattr(persistance_db, f"get_{domain}_engine")
engine.cache_clear()
importlib.import_module(f"core.{domain}.models")
if domain != "governance":
importlib.import_module(f"core.{domain}.indicadores.models")
base = getattr(importlib.import_module(base_module), base_class)
base.metadata.create_all(engine())
return engine
@pytest.fixture
def governance_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "governance", "core.governance.base", "GovernanceModel")
yield
engine.cache_clear()
@pytest.fixture
def cacu_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "cacu", "core.cacu.base", "CaCuModel")
yield
engine.cache_clear()
@pytest.fixture
def mlflow_tracking(tmp_path, monkeypatch):
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
import mlflow
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
mlflow.set_tracking_uri(uri)
monkeypatch.chdir(tmp_path)
yield
@pytest.fixture
def production_ready(governance_db, cacu_db, mlflow_tracking):
"""Factory: registers a PROD version that passes every promotion check,
returns (domain, scenario, version)."""
from core.governance.enums import ArtifactKind, Environment
from models.registry import registry
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
version = registry.register(
domain=domain, scenario=scenario, environment=Environment.PROD,
cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8},
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
interpretability_report_uri="docs/interpretabilidad.html",
)
registry.add_artifact(domain, scenario, version, kind=ArtifactKind.ONNX_CHECKPOINT, filename="model.onnx", data=tiny_onnx())
return domain, scenario, version
return make
def tiny_onnx() -> bytes:
import onnx.helper
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
def armado(huella: str) -> int:
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
from datetime import date, datetime, timezone
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
from persistance.db import get_cacu_session
with get_cacu_session() as session:
fila = CohorteArmado(
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
datos_as_of=date(2025, 12, 31), huella=huella, marco_sha="m", n_miembros=8,
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
session.add(fila)
session.flush()
session.add_all([CohorteExclusion(armado_id=fila.armado_id, orden=1, paso="candidatas", n=10),
CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)])
session.commit()
return fila.armado_id
+27
View File
@@ -0,0 +1,27 @@
"""`models` reads through Persistance's Repository, the same path WebApi
uses, against a temporary SQLite database."""
import pytest
def test_dataset_pages_through_every_row(cacu_db):
from datetime import date
from core.cacu.models import Paciente
from models.cacu import CaCuModel
model = CaCuModel()
repository = model.repository("paciente")
for i in range(7):
repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
rows = list(model.dataset("paciente", batch_size=3))
assert [r["pac_id_hospital"] for r in rows] == [f"M-{i}" for i in range(7)]
assert list(model.dataset("paciente", pac_id_hospital="M-3"))[0]["pac_sexo"] == "Femenino"
def test_unknown_entity_is_a_clear_error():
from models.tea import TeaModel
with pytest.raises(ValueError, match="no nope_repository"):
TeaModel().repository("nope")
+60
View File
@@ -0,0 +1,60 @@
import onnx
import onnx.helper
import pytest
from models.export import inspect_onnx_metadata
def _tiny_onnx_bytes() -> bytes:
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "tiny", [x], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
return model.SerializeToString()
def test_inspect_onnx_metadata_reads_producer_and_io(tmp_path):
path = tmp_path / "model.onnx"
path.write_bytes(_tiny_onnx_bytes())
metadata = inspect_onnx_metadata(path)
assert metadata["available"] is True
assert metadata["producer_name"] == "pytest-fixture"
assert metadata["graph_inputs"] == ["x"]
assert metadata["graph_outputs"] == ["y"]
def test_inspect_onnx_metadata_rejects_structurally_invalid_model(tmp_path):
"""A protobuf-valid but structurally broken graph (a node reading an
input the graph never declares) must be rejected: `onnx.load` alone
only parses the protobuf and would let this through."""
node = onnx.helper.make_node("Identity", ["undeclared_input"], ["y"])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "broken", [], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
path = tmp_path / "model.onnx"
path.write_bytes(model.SerializeToString())
with pytest.raises(ValueError, match="no es un modelo ONNX válido"):
inspect_onnx_metadata(path)
def test_inspect_onnx_metadata_without_onnx_available(monkeypatch, tmp_path):
import builtins
real_import = builtins.__import__
def fake_import(name, *args, **kwargs):
if name == "onnx":
raise ImportError("onnx not installed")
return real_import(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", fake_import)
path = tmp_path / "model.onnx"
path.write_bytes(b"irrelevant")
assert inspect_onnx_metadata(path) == {
"available": False,
"reason": "el paquete 'onnx' no está instalado (extra 'export')",
}
+115
View File
@@ -0,0 +1,115 @@
from core.ocr import OcrEstatus
from models.ocr import (
CIT_VPH_COLUMNS,
OcrExtractionResult,
OcrExtractor,
run_pending_extractions,
)
class StubVphExtractor(OcrExtractor):
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
return OcrExtractionResult(
values={"resultado": "POSITIVO", "genotipo_16": 1, "genotipo_18": 0},
confianza=0.92,
estatus=OcrEstatus.REALIZADO,
requiere_revision=False,
metodo_principal="stub-v1",
)
class AlwaysFailsExtractor(OcrExtractor):
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
raise RuntimeError("boom")
def _make_cacu_citologia_repo():
from core.cacu.models import CitologiaCervical
from persistance.cacu import citologia_cervical_repository
return citologia_cervical_repository, CitologiaCervical
def test_run_pending_extractions_populates_result_and_metadata(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(
CitologiaCervical(
pac_id_hospital="H-1",
cit_vph_pdf_blob=b"%PDF-fake",
)
)
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
assert summary.processed == 1
assert summary.skipped_already_done == 0
row = repo.list()[0]
assert row.cit_vph_resultado == "POSITIVO"
assert row.cit_vph_genotipo_16 == 1
assert row.cit_vph_ocr_estatus == OcrEstatus.REALIZADO
assert row.cit_vph_ocr_requiere_revision is False
assert row.cit_vph_ocr_metodo_principal == "stub-v1"
def test_run_pending_extractions_is_idempotent(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
first = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
second = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
assert first.processed == 1
assert second.processed == 0
assert second.skipped_already_done == 1
def test_run_pending_extractions_persists_failure_instead_of_crashing(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, AlwaysFailsExtractor(), domain="cacu", entity="citologiacervical")
assert summary.failed == 1
row = repo.list()[0]
assert row.cit_vph_ocr_estatus == OcrEstatus.FALLIDO
assert row.cit_vph_ocr_requiere_revision is True
def test_run_pending_extractions_logs_to_governance(cacu_db, governance_db):
from persistance.governance import extraction_run_repository
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
run_pending_extractions(
repo,
CIT_VPH_COLUMNS,
StubVphExtractor(),
domain="cacu",
entity="citologiacervical",
governance_repository=extraction_run_repository,
source_description="HIS export 2026-09-01",
)
runs = extraction_run_repository.list()
assert len(runs) == 1
assert runs[0].domain == "cacu"
assert runs[0].source_description == "HIS export 2026-09-01"
def test_done_rows_do_not_use_up_the_batch(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
for n in range(3):
repo.create(CitologiaCervical(pac_id_hospital=f"H-{n}", cit_vph_pdf_blob=b"%PDF-fake",
cit_vph_ocr_estatus=OcrEstatus.REALIZADO.value))
repo.create(CitologiaCervical(pac_id_hospital="H-nuevo", cit_vph_pdf_blob=b"%PDF-fake"))
repo.create(CitologiaCervical(pac_id_hospital="H-sin-pdf"))
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu",
entity="citologiacervical", limit=1)
assert (summary.processed, summary.skipped_already_done) == (1, 3)
assert repo.list(pac_id_hospital="H-nuevo")[0].cit_vph_resultado == "POSITIVO"
assert repo.list(pac_id_hospital="H-sin-pdf")[0].cit_vph_ocr_estatus is None
+40
View File
@@ -0,0 +1,40 @@
from core.ocr import OcrEstatus
from extraction.testing import scanned_pdf, text_pdf
from models.ocr import CinGradoOcrExtractor, GradoHistologicoOcrExtractor, VphOcrExtractor
def test_cin_grade_from_narrative_diagnosis():
report = text_pdf(
[
[
"REPORTE DE ESTUDIO HISTOPATOLOGICO",
"Descripción microscópica: epitelio escamoso con atipia en el tercio inferior.",
"No se observa carcinoma invasor.",
"DIAGNÓSTICO:",
"Lesión intraepitelial escamosa de bajo grado (NIC I) asociada a VPH.",
]
]
)
result = CinGradoOcrExtractor().extract(report)
assert result.values == {"grado": "LIEBG"}
assert result.estatus is OcrEstatus.REALIZADO
def test_breast_histological_grade_prefers_in_situ_over_its_prefix():
report = text_pdf([["Diagnóstico: CARCINOMA DUCTAL IN SITU de alto grado nuclear."]])
assert GradoHistologicoOcrExtractor().extract(report).values == {"grado": "CARCINOMA_IN_SITU"}
def test_scanned_vph_report_uses_tesseract_and_reports_confidence():
report = scanned_pdf([["Resultado VPH: NEGATIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: NO DETECTADO"]])
result = VphOcrExtractor().extract(report)
assert result.values == {"resultado": "NEGATIVO", "genotipo_16": 0, "genotipo_18": 0}
assert result.metodo_principal.startswith("tesseract")
assert 0 < result.confianza <= 1
def test_missing_fields_require_review_and_empty_reports_fail():
partial = VphOcrExtractor().extract(text_pdf([["VPH alto riesgo: POSITIVO"]]))
assert partial.estatus is OcrEstatus.REALIZADO and partial.requiere_revision
empty = VphOcrExtractor().extract(text_pdf([["Hoja sin resultados de laboratorio"]]))
assert empty.estatus is OcrEstatus.FALLIDO and empty.requiere_revision
+80
View File
@@ -0,0 +1,80 @@
import json
import pytest
from models.base import ScreeningModel
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
from models.registry import registry
class StubModel(ScreeningModel):
domain = "cacu"
def train(self, data=None):
raise NotImplementedError
def predict(self, data):
return {"label": "positivo", "confianza": 0.73}
def never_applicable(row: dict) -> bool:
return False
def _promote_a_version(production_ready):
domain, scenario, version = production_ready("v1-prod")
return registry.promote(domain, scenario, version)
def test_predict_and_record_persists_prediction_tagged_with_active_version(production_ready):
version = _promote_a_version(production_ready)
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
prediction = service.predict_and_record(
{"edad": 40},
pac_id_hospital="H-1",
interpretability=Interpretability(odds_ratio=1.8),
)
assert prediction.mlflow_run_id == version.run_id
assert prediction.modelo_version == str(version.version)
assert prediction.applicability_passed is True
assert json.loads(prediction.output)["label"] == "positivo"
assert json.loads(prediction.interpretability)["odds_ratio"] == 1.8
def test_predict_without_active_version_raises(governance_db, mlflow_tracking):
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
with pytest.raises(RuntimeError, match="no hay una versión en producción"):
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
def test_applicability_gate_flags_but_does_not_block_by_default(production_ready):
_promote_a_version(production_ready)
service = PredictionService(
StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable
)
prediction = service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
assert prediction.applicability_passed is False
def test_applicability_gate_can_reject_outright(production_ready):
_promote_a_version(production_ready)
service = PredictionService(
StubModel(),
domain="cacu",
scenario="tamizaje",
aplicable=never_applicable,
reject_inapplicable=True,
)
with pytest.raises(ApplicabilityRejected):
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
def test_applicability_gate_needs_a_dict(production_ready):
_promote_a_version(production_ready)
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable)
with pytest.raises(TypeError):
service.predict_and_record([40], pac_id_hospital="H-1")
+74
View File
@@ -0,0 +1,74 @@
import pytest
from core.governance.enums import ArtifactKind, Environment
from models.registry import PromotionBlocked, registry
def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking):
version = registry.register(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert registry.status("cacu", "tamizaje", version) == "desarrollo"
with pytest.raises(PromotionBlocked) as blocked:
registry.promote("cacu", "tamizaje", version)
failed = {check.code for check in blocked.value.checks if not check.passed}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
domain, scenario, first = production_ready("v1")
_, _, second = production_ready("v2", metrics={"auc": 0.84})
assert registry.status(domain, scenario, first) == "candidata"
registry.promote(domain, scenario, first)
registry.promote(domain, scenario, second)
assert registry.status(domain, scenario, first) == "retirada"
assert registry.status(domain, scenario, second) == "produccion"
other_domain, other_scenario, other_version = production_ready("v1-dx", scenario="diagnostico")
registry.promote(other_domain, other_scenario, other_version)
assert registry.status(domain, scenario, second) == "produccion"
def test_reports_can_be_attached_after_training(production_ready):
domain, scenario, version = production_ready("v1")
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri=None)
assert not next(c for c in registry.checks(domain, scenario, version) if c.code == "MLD-01b").passed
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri="docs/clinica-v2.pdf")
assert all(c.passed for c in registry.checks(domain, scenario, version))
with pytest.raises(ValueError):
registry.attach_reports(domain, scenario, version, metrics="{}")
def test_artifacts_are_logged_to_the_run(production_ready):
domain, scenario, version = production_ready("v1")
lineage = registry.lineage(domain, scenario, version)
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
def test_retire_and_lineage(production_ready):
domain, scenario, first = production_ready("v1", metrics={"auc": 0.8, "brier": 0.2})
_, _, second = production_ready("v2", metrics={"auc": 0.85})
registry.promote(domain, scenario, second)
lineage = registry.lineage(domain, scenario, second)
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
assert [p["paso"] for p in lineage["cohorte_exclusiones"]] == ["candidatas", "sin evento previo"]
assert lineage["model_version"]["status"] == "produccion"
registry.retire(domain, scenario, second)
assert registry.status(domain, scenario, second) == "retirada"
with pytest.raises(ValueError):
registry.retire(domain, scenario, second)
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
from models.export import inspect_onnx_metadata
with pytest.raises(ValueError, match="ONNX"):
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "x.onnx"
path.write_bytes(b"weights")
inspect_onnx_metadata(path)
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
with pytest.raises(ValueError):
registry.versions(domain, scenario)
-105
View File
@@ -1,105 +0,0 @@
"""El contrato `EstimadorDeRiesgo` y el estimador sustituto (ADR-MD-008)."""
import pytest
from models import riesgo
from models.riesgo import (
REGLA_SINTETICA_CAMA,
REGLA_SINTETICA_TEA,
EstimadorDeRiesgo,
Riesgo,
RiesgoSintetico,
RiesgoSinteticoCama,
RiesgoSinteticoTea,
)
COLUMNAS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"]
FILAS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"), (3, "2024-09-01", 0, None, None)]
def test_el_sustituto_cumple_el_contrato():
assert isinstance(RiesgoSintetico(), EstimadorDeRiesgo)
def test_un_riesgo_por_miembro_y_horizonte_en_el_orden_del_marco():
riesgos = RiesgoSintetico(horizontes=(0.0, 1.0)).estimar(COLUMNAS, FILAS)
assert [(r.pac_id, r.horizonte_anios) for r in riesgos] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)]
assert all(isinstance(r, Riesgo) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in riesgos)
def test_la_regla_suma_por_predictor_basal():
p = {r.pac_id: r.probabilidad for r in RiesgoSintetico().estimar(COLUMNAS, FILAS)}
assert p == {1: 0.01, 2: 0.16, 3: 0.01}
def test_es_determinista():
a, b = RiesgoSintetico(), RiesgoSintetico()
assert a.estimar(COLUMNAS, FILAS) == b.estimar(COLUMNAS, FILAS)
assert a.procedencia() == b.procedencia()
def test_la_procedencia_trae_las_cuatro_llaves_y_su_sha_cambia_con_la_regla(monkeypatch):
procedencia = RiesgoSintetico().procedencia()
assert set(procedencia.como_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"}
assert all(procedencia.como_dict().values())
monkeypatch.setitem(riesgo.REGLA_SINTETICA, "vph_positivo", 0.2)
assert RiesgoSintetico().procedencia().modelo_sha != procedencia.modelo_sha
def test_sin_los_predictores_falla_y_los_nombra():
with pytest.raises(ValueError, match="pap_0"):
RiesgoSintetico().estimar(["pac_id", "hpv_0"], [(1, None)])
# --- El sustituto de TEA (T-21f) ---------------------------------------------------------------
COLUMNAS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes",
"hipoacusia_0"]
def test_el_sustituto_de_tea_cumple_el_contrato_y_lee_su_cohorte():
estimador = RiesgoSinteticoTea()
assert isinstance(estimador, EstimadorDeRiesgo)
assert estimador.cohorte_url == "tea/cohorte_tamizaje" and estimador.horizontes == (4.0,)
def test_la_regla_de_tea_suma_mchat_ucin_y_apgar_bajo():
filas = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None),
(2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"),
(3, None, None, None, None, None, None, 0, None)]
r = REGLA_SINTETICA_TEA
assert [x.probabilidad for x in RiesgoSinteticoTea().estimar(COLUMNAS_TEA, filas)] == pytest.approx(
[r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]])
def test_el_sustituto_de_tea_sin_sus_predictores_falla():
with pytest.raises(ValueError, match="mchat_0"):
RiesgoSinteticoTea().estimar(["pac_id", "fecha_indice"], [])
# --- El sustituto de CaMa (T-21g) --------------------------------------------------------------
COLUMNAS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"]
def test_el_sustituto_de_cama_cumple_el_contrato_y_lee_su_cohorte():
estimador = RiesgoSinteticoCama()
assert isinstance(estimador, EstimadorDeRiesgo)
assert estimador.cohorte_url == "cama/cohorte_tamizaje" and estimador.horizontes == (1.0,)
def test_la_regla_de_cama_suma_por_birads_indice_y_4a_cuenta_como_4():
filas = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0),
(3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)]
r = REGLA_SINTETICA_CAMA
assert [x.probabilidad for x in RiesgoSinteticoCama().estimar(COLUMNAS_CAMA, filas)] == pytest.approx(
[r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]])
def test_el_sustituto_de_cama_sin_su_predictor_falla():
with pytest.raises(ValueError, match="birads_0"):
RiesgoSinteticoCama().estimar(["pac_id", "fecha_indice"], [])
+83
View File
@@ -0,0 +1,83 @@
import pytest
from core.governance.enums import ArtifactKind, Environment
from models.registry import registry
from mlflow import MlflowException
from models.training import ReadOnlyRepository, TrainingRun
def test_prod_run_requires_a_cohort_build():
with pytest.raises(ValueError, match="cohorte_armado_id"):
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD)
def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert run.cohorte_armado_id is None
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
checkpoint = tmp_path / "model.onnx"
checkpoint.write_bytes(b"fake-onnx-bytes")
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
version = run.finish(metrics={"auc": 0.81})
mv = registry.get("cacu", "tamizaje", version)
assert mv.tags["environment"] == Environment.DEV.value
metrics = registry.client.get_run(mv.run_id).data.metrics
assert metrics["auc"] == 0.81
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
assert any(path.endswith("model.onnx") for path in artifacts)
def test_read_only_repository_blocks_writes(cacu_db):
from persistance.cacu import paciente_repository
read_only = ReadOnlyRepository(paciente_repository)
assert read_only.list() == []
with pytest.raises(PermissionError, match="ML-04"):
read_only.create(object())
with pytest.raises(PermissionError, match="ML-04"):
read_only.open_session()
def test_training_run_repository_is_read_only(cacu_db, mlflow_tracking):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
repo = run.repository("paciente")
assert isinstance(repo, ReadOnlyRepository)
with pytest.raises(PermissionError):
repo.create(object())
def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, tmp_path, monkeypatch):
root = tmp_path / "artefactos"
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(root))
run = TrainingRun(domain="cama", scenario="riesgo", environment=Environment.DEV)
experiment = run.client.get_experiment_by_name("cama-riesgo")
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert run.finish() == "1"
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert second.finish() == "2"
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
def unreachable(name):
raise MlflowException("servidor no disponible")
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
with pytest.raises(MlflowException, match="no disponible"):
third.finish()
def test_unknown_domain_is_rejected():
with pytest.raises(ValueError, match="dominio desconocido"):
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)