Files
WebApi/webapi/model_analysis.py
T
2026-11-21 13:03:19 -06:00

111 lines
5.0 KiB
Python

"""What a model's production version found about its cohort: `GET /<domain>/modelo/curvas`, `GET /<domain>/modelo/desarrollo` and, over the data ingested so far, `POST /<domain>/modelo/curvas/consulta`.
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
cohort, not any patient. The answer names the version they come from, and carries `simulado: true` in DEV, where the
data are simulated. 404 while the scenario has no version in production, or its version has no such record.
"""
import json
from collections import OrderedDict
from threading import Lock
from flask import Blueprint, jsonify, request
from webapi.fhir.common import simulated_data
_LIVE: dict = {}
_ANSWERS: OrderedDict = OrderedDict()
_LOCK = Lock()
MAX_ANSWERS = 64
def _live_context(domain: str, scenario: str):
"""`(scenario, fitted model, labelled members, version)`: the production version and the cohort build the cycle made last,
kept until either changes. `LookupError` while there is no version or no build."""
import importlib
import mlflow.sklearn
from models.cama.survival import live
from models.dags.training import Scenario
from models.io.registry import registry
from models.io.storage import KitBuild
resolved = registry.resolve(domain, scenario)
spec = Scenario.load(domain, scenario)
build_id = importlib.import_module(f"persistance.{domain}").cohort_repository.latest_build(spec.cohort)
if build_id is None:
raise LookupError(f"({domain}, {scenario}) has no cohort build yet")
key = (resolved.version, build_id)
with _LOCK:
if _LIVE.get("key") != key:
build = KitBuild(domain, build_id)
model = live.rehydrate(mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1])
_LIVE.update(key=key, value=(spec, model, live.members(spec, build.frame(), build.lineage()), resolved.version))
_ANSWERS.clear()
return _LIVE["value"]
def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
"""The blueprint of one scenario, to register with `url_prefix="/<domain>"`."""
blueprint = Blueprint(f"model_analysis_{domain}_{scenario}", __name__)
@blueprint.get("/modelo/curvas")
def curves():
"""The curves and points 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/curvas.json")
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
return jsonify({"simulado": simulated_data(),
"modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version),
"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)})
@blueprint.post("/modelo/curvas/consulta")
def live_curves():
"""The figure's record for the selection in the body (`{filtros, periodo}`), scored with the production version over
the data ingested so far. 422 with the reason when the selection is too small or invalid."""
from models.cama.survival import live
query = request.get_json(silent=True) or {}
try:
spec, model, labelled, version = _live_context(domain, scenario)
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
key = json.dumps({"v": version, "q": query}, sort_keys=True, default=str)
with _LOCK:
record = _ANSWERS.get(key)
if record is None:
try:
record = live.curves(spec, model, labelled, query)
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
with _LOCK:
_ANSWERS[key] = record
while len(_ANSWERS) > MAX_ANSWERS:
_ANSWERS.popitem(last=False)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record})
return blueprint