Download src/classification/classifier.py from Estarcode/campusdesk-ai: direct link, hf CLI and curl.
- Browser
- Download file 3.29 kB
-
https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/src/classification/classifier.py
- Command line
-
hf download hf://Estarcode/campusdesk-ai/src/classification/classifier.py
-
curl -L -o classifier.py https://huggingface.co/Estarcode/campusdesk-ai/resolve/main/src/classification/classifier.py
3.29 kB
| """Unified intent classification wrappers for baseline and fine-tuned Hugging Face encoder.""" | |
| import time | |
| from pathlib import Path | |
| from typing import Dict, Optional | |
| import numpy as np | |
| import torch | |
| from src.classification.model_loader import ( | |
| load_finetuned_encoder, | |
| load_tfidf_baseline, | |
| ) | |
| from src.config import DEFAULT_DEPLOYED_CLASSIFIER, FINE_TUNED_DIR, LABEL_MAP_PATH, TFIDF_MODEL_PATH | |
| from src.schemas import IntentPrediction | |
| class TfidfIntentClassifier: | |
| """Character/word TF-IDF + LogisticRegression baseline classifier.""" | |
| def __init__(self, model_path: Path = TFIDF_MODEL_PATH): | |
| self.pipeline = load_tfidf_baseline(model_path) | |
| self.model_name = "TF-IDF + LogisticRegression (Baseline)" | |
| def predict(self, text: str) -> IntentPrediction: | |
| start = time.perf_counter() | |
| probs = self.pipeline.predict_proba([text])[0] | |
| classes = list(self.pipeline.classes_) | |
| prob_map = {cls: float(p) for cls, p in zip(classes, probs)} | |
| best_idx = int(np.argmax(probs)) | |
| elapsed = (time.perf_counter() - start) * 1000.0 | |
| return IntentPrediction( | |
| label=classes[best_idx], | |
| confidence=float(probs[best_idx]), | |
| probabilities=prob_map, | |
| model_used=self.model_name, | |
| latency_ms=round(elapsed, 2), | |
| ) | |
| class EncoderIntentClassifier: | |
| """Fine-tuned Afro-XLMR encoder intent classifier reloaded from checkpoint.""" | |
| def __init__( | |
| self, | |
| model_dir: Path = FINE_TUNED_DIR, | |
| label_map_path: Path = LABEL_MAP_PATH, | |
| ): | |
| self.tokenizer, self.model, self.id2label, self.device = load_finetuned_encoder( | |
| model_dir=model_dir, | |
| label_map_path=label_map_path, | |
| ) | |
| self.model_name = "Fine-tuned Encoder (Davlan/afro-xlmr-small)" | |
| def predict(self, text: str) -> IntentPrediction: | |
| start = time.perf_counter() | |
| enc = self.tokenizer( | |
| text, | |
| truncation=True, | |
| max_length=96, | |
| return_tensors="pt", | |
| ).to(self.device) | |
| logits = self.model(**enc).logits[0] | |
| probs = torch.softmax(logits, dim=-1).cpu().numpy() | |
| prob_map = {self.id2label[i]: float(probs[i]) for i in range(len(probs))} | |
| best_idx = int(np.argmax(probs)) | |
| elapsed = (time.perf_counter() - start) * 1000.0 | |
| return IntentPrediction( | |
| label=self.id2label[best_idx], | |
| confidence=float(probs[best_idx]), | |
| probabilities=prob_map, | |
| model_used=self.model_name, | |
| latency_ms=round(elapsed, 2), | |
| ) | |
| _CLASSIFIER_CACHE: Dict[str, object] = {} | |
| def get_classifier(choice: Optional[str] = None): | |
| """Return cached classifier instance ('encoder' or 'baseline').""" | |
| selected = (choice or DEFAULT_DEPLOYED_CLASSIFIER).lower() | |
| if selected not in {"encoder", "baseline"}: | |
| raise ValueError(f"Unknown classifier choice '{selected}'. Use 'encoder' or 'baseline'.") | |
| if selected not in _CLASSIFIER_CACHE: | |
| if selected == "encoder": | |
| _CLASSIFIER_CACHE[selected] = EncoderIntentClassifier() | |
| else: | |
| _CLASSIFIER_CACHE[selected] = TfidfIntentClassifier() | |
| return _CLASSIFIER_CACHE[selected] | |