Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f9d3b8f67e | |||
| 6e8ed1003d | |||
| cbb3b9c7b6 |
@@ -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/
|
||||
|
||||
@@ -1,54 +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`.
|
||||
|
||||
+27
-7
@@ -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
@@ -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
@@ -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.")
|
||||
|
||||
|
||||
@@ -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
@@ -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
|
||||
@@ -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
|
||||
@@ -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])
|
||||
+3
-1
@@ -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.")
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -5,10 +5,21 @@ description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"persistance",
|
||||
"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]
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
@@ -20,4 +31,6 @@ packages = ["models"]
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"onnx>=1.15",
|
||||
"reportlab>=4.0",
|
||||
]
|
||||
|
||||
@@ -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
|
||||
@@ -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")
|
||||
@@ -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')",
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user