Layout: per-domain folders, io, steps and pipelines, and one command line #3
@@ -9,16 +9,18 @@ WebApi.
|
||||
|
||||
| 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`. |
|
||||
| `contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). |
|
||||
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
|
||||
| `dags/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
||||
| `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); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. |
|
||||
| `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). |
|
||||
| `__main__.py` | La línea de comandos: `python -m models <comando>`. Cada área agrega ahí sus subcomandos. |
|
||||
| `io/contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). |
|
||||
| `io/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); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. |
|
||||
| `io/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`. |
|
||||
| `io/prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
|
||||
| `io/export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. |
|
||||
| `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. |
|
||||
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
|
||||
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
||||
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
|
||||
| `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. |
|
||||
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
|
||||
|
||||
MLflow se configura con sus propias variables (`MLFLOW_TRACKING_URI`).
|
||||
`MLFLOW_ARTIFACT_ROOT`, si existe, es la carpeta donde los experimentos nuevos
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""The package's command line: `python -m models <command>`.
|
||||
|
||||
Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit) belong inside the
|
||||
command that needs them, so `--help` stays immediate.
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
|
||||
|
||||
def _show_help(parser: argparse.ArgumentParser) -> int:
|
||||
"""A command without actions yet shows its help and fails, rather than appearing to have run."""
|
||||
parser.print_help()
|
||||
return 2
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.")
|
||||
commands = parser.add_subparsers(dest="command", metavar="<command>", required=True)
|
||||
|
||||
cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files")
|
||||
cohorts.set_defaults(run=lambda args: _show_help(cohorts))
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
return args.run(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,41 +0,0 @@
|
||||
import importlib
|
||||
from abc import ABC, abstractmethod
|
||||
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):
|
||||
"""Common train()/predict() interface for the CaCu, CaMa and TEA models.
|
||||
|
||||
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."""
|
||||
|
||||
@abstractmethod
|
||||
def predict(self, data: Any) -> Any:
|
||||
"""Score `data` and return predictions."""
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaCuModel(ScreeningModel):
|
||||
"""Scaffold for the CaCu (cervical cancer) screening model.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
domain = "cacu"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("CaCu training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaCu prediction is not implemented yet.")
|
||||
@@ -0,0 +1 @@
|
||||
"""CaCu's scenarios and notebooks."""
|
||||
+1
-1
@@ -17,7 +17,7 @@
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/notebooks/cacu/cin2_logistic → ../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[3] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))",
|
||||
"source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/models/cacu/notebooks/cin2_logistic → ../../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[4] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))",
|
||||
"id": "cacu-cin2-01-02"
|
||||
},
|
||||
{
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaMaModel(ScreeningModel):
|
||||
"""Scaffold for the CaMa (breast cancer) screening model.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
domain = "cama"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("CaMa training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaMa prediction is not implemented yet.")
|
||||
@@ -0,0 +1 @@
|
||||
"""CaMa's scenarios and notebooks."""
|
||||
@@ -1 +0,0 @@
|
||||
"""Hamilton modules for the model DAGs: each function is a node, each parameter an edge."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Data in and out, and the contracts: databases, files, the model registry. Nothing here computes."""
|
||||
@@ -1,6 +1,6 @@
|
||||
"""ONNX checkpoint inspection (ML-01b, MLD-03).
|
||||
|
||||
Writing/storing a checkpoint is `models.training.TrainingRun.log_artifact`,
|
||||
Writing/storing a checkpoint is `models.io.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}`.
|
||||
@@ -6,14 +6,19 @@ import hashlib
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from typing import Any, Protocol
|
||||
|
||||
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
|
||||
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
|
||||
|
||||
|
||||
class Predictor(Protocol):
|
||||
"""What the service needs from a model."""
|
||||
|
||||
def predict(self, data: Any) -> Any: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -42,7 +47,7 @@ class ApplicabilityRejected(Exception):
|
||||
|
||||
|
||||
class PredictionService:
|
||||
"""Runs a `ScreeningModel` and records its predictions against the
|
||||
"""Runs a model 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
|
||||
@@ -52,7 +57,7 @@ class PredictionService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: ScreeningModel,
|
||||
model: Predictor,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
@@ -104,7 +109,7 @@ class PredictionService:
|
||||
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"
|
||||
"promueva una con models.io.registry.registry.promote antes de predecir"
|
||||
)
|
||||
|
||||
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
@@ -24,7 +24,7 @@ from mlflow import MlflowClient, MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
from sqlmodel import select
|
||||
|
||||
from models.export import inspect_onnx_metadata
|
||||
from models.io.export import inspect_onnx_metadata
|
||||
|
||||
DOMAINS = ("cacu", "cama", "tea")
|
||||
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
||||
@@ -142,8 +142,8 @@ class ModelRegistry:
|
||||
**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
|
||||
In-process training uses `models.io.training.TrainingRun` directly."""
|
||||
from models.io.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)
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Finds a domain's Persistance repository by name, the same objects WebApi writes with."""
|
||||
import importlib
|
||||
|
||||
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
|
||||
@@ -31,8 +31,8 @@ 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, MODEL_SHA_TAG, REPORT_TAGS, registered_name
|
||||
from models.io.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name
|
||||
from models.io.repositories import resolve_repository
|
||||
|
||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
||||
MODEL_PATH = "model"
|
||||
@@ -173,7 +173,7 @@ class TrainingRun:
|
||||
**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
|
||||
`<domain>-<scenario>` tagged with `models.io.registry`'s promotion
|
||||
inputs (environment, cohort link, report URIs), and returns the new
|
||||
version string. Call once, after training (and artifact logging)
|
||||
completes."""
|
||||
+1
-1
@@ -32,7 +32,7 @@ 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 models.io.repositories import resolve_repository
|
||||
from persistance.repository import Repository
|
||||
|
||||
# Below this confidence a value is stored but flagged for manual review.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Hamilton modules that wire steps into graphs: each function is a node, each parameter an edge."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Pure functions shared by every model: no I/O, testable alone."""
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class TeaModel(ScreeningModel):
|
||||
"""Scaffold for the TEA (autism spectrum disorder) screening model.
|
||||
|
||||
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
|
||||
interface scaffolding only.
|
||||
"""
|
||||
|
||||
domain = "tea"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("TEA training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("TEA prediction is not implemented yet.")
|
||||
@@ -0,0 +1 @@
|
||||
"""TEA's scenarios and notebooks."""
|
||||
+1
-1
@@ -8,7 +8,7 @@ model and isn't used outside tests; it has no tests of its own.
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from models.contract import Provenance, Risk
|
||||
from models.io.contract import Provenance, Risk
|
||||
|
||||
# A base probability and what each baseline predictor adds, capped at `tope`.
|
||||
CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
|
||||
|
||||
+3
-2
@@ -7,13 +7,13 @@ dependencies = [
|
||||
"persistance",
|
||||
"extraction",
|
||||
"mlflow>=2.9",
|
||||
# The model DAGs (`models/dags`): each function a node, each parameter an edge.
|
||||
# The model DAGs (`models/pipelines`): each function a node, each parameter an edge.
|
||||
"apache-hamilton>=1.90",
|
||||
]
|
||||
|
||||
[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
|
||||
# models.io.export.inspect_onnx_metadata — writing/logging a checkpoint never
|
||||
# requires it, see that module's docstring.
|
||||
export = [
|
||||
"onnx>=1.15",
|
||||
@@ -29,6 +29,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["models"]
|
||||
exclude = ["**/notebooks"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ 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
|
||||
from models.io.registry import registry
|
||||
|
||||
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
|
||||
version = registry.register(
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""What this module covers: the `RiskEstimator` contract in `models.contract` and the two records it
|
||||
"""What this module covers: the `RiskEstimator` contract in `models.io.contract` and the two records it
|
||||
returns, `Risk` and `Provenance`.
|
||||
|
||||
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
|
||||
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
|
||||
"""
|
||||
|
||||
from models.contract import Provenance, Risk, RiskEstimator
|
||||
from models.io.contract import Provenance, Risk, RiskEstimator
|
||||
|
||||
|
||||
class ConstantEstimator:
|
||||
@@ -2,7 +2,7 @@ import onnx
|
||||
import onnx.helper
|
||||
import pytest
|
||||
|
||||
from models.export import inspect_onnx_metadata
|
||||
from models.io.export import inspect_onnx_metadata
|
||||
|
||||
|
||||
def _tiny_onnx_bytes() -> bytes:
|
||||
@@ -16,9 +16,9 @@ import pytest
|
||||
from core.governance.enums import Environment
|
||||
from mlflow import MlflowClient
|
||||
|
||||
from models import training
|
||||
from models.registry import MODEL_SHA_TAG, registry
|
||||
from models.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun
|
||||
from models.io import training
|
||||
from models.io.registry import MODEL_SHA_TAG, registry
|
||||
from models.io.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun
|
||||
|
||||
|
||||
class Constant(mlflow.pyfunc.PythonModel):
|
||||
@@ -2,17 +2,11 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
from models.base import ScreeningModel
|
||||
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
|
||||
from models.registry import registry
|
||||
from models.io.prediction import ApplicabilityRejected, Interpretability, PredictionService
|
||||
from models.io.registry import registry
|
||||
|
||||
|
||||
class StubModel(ScreeningModel):
|
||||
domain = "cacu"
|
||||
|
||||
def train(self, data=None):
|
||||
raise NotImplementedError
|
||||
|
||||
class StubModel:
|
||||
def predict(self, data):
|
||||
return {"label": "positivo", "confianza": 0.73}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import PromotionBlocked, registry
|
||||
from models.io.registry import PromotionBlocked, registry
|
||||
|
||||
|
||||
def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking):
|
||||
@@ -56,7 +56,7 @@ def test_retire_and_lineage(production_ready):
|
||||
|
||||
|
||||
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
|
||||
from models.export import inspect_onnx_metadata
|
||||
from models.io.export import inspect_onnx_metadata
|
||||
|
||||
with pytest.raises(ValueError, match="ONNX"):
|
||||
import tempfile
|
||||
@@ -0,0 +1,28 @@
|
||||
"""What this module covers: `resolve_repository`, how `models` finds a domain's Persistance repository by name.
|
||||
|
||||
Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from models.io.repositories import resolve_repository
|
||||
|
||||
|
||||
def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db):
|
||||
"""A repository found by name reads what was written through it, in batches and with filters. Fails if
|
||||
`resolve_repository` looks in another module or stops returning a working repository."""
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
|
||||
repository = resolve_repository("cacu", "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)))
|
||||
|
||||
assert [r.pac_id_hospital for r in repository.iter_all(batch_size=3)] == [f"M-{i}" for i in range(7)]
|
||||
assert list(repository.iter_all(pac_id_hospital="M-3"))[0].pac_sexo == "Femenino"
|
||||
|
||||
|
||||
def test_unknown_entity_is_a_clear_error():
|
||||
"""An unknown name raises `ValueError` naming it. Fails if the `AttributeError` is no longer translated."""
|
||||
with pytest.raises(ValueError, match="no nope_repository"):
|
||||
resolve_repository("tea", "nope")
|
||||
@@ -1,10 +1,10 @@
|
||||
import pytest
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import registry
|
||||
from models.io.registry import registry
|
||||
from mlflow import MlflowException
|
||||
|
||||
from models.training import ReadOnlyRepository, TrainingRun
|
||||
from models.io.training import ReadOnlyRepository, TrainingRun
|
||||
|
||||
|
||||
def test_prod_run_requires_a_cohort_build():
|
||||
@@ -1,4 +1,4 @@
|
||||
"""What this module covers: the reading nodes of `models.dags.reading` (`cohort_build`, `members`, `known_until`, `timeline`)
|
||||
"""What this module covers: the reading nodes of `models.pipelines.reading` (`cohort_build`, `members`, `known_until`, `timeline`)
|
||||
run by a Hamilton driver built from that module alone, and their place in the asset graph.
|
||||
|
||||
Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain
|
||||
@@ -29,7 +29,7 @@ from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String,
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from models.dags import reading
|
||||
from models.pipelines import reading
|
||||
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo)
|
||||
@@ -1,27 +0,0 @@
|
||||
"""`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")
|
||||
@@ -1,19 +0,0 @@
|
||||
import pytest
|
||||
|
||||
from models.cacu import CaCuModel
|
||||
from models.cama import CaMaModel
|
||||
from models.tea import TeaModel
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
|
||||
def test_train_not_implemented(cls):
|
||||
model = cls()
|
||||
with pytest.raises(NotImplementedError):
|
||||
model.train()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
|
||||
def test_predict_not_implemented(cls):
|
||||
model = cls()
|
||||
with pytest.raises(NotImplementedError):
|
||||
model.predict(data=None)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""What this module covers: the command line in `models/__main__.py`.
|
||||
|
||||
Fixtures: none; the commands declared so far touch no data.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from models.__main__ import main
|
||||
|
||||
|
||||
def test_help_lists_the_subcommands():
|
||||
"""`python -m models --help` runs as a module and lists `cohorts`. Fails if the entry point breaks or the
|
||||
subcommand stops being registered."""
|
||||
result = subprocess.run([sys.executable, "-m", "models", "--help"], capture_output=True, text=True)
|
||||
assert result.returncode == 0
|
||||
assert "cohorts" in result.stdout
|
||||
|
||||
|
||||
def test_a_command_is_required():
|
||||
"""Without a command the parser exits with an error. Fails if `required=True` is dropped, which would make
|
||||
a bare call look successful."""
|
||||
with pytest.raises(SystemExit) as exit_info:
|
||||
main([])
|
||||
assert exit_info.value.code == 2
|
||||
|
||||
|
||||
def test_a_command_without_actions_does_not_report_success(capsys):
|
||||
"""`cohorts` has no actions yet, so it shows its help and returns an error code. Fails if it returns 0, which
|
||||
would let a script believe it had run."""
|
||||
assert main(["cohorts"]) == 2
|
||||
assert "cohorts" in capsys.readouterr().out
|
||||
Reference in New Issue
Block a user