File size: 2,040 Bytes
2ab2b76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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