File size: 5,523 Bytes
7ca0188 | 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | """DistilBERT intent inference with a deterministic offline fallback."""
from __future__ import annotations
import json
import logging
import re
from pathlib import Path
from typing import Any
try:
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
except ImportError:
torch = None # type: ignore[assignment]
AutoModelForSequenceClassification = None # type: ignore[assignment]
AutoTokenizer = None # type: ignore[assignment]
from src.config import Settings, get_settings
LOGGER = logging.getLogger(__name__)
LABELS = (
"find_gate", "find_baggage", "find_checkin", "find_security", "find_transport",
"find_lounge", "find_restroom", "find_information_desk", "lost_found",
"accessibility_help", "opening_hours", "flight_status", "fallback_unknown",
)
class IntentClassifier:
"""Load a trained classifier when available and otherwise apply safe rules."""
def __init__(self, settings: Settings | None = None) -> None:
self.settings = settings or get_settings()
self.model_path = Path(self.settings.intent_model_path)
self.model: Any | None = None
self.tokenizer: Any | None = None
self.id_to_label: dict[int, str] = {}
def load(self) -> bool:
"""Load local model artifacts without attempting a network download."""
if self.is_available():
return True
if not self.model_path.is_dir() or AutoTokenizer is None or AutoModelForSequenceClassification is None:
return False
mapping_path = self.model_path.parent / "intent_label_mapping.json"
try:
mapping = json.loads(mapping_path.read_text(encoding="utf-8"))
self.id_to_label = {int(value): key for key, value in mapping.items()}
self.tokenizer = AutoTokenizer.from_pretrained(self.model_path, local_files_only=True)
self.model = AutoModelForSequenceClassification.from_pretrained(
self.model_path, local_files_only=True
)
self.model.eval()
return True
except (OSError, RuntimeError, ValueError, json.JSONDecodeError) as exc:
LOGGER.warning("Intent model unavailable; using rule fallback: %s", exc)
self.model = None
self.tokenizer = None
self.id_to_label = {}
return False
def is_available(self) -> bool:
"""Return whether model, tokenizer, and label mapping are loaded."""
return bool(self.model is not None and self.tokenizer is not None and self.id_to_label)
@staticmethod
def _fallback(text: str) -> dict[str, Any]:
lowered = text.lower().strip()
rules = (
("flight_status", r"\b(status|delay(?:ed)?|cancel(?:led|ed)?|gate\s+chang(?:e|ed)|boarding|flight)\b"),
("find_baggage", r"\b(baggage|luggage|suitcase|carousel|reclaim)\b"),
("find_checkin", r"\b(check[ -]?in|counter)\b"),
("find_security", r"\b(security|screening|control)\b"),
("find_transport", r"\b(train|rail|bus|taxi|transport)\b"),
("find_lounge", r"\blounge\b"),
("find_restroom", r"\b(restroom|toilet|washroom|bathroom|wc|loo)\b"),
("find_information_desk", r"\b(information|help\s+desk|info\s+desk)\b"),
("lost_found", r"\b(lost\s+property|lost\s+item|lost\s+and\s+found|found\s+item)\b"),
("accessibility_help", r"\b(wheelchair|wheel\s+chair|mobility|assistance|accessibility|accessible|tactile|induction\s+loop)\b"),
("opening_hours", r"\b(open|opening\s+hours?|close|closing|hours)\b"),
("find_gate", r"\b(gate|gates)\b"),
)
intent = "fallback_unknown"
for label, pattern in rules:
if re.search(pattern, lowered):
intent = label
break
confidence = 0.75 if intent != "fallback_unknown" else 0.30
return {
"intent": intent,
"confidence": confidence,
"all_scores": {intent: confidence},
"model_source": "rule_fallback",
}
def predict(self, text: str) -> dict[str, Any]:
"""Predict one intent using DistilBERT or the rule fallback."""
if not text or not text.strip() or not self.load():
return self._fallback(text or "")
try:
encoded = self.tokenizer(
text.strip(), return_tensors="pt", truncation=True, padding=True, max_length=128
)
with torch.no_grad():
logits = self.model(**encoded).logits[0]
probabilities = torch.softmax(logits, dim=-1).cpu().tolist()
scores = {
self.id_to_label[index]: float(score)
for index, score in enumerate(probabilities)
if index in self.id_to_label
}
intent = max(scores, key=scores.get)
return {
"intent": intent,
"confidence": float(scores[intent]),
"all_scores": scores,
"model_source": "distilbert",
}
except (RuntimeError, TypeError, ValueError) as exc:
LOGGER.warning("Intent inference failed; using rule fallback: %s", exc)
return self._fallback(text)
def predict_batch(self, texts: list[str]) -> list[dict[str, Any]]:
"""Predict a list of texts while preserving input order."""
return [self.predict(text) for text in texts]
|