From 2d22409e1f5e307dd5900b072b377a45ceedb7a6 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 12:48:41 -0600 Subject: [PATCH] Layout: per-domain folders, io, steps and pipelines, and one command line --- README.md | 20 +++++---- models/__main__.py | 32 +++++++++++++++ models/base.py | 41 ------------------- models/cacu.py | 21 ---------- models/cacu/__init__.py | 1 + .../notebooks}/cin2_logistic/01_eda.ipynb | 2 +- models/cama.py | 21 ---------- models/cama/__init__.py | 1 + models/dags/__init__.py | 1 - models/io/__init__.py | 1 + models/{ => io}/contract.py | 0 models/{ => io}/export.py | 2 +- models/{ => io}/prediction.py | 17 +++++--- models/{ => io}/registry.py | 6 +-- models/io/repositories.py | 14 +++++++ models/{ => io}/training.py | 6 +-- models/ocr.py | 2 +- models/pipelines/__init__.py | 1 + models/{dags => pipelines}/reading.py | 0 models/steps/__init__.py | 1 + models/tea.py | 21 ---------- models/tea/__init__.py | 1 + models/testing.py | 2 +- pyproject.toml | 5 ++- tests/conftest.py | 2 +- tests/{ => io}/test_contract.py | 4 +- tests/{ => io}/test_export.py | 2 +- tests/{ => io}/test_model_versions.py | 6 +-- tests/{ => io}/test_prediction.py | 12 ++---- tests/{ => io}/test_registry.py | 4 +- tests/io/test_repositories.py | 28 +++++++++++++ tests/{ => io}/test_training.py | 4 +- tests/{ => pipelines}/test_reading_nodes.py | 4 +- tests/test_data_access.py | 27 ------------ tests/test_interfaces.py | 19 --------- tests/test_main.py | 33 +++++++++++++++ 36 files changed, 164 insertions(+), 200 deletions(-) create mode 100644 models/__main__.py delete mode 100644 models/base.py delete mode 100644 models/cacu.py create mode 100644 models/cacu/__init__.py rename {notebooks/cacu => models/cacu/notebooks}/cin2_logistic/01_eda.ipynb (92%) delete mode 100644 models/cama.py create mode 100644 models/cama/__init__.py delete mode 100644 models/dags/__init__.py create mode 100644 models/io/__init__.py rename models/{ => io}/contract.py (100%) rename models/{ => io}/export.py (94%) rename models/{ => io}/prediction.py (91%) rename models/{ => io}/registry.py (98%) create mode 100644 models/io/repositories.py rename models/{ => io}/training.py (97%) create mode 100644 models/pipelines/__init__.py rename models/{dags => pipelines}/reading.py (100%) create mode 100644 models/steps/__init__.py delete mode 100644 models/tea.py create mode 100644 models/tea/__init__.py rename tests/{ => io}/test_contract.py (95%) rename tests/{ => io}/test_export.py (97%) rename tests/{ => io}/test_model_versions.py (97%) rename tests/{ => io}/test_prediction.py (89%) rename tests/{ => io}/test_registry.py (96%) create mode 100644 tests/io/test_repositories.py rename tests/{ => io}/test_training.py (96%) rename tests/{ => pipelines}/test_reading_nodes.py (98%) delete mode 100644 tests/test_data_access.py delete mode 100644 tests/test_interfaces.py create mode 100644 tests/test_main.py diff --git a/README.md b/README.md index 32fa680..fd52038 100644 --- a/README.md +++ b/README.md @@ -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 (`-`), 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 `. 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 (`-`), 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 diff --git a/models/__main__.py b/models/__main__.py new file mode 100644 index 0000000..979b835 --- /dev/null +++ b/models/__main__.py @@ -0,0 +1,32 @@ +"""The package's command line: `python -m models `. + +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="", 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()) diff --git a/models/base.py b/models/base.py deleted file mode 100644 index b6773f5..0000000 --- a/models/base.py +++ /dev/null @@ -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.` 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.._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.""" diff --git a/models/cacu.py b/models/cacu.py deleted file mode 100644 index 03d711e..0000000 --- a/models/cacu.py +++ /dev/null @@ -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.") diff --git a/models/cacu/__init__.py b/models/cacu/__init__.py new file mode 100644 index 0000000..d4c0509 --- /dev/null +++ b/models/cacu/__init__.py @@ -0,0 +1 @@ +"""CaCu's scenarios and notebooks.""" diff --git a/notebooks/cacu/cin2_logistic/01_eda.ipynb b/models/cacu/notebooks/cin2_logistic/01_eda.ipynb similarity index 92% rename from notebooks/cacu/cin2_logistic/01_eda.ipynb rename to models/cacu/notebooks/cin2_logistic/01_eda.ipynb index 320fc8a..c5be55f 100644 --- a/notebooks/cacu/cin2_logistic/01_eda.ipynb +++ b/models/cacu/notebooks/cin2_logistic/01_eda.ipynb @@ -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" }, { diff --git a/models/cama.py b/models/cama.py deleted file mode 100644 index 95d12e6..0000000 --- a/models/cama.py +++ /dev/null @@ -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.") diff --git a/models/cama/__init__.py b/models/cama/__init__.py new file mode 100644 index 0000000..80028b4 --- /dev/null +++ b/models/cama/__init__.py @@ -0,0 +1 @@ +"""CaMa's scenarios and notebooks.""" diff --git a/models/dags/__init__.py b/models/dags/__init__.py deleted file mode 100644 index 2d7d505..0000000 --- a/models/dags/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Hamilton modules for the model DAGs: each function is a node, each parameter an edge.""" diff --git a/models/io/__init__.py b/models/io/__init__.py new file mode 100644 index 0000000..c19e917 --- /dev/null +++ b/models/io/__init__.py @@ -0,0 +1 @@ +"""Data in and out, and the contracts: databases, files, the model registry. Nothing here computes.""" diff --git a/models/contract.py b/models/io/contract.py similarity index 100% rename from models/contract.py rename to models/io/contract.py diff --git a/models/export.py b/models/io/export.py similarity index 94% rename from models/export.py rename to models/io/export.py index 5201ebe..9d9ecc7 100644 --- a/models/export.py +++ b/models/io/export.py @@ -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}`. diff --git a/models/prediction.py b/models/io/prediction.py similarity index 91% rename from models/prediction.py rename to models/io/prediction.py index fc00737..588fcd3 100644 --- a/models/prediction.py +++ b/models/io/prediction.py @@ -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() diff --git a/models/registry.py b/models/io/registry.py similarity index 98% rename from models/registry.py rename to models/io/registry.py index 60689a2..874c548 100644 --- a/models/registry.py +++ b/models/io/registry.py @@ -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) diff --git a/models/io/repositories.py b/models/io/repositories.py new file mode 100644 index 0000000..fd7e0fb --- /dev/null +++ b/models/io/repositories.py @@ -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.` 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 diff --git a/models/training.py b/models/io/training.py similarity index 97% rename from models/training.py rename to models/io/training.py index d25e0a7..a6d70e0 100644 --- a/models/training.py +++ b/models/io/training.py @@ -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 - `-` tagged with `models.registry`'s promotion + `-` 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.""" diff --git a/models/ocr.py b/models/ocr.py index e54b671..295d17d 100644 --- a/models/ocr.py +++ b/models/ocr.py @@ -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. diff --git a/models/pipelines/__init__.py b/models/pipelines/__init__.py new file mode 100644 index 0000000..cf0fbaa --- /dev/null +++ b/models/pipelines/__init__.py @@ -0,0 +1 @@ +"""Hamilton modules that wire steps into graphs: each function is a node, each parameter an edge.""" diff --git a/models/dags/reading.py b/models/pipelines/reading.py similarity index 100% rename from models/dags/reading.py rename to models/pipelines/reading.py diff --git a/models/steps/__init__.py b/models/steps/__init__.py new file mode 100644 index 0000000..b3a5d1c --- /dev/null +++ b/models/steps/__init__.py @@ -0,0 +1 @@ +"""Pure functions shared by every model: no I/O, testable alone.""" diff --git a/models/tea.py b/models/tea.py deleted file mode 100644 index e42bf90..0000000 --- a/models/tea.py +++ /dev/null @@ -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.") diff --git a/models/tea/__init__.py b/models/tea/__init__.py new file mode 100644 index 0000000..62a9d63 --- /dev/null +++ b/models/tea/__init__.py @@ -0,0 +1 @@ +"""TEA's scenarios and notebooks.""" diff --git a/models/testing.py b/models/testing.py index 6e1e092..a3bc49d 100644 --- a/models/testing.py +++ b/models/testing.py @@ -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} diff --git a/pyproject.toml b/pyproject.toml index d054073..a063a5f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 = [ diff --git a/tests/conftest.py b/tests/conftest.py index 67f5955..e50e900 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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( diff --git a/tests/test_contract.py b/tests/io/test_contract.py similarity index 95% rename from tests/test_contract.py rename to tests/io/test_contract.py index 2ebe277..b178ee9 100644 --- a/tests/test_contract.py +++ b/tests/io/test_contract.py @@ -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: diff --git a/tests/test_export.py b/tests/io/test_export.py similarity index 97% rename from tests/test_export.py rename to tests/io/test_export.py index 05fad8e..c516199 100644 --- a/tests/test_export.py +++ b/tests/io/test_export.py @@ -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: diff --git a/tests/test_model_versions.py b/tests/io/test_model_versions.py similarity index 97% rename from tests/test_model_versions.py rename to tests/io/test_model_versions.py index 505e23a..a702716 100644 --- a/tests/test_model_versions.py +++ b/tests/io/test_model_versions.py @@ -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): diff --git a/tests/test_prediction.py b/tests/io/test_prediction.py similarity index 89% rename from tests/test_prediction.py rename to tests/io/test_prediction.py index 9d147b1..0b42866 100644 --- a/tests/test_prediction.py +++ b/tests/io/test_prediction.py @@ -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} diff --git a/tests/test_registry.py b/tests/io/test_registry.py similarity index 96% rename from tests/test_registry.py rename to tests/io/test_registry.py index dc36e00..bc746b5 100644 --- a/tests/test_registry.py +++ b/tests/io/test_registry.py @@ -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 diff --git a/tests/io/test_repositories.py b/tests/io/test_repositories.py new file mode 100644 index 0000000..2ba6099 --- /dev/null +++ b/tests/io/test_repositories.py @@ -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") diff --git a/tests/test_training.py b/tests/io/test_training.py similarity index 96% rename from tests/test_training.py rename to tests/io/test_training.py index c4246d2..4a2b2fb 100644 --- a/tests/test_training.py +++ b/tests/io/test_training.py @@ -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(): diff --git a/tests/test_reading_nodes.py b/tests/pipelines/test_reading_nodes.py similarity index 98% rename from tests/test_reading_nodes.py rename to tests/pipelines/test_reading_nodes.py index 13afc9c..0cb515f 100644 --- a/tests/test_reading_nodes.py +++ b/tests/pipelines/test_reading_nodes.py @@ -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) diff --git a/tests/test_data_access.py b/tests/test_data_access.py deleted file mode 100644 index 905043e..0000000 --- a/tests/test_data_access.py +++ /dev/null @@ -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") diff --git a/tests/test_interfaces.py b/tests/test_interfaces.py deleted file mode 100644 index a5b0fee..0000000 --- a/tests/test_interfaces.py +++ /dev/null @@ -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) diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..6114f79 --- /dev/null +++ b/tests/test_main.py @@ -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