campusdesk-ai / src /classification /model_loader.py
Estarcode's picture
Upload folder using huggingface_hub
2ab2b76 verified
Raw History Blame Contribute Delete
2.04 kB
"""Checkpoint and artifact loaders for TF-IDF baseline and fine-tuned encoder models."""
import json
from pathlib import Path
from typing import Dict, Tuple
import joblib
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from src.config import FINE_TUNED_DIR, INTENT_LABELS, LABEL_MAP_PATH, TFIDF_MODEL_PATH
def load_tfidf_baseline(model_path: Path = TFIDF_MODEL_PATH):
"""Load the serialized scikit-learn TF-IDF + LogisticRegression pipeline."""
if not model_path.exists():
raise FileNotFoundError(
f"Baseline artifact not found at {model_path}. Run scripts/train_classifiers.py first."
)
return joblib.load(model_path)
def load_label_map(label_map_path: Path = LABEL_MAP_PATH) -> Dict[int, str]:
"""Load id2label mapping from label_map.json with deterministic fallback."""
if label_map_path.exists():
data = json.loads(label_map_path.read_text(encoding="utf-8"))
return {int(k): v for k, v in data["id2label"].items()}
return {idx: lbl for idx, lbl in enumerate(INTENT_LABELS)}
def load_finetuned_encoder(
model_dir: Path = FINE_TUNED_DIR,
label_map_path: Path = LABEL_MAP_PATH,
) -> Tuple[AutoTokenizer, AutoModelForSequenceClassification, Dict[int, str], str]:
"""Reload fine-tuned Hugging Face encoder checkpoint, tokenizer, and label map."""
if not model_dir.exists() or not (model_dir / "config.json").exists():
raise FileNotFoundError(
f"Fine-tuned encoder checkpoint not found at {model_dir}. "
"Run scripts/train_classifiers.py first."
)
effective_label_map = label_map_path if label_map_path.exists() else (model_dir / "label_map.json")
id2label = load_label_map(effective_label_map)
device = "cuda" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained(model_dir)
model = AutoModelForSequenceClassification.from_pretrained(model_dir).to(device)
model.eval()
return tokenizer, model, id2label, device