6fded849a2adb05702a9fcd3008486ba03446356
models
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.
| Módulo | Qué hace |
|---|---|
__main__.py |
La línea de comandos: python -m models <comando>. Cada área agrega ahí sus subcomandos. |
io/contracts.py |
The shapes of the data: a cohort build's file (COHORT_SCHEMA), a cohort's rules (ExclusionRule, CohortQueries, BuiltCohort), an estimate's output (ESTIMATE_COLUMNS) and the risk contract (Risk, Provenance, RiskEstimator, which still takes the wide frame). |
io/storage.py |
Where data lives and how it's read and written: cohort and estimate Parquet files (read_cohort, write_once, read_metadata) and their hashes (file_sha256, table_sha256, cohort_reference), dbt's manifest (read_queries), Persistance repositories, the risk batches, and the cohort sources a model trains and estimates on: KitBuild, a kit build read now from the domain's database (nothing written), or CohortFile, an exported file, behind one contract (frame, lineage, reference). |
io/lineage.py |
What each output came from, in one vocabulary: registered names, tag keys, the code's version (the installed models package, code_version), a model's hash (model_sha), and matches, the one rule for "already done". |
io/tracking.py |
TrainingRun: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the models version, and log_model with its modelo_sha (a scikit-learn estimator, served through predict_proba, or a pyfunc). In PROD, only models whose class lives in a module. log_routine records what each routine around training did, as it runs (ML-01a): one JSON per kind in ROUTINE_KINDS (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under rutinas/, counts and settings only. run_files/run_file list and download a run's files (a folder as a zip). inspect_onnx_metadata checks an ONNX checkpoint before it's logged. |
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 ML-01a/ML-01b: las cinco rutinas y el modelo, escritos por la propia corrida) y el alias produccion. artifacts/artifact listan y descargan los archivos de una versión (ML-01b). Registers a finished run as a version (register_run) and sets its description. PredictionService stores each single prediction with the version in production (MLD-4/5, EL-04b). |
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. |
steps/cohort.py, steps/cohort_file.py |
The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. |
pipelines/cohort_build.py |
Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph] shows the attrition or the Mermaid diagram; it stores nothing. |
pipelines/export_cohort.py |
Exports a build to its Parquet file. python -m models cohorts export cacu cohorte_vigilancia [--build N] writes the kit's build once; --source dbt --manifest target/manifest.json builds it from dbt's rules into dbt/<n>.parquet and writes only when its rows change. The timeline comes from dbt's view <domain>_linea_de_tiempo. |
cohorts list, cohorts show |
python -m models cohorts list cacu cohorte_vigilancia [--source kit|dbt] lists the builds of both sources, newest first, and whether each has its file (dbt's from their files alone); cohorts show … --source kit|dbt --build N prints one build's file, hash, parameters, rules and attrition as JSON (io/storage.py: list_builds, describe_build). |
steps/risks.py, pipelines/store_risks.py |
Stores an estimate file as a batch of risks in the domain's database (evaluacion_riesgo_lote, evaluacion_riesgo), through cohort_repository: one preliminary risk per member and horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (armado_id), so estimates of dbt builds are refused. python -m models store cacu cin2_logistic --input file.parquet, or run … --estimate --store --output file.parquet. |
reports/ (rendering.py, eda.py) |
A model's exploratory notebook as an MLflow report: python -m models report eda cacu cin2_logistic [--source kit|dbt] [--build N] [--notebook path] [--kernel name] runs <scenario>/notebooks/01_eda.ipynb on the build's file (COHORT_FILE), renders it to one HTML page, and logs the page and the notebook without outputs as a run of the experiment <domain>-<scenario>/<notebook>, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Renderers are classes in rendering.py (RENDERERS, register_renderer): quarto (QUARTO_BIN, and a Python with Jupyter in QUARTO_PYTHON) and jupyter (nbclient + nbconvert, the notebooks extra). NOTEBOOK_RENDERER picks one; otherwise Quarto if installed, else Jupyter. NOTEBOOK_CELL_TIMEOUT limits each cell (1800 s). |
pipelines/experiment.py |
A notebook uploaded to the platform, run on one exported cohort build as a run of <domain>-<scenario>/experimentos: the notebook, its page, what was imported from it (importado.json), error.txt if it failed, and tags for the notebook's hash, the build's file, the version, the code and where it ran (sandbox). start and execute are separate so the WebApi runs it in the background. |
io/notebook_jobs.py |
Where the notebook runs: a job folder with the notebook, a copy of the build's file and of the chosen model, and an MLflow store of its own; every database URL is an empty in-memory one. Executors: contenedor leaves the job in NOTEBOOK_JOBS_DIR for the runner (python -m models notebooks serve, the notebooks container: no network, read-only, unprivileged, only that folder); local runs it in this process, unisolated, for development. |
io/notebook_import.py |
Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed modelo_sha, never with an alias; refuses symbolic links and anything outside the job folder. |
io/extraction_ranker.py |
Each domain's document extraction ranker (extraction.nlp.ranking.LearnedRanker) as the model <domain>-extraccion: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (ranker/ranker.json) and its saved model. current gives the version in production, otherwise the latest; EXTRACTION_RANKER=produccion only takes production, ninguno turns it off. Weights over how candidates were found and counts only, never document text. |
notebook.py |
What a notebook uses inside: experiment() gives the build's rows (cohort()), its metadata, the chosen version loaded (model()), a DEV TrainingRun linked to the build (training_run()) and register(run). |
io/adapters.py |
Hamilton's boundary with storage and MLflow, attached by the driver with with_materializers: the loaders cohort_source (which refuses a build with no rows or with a member, a date or an event missing: MODEL_COHORT, pandera) and cohort_source_lineage (any source) and the saver registered_model, which logs a scenario's fitted_model in the open TrainingRun, records its metrics (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. |
annotations.py |
Validators a dataflow puts on its nodes, with no I/O: @checked_frame(schema), a pandera check whose failure names columns and counts, never values. |
dags/training.py, dags/estimation.py |
Training and estimating any scenario: Scenario reads model.toml (its modules, the graph's nodes, and [config]); the driver is with_modules(*modules) with the config, a source's loaders and the saver; find_trained (same source reference, models version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's predict_proba on the source's frame and writes one row per member and horizon. python -m models train|estimate|run … [--read db|file]: a kit build is read from the database by default. |
steps/model_fitting.py |
The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit, its metrics and the routine records every classifier shares (sampling, analytic_method, class_balance, output_confidence), gathered by routines with the scenario's missing_data (ML-01a). |
cacu/cin2_logistic/ |
CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (horizons_years, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. model.toml (names, modules: its model.py and steps/model_fitting.py, and [config]) and model.py (the dataflow to labelled_members, fitted_model: a scikit-learn Pipeline that takes the long frame, and its missing_data routine record). Training records its five routines. Train with `python -m models train cacu cin2_logistic [--source kit |
cacu/cin2_pim/ |
CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. PrevalenceIncidenceMixture, a scikit-learn estimator (logistic prevalence, Weibull incidence, likelihood.py), fitted to each member's code and interval; the clinical settings (windows, known-negative results) in model.toml. Its dataflow records its own five routines. No correction of verification bias, no clinical validation. Same commands as cin2_logistic. |
cacu/, cama/, tea/ |
Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en <escenario>/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). |
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
guardan sus artefactos.
uv run pytest -q
Description
Languages
Python
100%