"""What each output came from, in one vocabulary for files, runs and versions: the names models are registered under, the keys lineage is recorded with, the code's version, a model's hash, and the rule that an output already exists when its recorded lineage matches what's expected. The hashes of data files live with the files (`models.io.storage`). """ import hashlib from importlib.metadata import version from pathlib import Path DOMAINS = ("cacu", "cama", "tea") ARMADO_TAG = "kit.armado_id" MODEL_SHA_TAG = "modelo_sha" MODELS_VERSION_TAG = "models.version" GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets; read by `models.tea.eeg.bundle` COHORT_URL_TAG, COHORT_SOURCE_TAG = "cohort.url", "cohort.source" COHORT_BUILD_TAG, COHORT_FILE_TAG = "cohort.build", "cohort.file_sha256" def registered_name(domain: str, scenario: str) -> str: return f"{domain}-{scenario}" def code_version() -> dict[str, str]: """The version of the installed `models` package: what a run's code is, with or without a repository.""" return {MODELS_VERSION_TAG: version("models")} def model_sha(model_dir: str | Path) -> str: """sha256 of a saved model's pickle (`python_model.pkl` for a pyfunc, `model.pkl` for scikit-learn): the fitted model itself. `MLmodel` is left out because it carries ids and dates, so the same model saved twice has the same sha.""" folder = Path(model_dir) pickle = next(path for path in (folder / "python_model.pkl", folder / "model.pkl") if path.exists()) return hashlib.sha256(pickle.read_bytes()).hexdigest() def matches(recorded: dict, expected: dict) -> bool: """Whether an output's recorded lineage has every expected value: then it is already done.""" return all(str(recorded.get(key)) == str(value) for key, value in expected.items())