diff --git a/pyproject.toml b/pyproject.toml index c336e85..f1ce319 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ requires-python = ">=3.12" dependencies = [ "flask>=3.0", "persistance", - "models[notebooks,survival-curves]", + "models[notebooks,survival-curves,seer-survival]", "extraction", "apache-hamilton>=1.90", "pandas>=2.0", diff --git a/tests/test_extracted_results.py b/tests/test_extracted_results.py index 440f42e..69a3479 100644 --- a/tests/test_extracted_results.py +++ b/tests/test_extracted_results.py @@ -121,14 +121,14 @@ def test_a_stage_is_found_in_a_note_without_a_caption(): def test_a_pathology_pdf_s_text_layer_gives_its_results(): - """Pins down: a PDF's text layer is read without OCR and every result on it comes out. Fails if bytes stop + """Pins down: a PDF's text layer is read without OCR and every result on it comes out (the size, which the fixture report does not state, as nothing). Fails if bytes stop going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor.""" leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1]))) assert {r: v for r, (v, _) in leido.items()} == { "biopsia.tipo_histologico": "8500/3", "biopsia.grado_nottingham": "G2", "biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0, "biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0, - "biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, + "biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, "biopsia.tamano_tumor_mm": None, } diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 2001b6e..6538a51 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -1,4 +1,4 @@ -"""What this module covers: `GET /cama/modelo/curvas` (`webapi.model_analysis`): it serves the production version's +"""What this module covers: `GET /cama/modelo/curvas` and `GET /cama/modelo/desarrollo` (`webapi.model_analysis`): they serve the production version's population record with the version it comes from, and answers 404 while there is no version in production or the version has no such record. @@ -62,3 +62,18 @@ def test_without_a_version_in_production_or_a_record_it_is_a_404(client): assert missing_record.status_code == 404 and "curvas.json" in missing_record.get_json()["error"] assert no_version.status_code == 404 and "producción" in no_version.get_json()["error"] + + +def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none(client): + """Pins down: `GET /cama/modelo/desarrollo` returns `analisis/desarrollo.json` with the version it comes from, and a + version trained before that record existed is a 404, not an empty page. Fails if the route reads another file or + answers 200 without a record.""" + record = {"tablas": {"or_lr_balanceada": [{"variable": "Grado"}]}, "figuras": {}} + client.holder.files["analisis/desarrollo.json"] = json.dumps(record).encode() + found = client.get("/cama/modelo/desarrollo") + del client.holder.files["analisis/desarrollo.json"] + missing = client.get("/cama/modelo/desarrollo") + + assert found.status_code == 200 and found.get_json()["desarrollo"] == record + assert found.get_json()["modelo"]["version"] == "3" + assert missing.status_code == 404 and "desarrollo.json" in missing.get_json()["error"] diff --git a/tests/test_pathology_report_wording.py b/tests/test_pathology_report_wording.py index b73594d..919b8cb 100644 --- a/tests/test_pathology_report_wording.py +++ b/tests/test_pathology_report_wording.py @@ -50,3 +50,14 @@ def test_the_rarer_invasive_types_are_read_as_their_code(tipo, codigo): """Pins down: a mucinous, tubular or mixed ductal and lobular carcinoma is read as its ICD-O-3 code rather than left unresolved or taken as ductal or lobular. Fails if their names leave the catalog's aliases.""" assert _leer(f"Diagnóstico: BIOPSIA: {tipo} (8480/3).")["biopsia.tipo_histologico"][0] == codigo + + +@pytest.mark.parametrize("texto", [ + "GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO DE LA LESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.", + "GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO DE LA\nLESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.", + "GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO\nDE LA LESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.", +]) +def test_the_lesion_size_is_read_even_when_the_page_wraps_its_caption(texto): + """Pins down: "TAMAÑO DE LA LESIÓN: 25 MM" gives 25 whether it is on one line or the page wraps it between words, + because the extractor also sees each pair of adjacent lines joined. Fails if the joined lines stop being offered.""" + assert float(_leer(texto)["biopsia.tamano_tumor_mm"][0]) == 25.0 diff --git a/tests/test_training_jobs.py b/tests/test_training_jobs.py new file mode 100644 index 0000000..50728ba --- /dev/null +++ b/tests/test_training_jobs.py @@ -0,0 +1,103 @@ +"""What this module covers: the scenarios governance can train and the background training jobs (`webapi.training_jobs` +and their routes in `webapi.blueprints.governance`): the catalog, a job's states (running, completed, failed, trained but +not promoted, interrupted), and the refusal to start a second job of a scenario that is running. + +Fixtures: `app_client`, the governance blueprint on a bare Flask app with `INDICADORES_DIR` in a temporary folder and the +job's command replaced by a Python one-liner the test chooses, so no model is trained. `esperar` waits for a job to leave +`en_curso`. +""" + +import sys +import time + +import pytest +from flask import Flask + +from webapi import training_jobs +from webapi.blueprints.governance import governance_bp + + +@pytest.fixture +def app_client(tmp_path, monkeypatch): + monkeypatch.setenv("INDICADORES_DIR", str(tmp_path)) + monkeypatch.setenv("DBT_MANIFEST", str(tmp_path / "manifest.json")) + app = Flask(__name__) + app.register_blueprint(governance_bp, url_prefix="/governance") + with app.test_client() as client: + yield client + + +def _command_that(code: str): + return lambda domain, scenario: [sys.executable, "-c", code] + + +def esperar(client, job_id, timeout=20): + deadline = time.time() + timeout + while time.time() < deadline: + job = client.get(f"/governance/training-jobs/{job_id}").get_json()["job"] + if job["estado"] != "en_curso": + return job + time.sleep(0.1) + raise AssertionError("the job did not finish") + + +def test_the_catalog_lists_the_trainable_scenarios_and_not_the_pipeline_settings(): + """Pins down: every scenario with its own `model.toml` and a cohort is listed (CaCu, CaMa), TEA's EEG is listed as + trained on its reference, and the SEER pipeline's settings file is not a scenario. Fails if a scenario stops being + discoverable or a settings file starts showing as one.""" + entries = {(s["domain"], s["scenario"]): s for s in training_jobs.catalog()} + + assert ("cama", "survival") in entries and ("cacu", "cin2_logistic") in entries + assert entries[("tea", "eeg")]["kind"] == "referencia" and entries[("cama", "survival")]["kind"] == "cohorte" + assert ("cama", "seer_survival") not in entries + + +@pytest.mark.parametrize("code,estado", [ + ("print('trained: version 4')", "completado"), + ("import sys; print('boom', file=sys.stderr); sys.exit(1)", "fallido"), + ("import sys; print('version 4 not promoted, missing MLD-01', file=sys.stderr); sys.exit(1)", "entrenado_sin_promover"), +]) +def test_a_job_ends_as_completed_failed_or_trained_without_promotion(app_client, monkeypatch, code, estado): + """Pins down: the job's state comes from its exit code and its error output, and carries both outputs. Fails if a + failure is shown as done, or a version that only lacks its reports is shown as failed.""" + monkeypatch.setattr(training_jobs, "_command", _command_that(code)) + + started = app_client.post("/governance/model-versions/cama/survival/train-jobs") + job = esperar(app_client, started.get_json()["job"]["id"]) + + assert started.status_code == 202 and job["estado"] == estado + assert ("trained" in job["salida"]) or ("boom" in job["error"]) or ("not promoted" in job["error"]) + + +def test_a_second_job_of_a_running_scenario_is_refused_with_the_running_one(app_client, monkeypatch): + """Pins down: while a scenario's job runs, starting another answers 409 with that job, and another scenario still + starts. Fails if two trainings of one model can run at once, which would register the same version twice.""" + monkeypatch.setattr(training_jobs, "_command", _command_that("import time; time.sleep(3)")) + first = app_client.post("/governance/model-versions/cama/survival/train-jobs") + again = app_client.post("/governance/model-versions/cama/survival/train-jobs") + other = app_client.post("/governance/model-versions/cacu/cin2_logistic/train-jobs") + + assert first.status_code == 202 and again.status_code == 409 + assert again.get_json()["job"]["id"] == first.get_json()["job"]["id"] + assert other.status_code == 202 + + +def test_a_job_whose_process_is_gone_without_an_exit_code_is_interrupted(app_client, tmp_path): + """Pins down: a job file with no exit file and a dead process reads `interrumpido`, not `en_curso` forever. Fails if + a killed worker leaves its job running in the list.""" + folder = tmp_path / "entrenamientos" / "20260101T000000-aaaaaa" + folder.mkdir(parents=True) + (folder / "job.json").write_text('{"id": "20260101T000000-aaaaaa", "domain": "cama", "scenario": "survival", ' + '"pid": 2147483646, "iniciado": "2026-01-01T00:00:00+00:00"}') + + assert app_client.get("/governance/training-jobs/20260101T000000-aaaaaa").get_json()["job"]["estado"] == "interrumpido" + assert [j["id"] for j in app_client.get("/governance/training-jobs").get_json()["jobs"]] == ["20260101T000000-aaaaaa"] + + +def test_an_unknown_scenario_or_job_is_a_404_and_no_manifest_is_a_503(app_client, monkeypatch): + """Pins down: starting an unknown scenario, or reading an unknown job, is a 404; a cohort scenario with no dbt + manifest configured is a 503 and starts nothing. Fails if either becomes a 500 or starts a process.""" + assert app_client.post("/governance/model-versions/cama/nope/train-jobs").status_code == 404 + assert app_client.get("/governance/training-jobs/nada").status_code == 404 + monkeypatch.delenv("DBT_MANIFEST") + assert app_client.post("/governance/model-versions/cama/survival/train-jobs").status_code == 503 diff --git a/uv.lock b/uv.lock index 451ff3f..729b021 100644 --- a/uv.lock +++ b/uv.lock @@ -992,6 +992,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/86/32914542064b8aee77ac48142f8a1955df78da4eb905dd41697d26941d21/fhir_resources-8.3.0-py2.py3-none-any.whl", hash = "sha256:151e6c9b4336e36383cc2aaf2067a6f112a420fce1c7bd289182e55dd950871b", size = 2288069, upload-time = "2026-07-03T15:23:51.97Z" }, ] +[[package]] +name = "filelock" +version = "4.2.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/52/aa/8ccff8da9a27e089727fcffd3c5b61708383217e47eb1e1b8af37b1dd166/filelock-4.2.12.tar.gz", hash = "sha256:7e7da24d3ac39268b0f156e56870001de44886318f092f9d851e692f7114d6dd", size = 680837, upload-time = "2026-11-18T01:20:03.951Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8a/c9/eb6b6528c7edb958d4c24ac47a8b94113d9de36e4cfc6eecd599b1a4f349/filelock-4.2.12-py3-none-any.whl", hash = "sha256:21decfec02f116ed4c954433cdb31f28c3b346b784543177b6d7059da2702ee9", size = 222442, upload-time = "2026-11-18T01:20:02.439Z" }, +] + [[package]] name = "flask" version = "3.1.3" @@ -1354,6 +1363,69 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] +[[package]] +name = "hf-xet" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/18/db7ebc58820d82fd5506aa405a75611e7a4398f573dc436f7387603bf63d/hf_xet-1.8.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56", size = 3883873, upload-time = "2026-10-30T10:04:03.24Z" }, + { url = "https://files.pythonhosted.org/packages/37/bd/6c9ed89aafbeb4a7ee0d76d6b7b9365221e3e7ee47958aeecdc2c60a0511/hf_xet-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740", size = 3594510, upload-time = "2026-10-30T10:04:05.364Z" }, + { url = "https://files.pythonhosted.org/packages/0e/1f/c26154b3a053b637c0984db0db9fdacbbfc257bdc2e95e9bc0782b745b0c/hf_xet-1.8.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba", size = 4281780, upload-time = "2026-10-30T10:04:07.35Z" }, + { url = "https://files.pythonhosted.org/packages/e3/9e/d84c31f8e3acc286c9c6a4fd85f7f332e3db40636595f0de5ad776b69beb/hf_xet-1.8.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c", size = 4060223, upload-time = "2026-10-30T10:04:09.029Z" }, + { url = "https://files.pythonhosted.org/packages/a4/70/c142e4ad8a679ff6ffe40964a9d017fa0211aabca9ca4d3d547c3a2fc165/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330", size = 4263619, upload-time = "2026-10-30T10:04:11.085Z" }, + { url = "https://files.pythonhosted.org/packages/9d/08/92e03e3ac4eaeab046359093c447c03c8c30b577c2b1e1687dc747654f1c/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01", size = 4493381, upload-time = "2026-10-30T10:04:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/61/63/a512b2906d0f92b5d325f58169d1fd8c3202a9ee61bd8405ec78c67e5315/hf_xet-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa", size = 3901344, upload-time = "2026-10-30T10:04:15.051Z" }, + { url = "https://files.pythonhosted.org/packages/2d/5e/b453f82690cb36f176c4b01e64d6d32757fabbf34dbb9bcbdf747e429a79/hf_xet-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b", size = 3731681, upload-time = "2026-10-30T10:04:16.855Z" }, + { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" }, + { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" }, + { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" }, +] + +[[package]] +name = "httpcore2" +version = "2.16.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h11" }, + { name = "truststore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" }, +] + +[[package]] +name = "httpx2" +version = "2.16.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio", marker = "sys_platform != 'emscripten'" }, + { name = "httpcore2", marker = "sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" }, + { name = "idna" }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, +] + [[package]] name = "huey" version = "3.4.0" @@ -1363,6 +1435,26 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/57/31/cee585bd4d1e39947a426a6736f4e17d22b454952370fb9cf48eb3103085/huey-3.4.0-py3-none-any.whl", hash = "sha256:d0580762397744026f83baae5f2b97a62474a62b8565ac75bbafefe72f9c784f", size = 136493, upload-time = "2026-09-04T02:04:32.848Z" }, ] +[[package]] +name = "huggingface-hub" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'ARM64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "httpx2" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b5/3b/2fcef1eabe52aec90fc8cd253cc154da1d02a446d7bbcdec59b4a51d4be7/huggingface_hub-2.4.0.tar.gz", hash = "sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188", size = 1066194, upload-time = "2026-10-29T15:30:12.321Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/55/ff47f1b082ecf5f43f4bc1e3b932d68eead171dabbbd1a92666c686301d7/huggingface_hub-2.4.0-py3-none-any.whl", hash = "sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801", size = 857021, upload-time = "2026-10-29T15:30:10.421Z" }, +] + [[package]] name = "idna" version = "3.20" @@ -2068,6 +2160,14 @@ notebooks = [ { name = "nbclient" }, { name = "nbconvert" }, ] +seer-survival = [ + { name = "matplotlib" }, + { name = "mpmath" }, + { name = "networkx" }, + { name = "pgmpy" }, + { name = "scipy" }, + { name = "statsmodels" }, +] survival-curves = [ { name = "mpmath" }, { name = "scipy" }, @@ -2425,6 +2525,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/09/ed/559d2915dce85794bc0c36064043da170da50cd98746dcbddd85d5932017/nest_asyncio2-1.7.4-py3-none-any.whl", hash = "sha256:86e77b52c3d1496b294af3c944b44213b9b82a12a5ee590c0acc4ca4692ef6c7", size = 8543, upload-time = "2026-10-07T22:31:49.245Z" }, ] +[[package]] +name = "networkx" +version = "3.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205, upload-time = "2026-09-21T16:45:14.609Z" }, +] + [[package]] name = "numba" version = "0.68.1" @@ -2596,6 +2705,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, ] +[[package]] +name = "opt-einsum" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/b9/2ac072041e899a52f20cf9510850ff58295003aa75525e58343591b0cbfb/opt_einsum-3.4.0.tar.gz", hash = "sha256:96ca72f1b886d148241348783498194c577fa30a8faac108586b14f1ba4473ac", size = 63004, upload-time = "2024-09-26T14:33:24.483Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932, upload-time = "2024-09-26T14:33:23.039Z" }, +] + [[package]] name = "packaging" version = "26.3" @@ -2795,6 +2913,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" }, ] +[[package]] +name = "pgmpy" +version = "1.1.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, + { name = "joblib" }, + { name = "networkx" }, + { name = "numpy" }, + { name = "opt-einsum" }, + { name = "pandas" }, + { name = "pyparsing" }, + { name = "scikit-base" }, + { name = "scikit-learn" }, + { name = "scipy" }, + { name = "statsmodels" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/9a/b94ccd1d6cbf2982937c26e54e887b47ee10f848ad53c4427965578a358d/pgmpy-1.1.2.tar.gz", hash = "sha256:a62a89352f139a5d459839e54e6bfa202a7d8749e6dc6d7ceec088a71529af45", size = 2183113, upload-time = "2026-04-30T11:34:49.538Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c6/5d/d03634ed296986abad834a69b0df21510cc9b6c40fb8afaed5df1c4b6074/pgmpy-1.1.2-py3-none-any.whl", hash = "sha256:e55c78763a4a45dd644a13b250cea86af0c7e08590cf35de489624f34a4d9a0b", size = 2446383, upload-time = "2026-04-30T11:34:47.189Z" }, +] + [[package]] name = "pillow" version = "12.3.0" @@ -3858,6 +3999,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/55/4b2fa381a583760aea5c92841e4e928a358e1c6511b129219e9c2826a226/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37", size = 346877, upload-time = "2026-10-04T16:32:34.061Z" }, ] +[[package]] +name = "scikit-base" +version = "1.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/e9/287707e71be93558076d873f92444fa788c1a11c259982a1967ad2071b0e/scikit_base-1.2.1.tar.gz", hash = "sha256:6cccfab1cf51e36141b731fe3248bd3c1a55361e965ddc7457be75ad8a9803eb", size = 136836, upload-time = "2026-11-08T20:24:26.859Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/b4/21adac81fbb522bdbb74c4809c7ea06fbde847a24c54b68dfed1519ff3dc/scikit_base-1.2.1-py3-none-any.whl", hash = "sha256:8695538dcf61c5439752b56baeca9d4ce52de012ddc4cee50ee67c910a9b5fb9", size = 163886, upload-time = "2026-11-08T20:24:25.324Z" }, +] + [[package]] name = "scikit-learn" version = "1.9.1" @@ -4356,6 +4506,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" }, ] +[[package]] +name = "truststore" +version = "0.10.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" }, +] + [[package]] name = "typeguard" version = "4.6.0" @@ -4535,7 +4694,7 @@ dependencies = [ { name = "flask" }, { name = "flask-cors" }, { name = "gunicorn" }, - { name = "models", extra = ["notebooks", "survival-curves"] }, + { name = "models", extra = ["notebooks", "seer-survival", "survival-curves"] }, { name = "openpyxl" }, { name = "pandas" }, { name = "pdfplumber" }, @@ -4571,7 +4730,7 @@ requires-dist = [ { name = "flask", specifier = ">=3.0" }, { name = "flask-cors", specifier = ">=4.0" }, { name = "gunicorn", specifier = ">=23.0" }, - { name = "models", extras = ["notebooks", "survival-curves"], editable = "../models" }, + { name = "models", extras = ["notebooks", "survival-curves", "seer-survival"], editable = "../models" }, { name = "openpyxl", specifier = ">=3.1" }, { name = "pandas", specifier = ">=2.0" }, { name = "pdfplumber", specifier = ">=0.11" }, diff --git a/webapi/blueprints/governance.py b/webapi/blueprints/governance.py index 68f91d7..dd7c11d 100644 --- a/webapi/blueprints/governance.py +++ b/webapi/blueprints/governance.py @@ -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///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/") +def training_job(job_id: str): + from webapi import training_jobs + + return jsonify({"job": training_jobs.get(job_id)}) + + @governance_bp.patch("/model-versions////reports") def attach_reports(domain: str, scenario: str, version: str): """MLD-01/01b/03 documents, usually written after training.""" diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 95f9359..697eb6c 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -1,4 +1,4 @@ -"""What a model's production version found about its cohort: `GET //modelo/curvas`. +"""What a model's production version found about its cohort: `GET //modelo/curvas` and `GET //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 diff --git a/webapi/orchestration/silver/cama.py b/webapi/orchestration/silver/cama.py index 4716e56..9332bb4 100644 --- a/webapi/orchestration/silver/cama.py +++ b/webapi/orchestration/silver/cama.py @@ -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( diff --git a/webapi/orchestration/silver/extracted.py b/webapi/orchestration/silver/extracted.py index dee3604..7ac8666 100644 --- a/webapi/orchestration/silver/extracted.py +++ b/webapi/orchestration/silver/extracted.py @@ -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} diff --git a/webapi/training_jobs.py b/webapi/training_jobs.py new file mode 100644 index 0000000..46a654a --- /dev/null +++ b/webapi/training_jobs.py @@ -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 --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//` (`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]]