Lesion size extracted from pathology reports; development record route; scenario catalog and background training jobs in governance
This commit is contained in:
@@ -117,6 +117,50 @@ def train_model_version(domain: str, scenario: str):
|
||||
return jsonify({"error": error or "No se pudo entrenar el modelo.", "output": output}), status
|
||||
|
||||
|
||||
@governance_bp.get("/scenarios")
|
||||
def trainable_scenarios():
|
||||
"""The scenarios that can be trained from here, each with its production version if it has one."""
|
||||
from webapi import training_jobs
|
||||
|
||||
result = []
|
||||
for entry in training_jobs.catalog():
|
||||
try:
|
||||
production = str(registry.resolve(entry["domain"], entry["scenario"]).version)
|
||||
except LookupError:
|
||||
production = None
|
||||
result.append({**entry, "produccion": production})
|
||||
return jsonify({"scenarios": result})
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/train-jobs")
|
||||
def start_training_job(domain: str, scenario: str):
|
||||
"""Starts the scenario's training in the background and answers 202 with the job; a job of that scenario that is
|
||||
still running is answered 409 with it. 404 for a scenario that cannot be trained, 503 with no dbt manifest."""
|
||||
from webapi import training_jobs
|
||||
|
||||
if training_jobs.running(domain, scenario) is not None:
|
||||
return jsonify({"error": "Ya hay un entrenamiento en curso para este modelo.",
|
||||
"job": training_jobs.running(domain, scenario)}), 409
|
||||
try:
|
||||
return jsonify({"job": training_jobs.start(domain, scenario)}), 202
|
||||
except RuntimeError as error:
|
||||
return jsonify({"error": str(error)}), 503
|
||||
|
||||
|
||||
@governance_bp.get("/training-jobs")
|
||||
def list_training_jobs():
|
||||
from webapi import training_jobs
|
||||
|
||||
return jsonify({"jobs": training_jobs.jobs()})
|
||||
|
||||
|
||||
@governance_bp.get("/training-jobs/<job_id>")
|
||||
def training_job(job_id: str):
|
||||
from webapi import training_jobs
|
||||
|
||||
return jsonify({"job": training_jobs.get(job_id)})
|
||||
|
||||
|
||||
@governance_bp.patch("/model-versions/<domain>/<scenario>/<version>/reports")
|
||||
def attach_reports(domain: str, scenario: str, version: str):
|
||||
"""MLD-01/01b/03 documents, usually written after training."""
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""What a model's production version found about its cohort: `GET /<domain>/modelo/curvas`.
|
||||
"""What a model's production version found about its cohort: `GET /<domain>/modelo/curvas` and `GET /<domain>/modelo/desarrollo`.
|
||||
|
||||
The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's
|
||||
survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the
|
||||
@@ -32,4 +32,19 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
|
||||
"mlflow_run_id": resolved.run_id},
|
||||
"curvas": json.loads(content)})
|
||||
|
||||
@blueprint.get("/modelo/desarrollo")
|
||||
def development():
|
||||
"""The development stages' tables and figures of the scenario's production version."""
|
||||
from models.io.registry import registry
|
||||
|
||||
try:
|
||||
resolved = registry.resolve(domain, scenario)
|
||||
_, content = registry.artifact(domain, scenario, resolved.version, "analisis/desarrollo.json")
|
||||
except LookupError as error:
|
||||
return jsonify({"error": f"sin desarrollo: {error}"}), 404
|
||||
return jsonify({"simulado": simulated_data(),
|
||||
"modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version),
|
||||
"mlflow_run_id": resolved.run_id},
|
||||
"desarrollo": json.loads(content)})
|
||||
|
||||
return blueprint
|
||||
|
||||
@@ -33,7 +33,7 @@ DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
|
||||
"cama",
|
||||
("biopsia.tipo_histologico", "biopsia.grado_nottingham", "biopsia.receptor_estrogeno",
|
||||
"biopsia.receptor_estrogeno_pct", "biopsia.receptor_progesterona", "biopsia.receptor_progesterona_pct",
|
||||
"biopsia.her2", "biopsia.ki67_pct"),
|
||||
"biopsia.her2", "biopsia.ki67_pct", "biopsia.tamano_tumor_mm"),
|
||||
texto=lambda f: f.bx_pdf_blob,
|
||||
)
|
||||
DE_LA_NOTA = DesdeTexto(
|
||||
|
||||
@@ -42,6 +42,19 @@ def lineas_de_texto(texto: str, nombre: str = "texto") -> list[SegmentLine]:
|
||||
return [SegmentLine(nombre, 1, Line(r, BBox(0, i * alto, 1, (i + 1) * alto))) for i, r in enumerate(renglones)]
|
||||
|
||||
|
||||
def con_renglones_unidos(lineas: list[SegmentLine]) -> list[SegmentLine]:
|
||||
"""The lines and, after them, each pair of consecutive lines of a page joined: a caption that the page wraps ("TAMAÑO
|
||||
DE LA" / "LESIÓN: 25 MM") is whole in one of them. A value found in both counts as found twice, which doesn't change
|
||||
which one wins."""
|
||||
unidas = []
|
||||
for a, b in zip(lineas, lineas[1:]):
|
||||
if a.page_number != b.page_number or a.document != b.document:
|
||||
continue
|
||||
caja = BBox(min(a.line.bbox.x0, b.line.bbox.x0), a.line.bbox.y0, max(a.line.bbox.x1, b.line.bbox.x1), b.line.bbox.y1)
|
||||
unidas.append(SegmentLine(a.document, a.page_number, Line(f"{a.line.text} {b.line.text}", caja), a.ocr or b.ocr))
|
||||
return [*lineas, *unidas]
|
||||
|
||||
|
||||
def lineas_de_pdf(contenido: bytes) -> list[SegmentLine]:
|
||||
"""The text layer of a PDF, without OCR: a load doesn't run OCR, and a scan without text gives no lines."""
|
||||
try:
|
||||
@@ -74,7 +87,7 @@ class DesdeTexto:
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def extraer(contenido: str | bytes) -> dict[str, tuple]:
|
||||
lineas = lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido)
|
||||
lineas = con_renglones_unidos(lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido))
|
||||
leidos = extractor.extract(lineas)
|
||||
return {r: _valor_y_fuente(leidos.get(r), leidos.get(r + SUFIJO_DE_TEXTO), tipos[r]) for r in tipos}
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Model training started from governance: the scenarios that can be trained and the jobs that train them.
|
||||
|
||||
A job is the same pipeline the `entrenar` compose profile runs (`models run <domain> <scenario> --export --source dbt
|
||||
--environment prod --train --promote`), in a detached process that the request does not wait for. Its state lives in files
|
||||
under `INDICADORES_DIR/entrenamientos/<id>/` (`job.json`, `stdout.log`, `stderr.log` and `exit` once it ends), so any
|
||||
worker of the server answers for any job and a restart does not lose them. A job whose process is gone without an exit
|
||||
code is `interrumpido`.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tomllib
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
TAIL_CHARS = 4000
|
||||
# A domain whose scenarios train on a reference cohort and not on a dbt cohort build.
|
||||
OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (requiere el clúster o --reference-dir)."}
|
||||
|
||||
|
||||
def _models_root() -> Path:
|
||||
import models
|
||||
|
||||
return Path(models.__file__).parent
|
||||
|
||||
|
||||
def catalog() -> list[dict]:
|
||||
"""The scenarios that have a `model.toml` of their own, with the cohort each trains on."""
|
||||
found = []
|
||||
for path in sorted(_models_root().glob("*/*/model.toml")):
|
||||
spec = tomllib.loads(path.read_text(encoding="utf-8"))
|
||||
domain = spec.get("domain")
|
||||
if domain is None:
|
||||
continue
|
||||
own = domain in OWN_STEPS
|
||||
if not own and "scenario" not in spec:
|
||||
continue
|
||||
found.append({
|
||||
"domain": domain, "scenario": spec.get("scenario", path.parent.name), "cohort": spec.get("cohort"),
|
||||
"outcome": spec.get("outcome"), "description": " ".join(str(spec.get("description", OWN_STEPS.get(domain, ""))).split()),
|
||||
"kind": "referencia" if own else "cohorte",
|
||||
})
|
||||
return found
|
||||
|
||||
|
||||
def _base() -> Path:
|
||||
return Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "entrenamientos"
|
||||
|
||||
|
||||
def _command(domain: str, scenario: str) -> list[str]:
|
||||
argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"]
|
||||
if domain not in OWN_STEPS:
|
||||
argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]]
|
||||
return argv
|
||||
|
||||
|
||||
def _alive(pid: int) -> bool:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def _tail(path: Path) -> str:
|
||||
return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else ""
|
||||
|
||||
|
||||
def _state(folder: Path) -> dict:
|
||||
job = json.loads((folder / "job.json").read_text(encoding="utf-8"))
|
||||
out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log")
|
||||
exit_file = folder / "exit"
|
||||
if exit_file.exists():
|
||||
code = int(exit_file.read_text().strip() or 1)
|
||||
state = ("completado" if code == 0 else "entrenado_sin_promover" if "not promoted, missing" in err else "fallido")
|
||||
elif _alive(job["pid"]):
|
||||
code, state = None, "en_curso"
|
||||
else:
|
||||
code, state = None, "interrumpido"
|
||||
return {**job, "estado": state, "codigo": code, "salida": out, "error": err}
|
||||
|
||||
|
||||
def running(domain: str, scenario: str) -> dict | None:
|
||||
return next((j for j in jobs() if j["estado"] == "en_curso" and (j["domain"], j["scenario"]) == (domain, scenario)), None)
|
||||
|
||||
|
||||
def start(domain: str, scenario: str) -> dict:
|
||||
"""Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest."""
|
||||
if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}:
|
||||
raise LookupError(f"no such model: {domain}/{scenario}")
|
||||
if domain not in OWN_STEPS and not os.environ.get("DBT_MANIFEST"):
|
||||
raise RuntimeError("No hay un manifest de dbt configurado.")
|
||||
job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}"
|
||||
folder = _base() / job_id
|
||||
folder.mkdir(parents=True)
|
||||
shell = '{ "$@" > stdout.log 2> stderr.log; echo $? > exit; }'
|
||||
process = subprocess.Popen(["sh", "-c", shell, "sh", *_command(domain, scenario)], cwd=folder, start_new_session=True,
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
job = {"id": job_id, "domain": domain, "scenario": scenario, "pid": process.pid,
|
||||
"iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")}
|
||||
(folder / "job.json").write_text(json.dumps(job), encoding="utf-8")
|
||||
return _state(folder)
|
||||
|
||||
|
||||
def get(job_id: str) -> dict:
|
||||
folder = _base() / job_id
|
||||
if "/" in job_id or not (folder / "job.json").exists():
|
||||
raise LookupError(f"no such training job: {job_id}")
|
||||
return _state(folder)
|
||||
|
||||
|
||||
def jobs(limit: int = 50) -> list[dict]:
|
||||
"""The latest jobs, newest first."""
|
||||
folders = sorted((p for p in _base().glob("*") if (p / "job.json").exists()), reverse=True) if _base().exists() else []
|
||||
return [_state(p) for p in folders[:limit]]
|
||||
Reference in New Issue
Block a user