Live models: the labelled members are saved once per build and version, prepared by the indicators cycle and loaded by each API worker as it starts
This commit is contained in:
@@ -7,7 +7,10 @@ data are simulated. 404 while the scenario has no version in production, or its
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
@@ -19,6 +22,40 @@ _LIVE: dict = {}
|
||||
_ANSWERS: OrderedDict = OrderedDict()
|
||||
_LOCK = Lock()
|
||||
MAX_ANSWERS = 64
|
||||
# The scenarios whose members are scored over the data ingested so far, by domain.
|
||||
LIVE_SCENARIOS = {"cama": ("survival",)}
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _members_path(domain: str, scenario: str, version: str, build_id: int) -> Path:
|
||||
folder = Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "modelos"
|
||||
return folder / f"{domain}-{scenario}-v{version}-armado{build_id}.parquet"
|
||||
|
||||
|
||||
def _members(spec, domain: str, scenario: str, version: str, build_id: int):
|
||||
"""The build's members labelled for the version: read from the file the first reader left (the cycle or another API worker), or
|
||||
computed from the build and saved for the next. Reading the build takes minutes; the file, a fraction of a second."""
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.survival import live
|
||||
from models.io.storage import KitBuild
|
||||
|
||||
path = _members_path(domain, scenario, version, build_id)
|
||||
if path.exists():
|
||||
try:
|
||||
return pd.read_parquet(path)
|
||||
except (OSError, ValueError):
|
||||
log.warning("no se pudo leer %s; se recalcula", path)
|
||||
build = KitBuild(domain, build_id)
|
||||
labelled = live.members(spec, build.frame(), build.lineage())
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
||||
labelled.to_parquet(tmp)
|
||||
tmp.replace(path)
|
||||
for old in path.parent.glob(f"{domain}-{scenario}-v*-armado*.parquet"):
|
||||
if old != path:
|
||||
old.unlink(missing_ok=True)
|
||||
return labelled
|
||||
|
||||
|
||||
def _live_context(domain: str, scenario: str):
|
||||
@@ -31,7 +68,6 @@ def _live_context(domain: str, scenario: str):
|
||||
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)
|
||||
@@ -41,13 +77,25 @@ def _live_context(domain: str, scenario: str):
|
||||
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))
|
||||
_LIVE.update(key=key, value=(spec, model, _members(spec, domain, scenario, resolved.version, build_id), resolved.version))
|
||||
_ANSWERS.clear()
|
||||
return _LIVE["value"]
|
||||
|
||||
|
||||
def warm(domain: str) -> list[str]:
|
||||
"""Loads the live context of each of the domain's live scenarios (`LIVE_SCENARIOS`), leaving their members' file for every
|
||||
reader; the scenarios it loaded. One without a version in production or a build is skipped."""
|
||||
loaded = []
|
||||
for scenario in LIVE_SCENARIOS.get(domain, ()):
|
||||
try:
|
||||
_live_context(domain, scenario)
|
||||
except LookupError:
|
||||
continue
|
||||
loaded.append(scenario)
|
||||
return loaded
|
||||
|
||||
|
||||
def _summary(domain: str, scenario: str, version: str, artifact: str = "analisis/desarrollo.json", table: str = "escenarios_resumen") -> list[dict]:
|
||||
"""The rows of the scenario summary a version published (`escenarios_resumen`): one per scenario, and for recurrence one per
|
||||
cohort, scenario and horizon. `[]` for a version that published none (trained before the summary existed)."""
|
||||
|
||||
Reference in New Issue
Block a user