models train: train a model from the command line

This commit is contained in:
2026-11-04 23:36:46 -06:00
parent 37fb292a4f
commit 0fdab3651c
5 changed files with 130 additions and 26 deletions
+2 -19
View File
@@ -13,7 +13,6 @@ repository, so it needs neither dbt nor write access. In a read-only folder, wit
"""
import argparse
import os
import sys
import tempfile
from collections.abc import Callable, Iterable
@@ -28,10 +27,9 @@ from persistance.aristas.oro import CohortBuild, CohortMember
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
from persistance.settings import settings
from sqlalchemy import column, select, table
from sqlalchemy.engine import make_url
from sqlalchemy.exc import DBAPIError
from models.io.cohorts import SCHEMA, cohort_lineage
from models.io.cohorts import SCHEMA, cohort_lineage, cohort_path, cohorts_root
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
@@ -40,21 +38,6 @@ class TimelineViewError(RuntimeError):
"""dbt's timeline view can't be read."""
def cohorts_root(database_url: str) -> Path:
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
if configured := os.environ.get("COHORTS_DIR"):
return Path(configured)
url = make_url(database_url)
if url.get_backend_name() != "sqlite" or not url.database:
raise ValueError("this database has no data folder: set COHORTS_DIR")
return Path(url.database.removeprefix("file:")).parent / "cohorts"
def cohort_file(build: CohortBuild, root: Path) -> Path:
domain, cohort = build.url.split("/", 1)
return root / domain / cohort / f"{build.armado_id}.parquet"
def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]:
"""Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`."""
name = f"{domain}_linea_de_tiempo"
@@ -107,7 +90,7 @@ def write_once(table: pa.Table, path: Path) -> None:
def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) -> tuple[Path, str]:
"""The build's file: reused if it's already there and belongs to the build, written once if not."""
path = cohort_file(build, root)
path = cohort_path(root, build.url, build.armado_id)
if path.exists():
lineage = cohort_lineage(path)
if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros):