Files
models/models/__main__.py
T

271 lines
13 KiB
Python

"""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 _model_module(args: argparse.Namespace, name: str):
"""A module of the model's folder; `None` and a message on stderr if there's no such model."""
from importlib import import_module
package = f"models.{args.domain}.{args.scenario}"
try:
return import_module(f"{package}.{name}")
except ModuleNotFoundError as error:
if not (error.name or "").startswith(package):
raise
print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr)
return None
def _cohort_file(args: argparse.Namespace, model):
"""The build's exported file; `None` and a message on stderr if it's missing."""
from persistance.settings import settings
from models.io.storage import cohorts_root, find_cohort_file
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
return find_cohort_file(root, model.SETTINGS["cohort"], args.armado)
except (FileNotFoundError, ValueError) as error:
print(f"{error}: export it with `python -m models cohorts export {model.SETTINGS['cohort'].replace('/', ' ')}`", file=sys.stderr)
return None
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Trains the model on the build's file, always as a new version."""
if args.environment == "prod" and args.armado is None:
parser.error("a prod run names its cohort build: --armado (ML-03)")
if not (model := _model_module(args, "model")) or not (trainer := _model_module(args, "train")):
return 1
if not (path := _cohort_file(args, model)):
return 1
print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}")
return 0
def _estimate_step(args: argparse.Namespace, path) -> int:
estimator = _model_module(args, "estimate")
if not estimator:
return 1
try:
resolved, written = estimator.estimate(path, args.output, args.version)
except LookupError as error:
print(error, file=sys.stderr)
return 1
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {path}, to {args.output}")
return 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build's file with a registered version and writes the output file."""
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
return 1
return _estimate_step(args, path)
def _promote_step(args: argparse.Namespace, version: str) -> int:
from mlflow import MlflowException
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
name = registered_name(args.domain, args.scenario)
try:
current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version
except MlflowException:
current = None
if str(current) == str(version):
print(f"already in production: version {version}")
return 0
registry.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
print(f"in production: version {version}")
return 0
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
if not (args.export or args.train or args.promote or args.estimate):
parser.error("name at least one step: --export, --train, --promote, --estimate")
if args.estimate and not args.output:
parser.error("--estimate needs --output")
if args.train and args.environment == "prod" and args.armado is None:
parser.error("a prod run names its cohort build: --armado (ML-03)")
if args.train and args.version:
parser.error("--version names an existing version: it can't go with --train")
if not (model := _model_module(args, "model")):
return 1
if args.export:
cohort = model.SETTINGS["cohort"].split("/", 1)[1]
export = argparse.Namespace(domain=args.domain, cohort=cohort, source="kit", build=args.armado, manifest=None)
if code := _cohort_export(export):
return code
if not (args.train or args.promote or args.estimate):
return 0
if not (path := _cohort_file(args, model)):
return 1
version = args.version
if args.train or (args.promote and not version):
if not (trainer := _model_module(args, "train")):
return 1
environment = args.environment.upper()
version = trainer.find_trained(path, environment)
if args.train and version:
print(f"already trained: version {version}, from {path}")
elif args.train:
version = trainer.train(path, environment)
print(f"trained: version {version}, from {path}")
elif not version:
print(f"no {environment} version trained on {path}: use --train or --version", file=sys.stderr)
return 1
if args.promote and (code := _promote_step(args, version)):
return code
return _estimate_step(args, path) if args.estimate else 0
def _cohort_build(args: argparse.Namespace) -> int:
"""Runs the cohort's rules and shows its attrition, or only its graph. Stores nothing."""
from sqlalchemy.exc import DBAPIError
from importlib import import_module
from models.io.contracts import CohortDefinitionError
from models.io.storage import read_queries
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
url = f"{args.domain}/{args.cohort}"
try:
queries = read_queries(args.manifest, url)
if args.graph:
print(mermaid(build_driver(queries).graph))
return 0
built = build_cohort(queries, import_module(f"persistance.{args.domain}").dbt_query_repository)
except (FileNotFoundError, CohortDefinitionError) as error:
print(error, file=sys.stderr)
return 1
except DBAPIError as error:
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
return 1
print(built.attrition.to_string(index=False))
print(f"{url}: {len(built.study_population)} members, not stored")
return 0
def _cohort_export(args: argparse.Namespace) -> int:
"""Exports a build to its Parquet file: the kit's stored build, or one built now from dbt's rules."""
from importlib import import_module
from persistance.aristas.dbt import DbtRelationError
from persistance.settings import settings
from sqlalchemy.exc import DBAPIError
from models.io.contracts import CohortDefinitionError
from models.io.storage import read_queries
from models.io.storage import cohorts_root
from models.pipelines.export_cohort import export_dbt_build, export_kit_build
url = f"{args.domain}/{args.cohort}"
repositories = import_module(f"persistance.{args.domain}")
timeline = repositories.timeline_repository
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
if args.source == "dbt":
queries = read_queries(args.manifest, url)
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
else:
path, outcome = export_kit_build(repositories.cohorte_repository, timeline, root, args.domain, url, args.build)
except PermissionError as error:
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
return 1
except DBAPIError as error:
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
return 1
except (FileNotFoundError, LookupError, ValueError, DbtRelationError) as error:
print(error, file=sys.stderr)
return 1
print(f"{outcome}: {path}")
return 0
def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
if args.source == "dbt" and not args.manifest:
parser.error("--source dbt needs --manifest")
if args.source == "dbt" and args.build is not None:
parser.error("--build names a kit build: it can't go with --source dbt")
return _cohort_export(args)
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))
actions = cohorts.add_subparsers(dest="action", metavar="<action>")
build = actions.add_parser("build", help="run a cohort's rules and show its attrition; stores nothing")
build.add_argument("domain", choices=["cacu", "cama", "tea"])
build.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
build.add_argument("--manifest", required=True, help="the manifest.json `dbt compile` wrote")
build.add_argument("--graph", action="store_true", help="print the chain as a Mermaid diagram without running it")
build.set_defaults(run=_cohort_build)
export = actions.add_parser("export", help="export a build to its Parquet file, once")
export.add_argument("domain", choices=["cacu", "cama", "tea"])
export.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
export.add_argument("--source", choices=["kit", "dbt"], default="kit",
help="the kit's stored build, or one built now from dbt's rules")
export.add_argument("--build", type=int, help="the kit build's armado_id; the cohort's latest by default")
export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt")
export.set_defaults(run=lambda args: _cohort_export_checked(export, args))
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
train.add_argument("domain", choices=["cacu", "cama", "tea"])
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
train.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default")
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
train.set_defaults(run=lambda args: _train(train, args))
estimate = commands.add_parser("estimate", help="score a cohort build's file with a registered version")
estimate.add_argument("domain", choices=["cacu", "cama", "tea"])
estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
estimate.add_argument("--output", required=True, help="the Parquet file to write")
estimate.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default")
estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate)
run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops")
run.add_argument("domain", choices=["cacu", "cama", "tea"])
run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
run.add_argument("--export", action="store_true", help="export the build to its Parquet file")
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists")
run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version")
run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production")
run.add_argument("--armado", type=int, help="the build's armado_id; the latest by default")
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes")
run.set_defaults(run=lambda args: _run(run, args))
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())