File size: 2,608 Bytes
5eb0dd1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | """Load the scenarios and trained trees, from the Hub or from local folders.
This is all the Gradio app needs at run time. Training and labeling live in model.py.
"""
import os
from pathlib import Path
import polars as pl
import skops.io as sio
from sklearn.tree import DecisionTreeClassifier
DATA = Path(__file__).parents[2] / "dataset" / "scenarios.csv"
MODELS_DIR = Path(__file__).parents[2] / "models"
# A Hugging Face model repo id (e.g. "<user>/phi115_learning_object_2_model"); when set, load from there.
MODEL_REPO_ENV = "LO_MODEL_REPO"
# A Hugging Face dataset repo id holding scenarios.csv; when set, the app reads it from there.
DATASET_REPO_ENV = "LO_DATASET_REPO"
# skops lists the types a file would instantiate; a tree file should contain only this one.
EXPECTED_TYPES = {"sklearn.tree._tree.Tree"}
FEATURES = ["human_decided", "explicit_rule", "foreseeable", "patchable"]
LABELS = ["legal", "moral", "design"]
def load_scenarios(repo: str | None = None) -> pl.DataFrame:
"""Read scenarios.csv from the Hub (repo, or $LO_DATASET_REPO) or from the local dataset folder.
A private repo needs a token in the HF_TOKEN environment variable (a Space secret).
"""
repo = repo or os.environ.get(DATASET_REPO_ENV)
if repo:
from huggingface_hub import hf_hub_download
return pl.read_csv(hf_hub_download(repo, "scenarios.csv", repo_type="dataset"))
return pl.read_csv(DATA)
def load_trees(
repo: str | None = None, directory: Path = MODELS_DIR
) -> dict[str, DecisionTreeClassifier]:
"""Load the three trees from the Hub (repo, or $LO_MODEL_REPO) or from a local directory.
skops refuses to load anything outside the types we expect, unlike pickle.
"""
repo = repo or os.environ.get(MODEL_REPO_ENV)
trees = {}
for label in LABELS:
if repo:
from huggingface_hub import hf_hub_download
path = Path(hf_hub_download(repo, f"{label}.skops"))
else:
path = directory / f"{label}.skops"
if not path.exists():
raise FileNotFoundError(
f"{path} not found. Run `uv run learning-object-02` to train and save the "
f"trees, or set {MODEL_REPO_ENV} to a Hugging Face model repo."
)
untrusted = set(sio.get_untrusted_types(file=path))
if not untrusted <= EXPECTED_TYPES:
raise ValueError(
f"{path} contains unexpected types: {sorted(untrusted - EXPECTED_TYPES)}"
)
trees[label] = sio.load(path, trusted=sorted(untrusted))
return trees
|