"""A bag of n grams classifier trained from the corpus of this bundle (acceptance D1). No pre trained model is used anywhere in this dataset: the classifier here counts word unigrams, word bigrams, character trigrams and four grams inside each token, and character four to six grams across the whole request, then scores a request with a complement multinomial naive Bayes in log space: a feature is scored by how much it belongs to one class against all the others, not by its raw frequency. The wide character grams carry the shape of a phrase across a reworded request, which the per token grams alone lose. One model is trained per variety, because the feature space of a Chinese request shares nothing with an Italian one. The class for a request that is out of the catalog is a class of its own, so the same model that recognises a frame also decides when to abstain. The classifier is a second opinion: the intent node keeps the lexicon ranking, and only when the ranking abstains does it ask this model. A margin on the log score gap decides how much confidence the second opinion needs, and that margin is chosen on the eval split of the corpus, never on a held out set. """ import json import math import os import re import sys from collections import Counter, defaultdict from typing import Any, Dict, Iterable, List, Optional, Tuple ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT) MODEL_PATH = os.path.join(ROOT, "models", "intent_model.json") REFUSE = "__refuse__" ALPHA = 0.1 WORD = re.compile(r"\w+", re.UNICODE) class ModelError(Exception): pass def features(text: str) -> Counter: """Counts of the n grams a request is made of, script independent.""" tokens = WORD.findall(str(text or "").lower()) counts: Counter = Counter() for token in tokens: counts["w:" + token] += 1 for size in (3, 4): if len(token) >= size: for start in range(len(token) - size + 1): counts["c:" + token[start:start + size]] += 1 for first, second in zip(tokens, tokens[1:]): counts["b:" + first + " " + second] += 1 joined = " " + " ".join(tokens) + " " for size in (4, 5, 6): for start in range(len(joined) - size + 1): counts["j:" + joined[start:start + size]] += 1 return counts def train(rows: Iterable[Dict[str, Any]]) -> Dict[str, Any]: """One naive Bayes per variety over the rows of the train split.""" per_language: Dict[str, Dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter)) documents: Dict[str, Counter] = defaultdict(Counter) for row in rows: if row.get("split") != "train": continue language = row.get("lang") or "" label = row.get("frame") or REFUSE per_language[language][label].update(features(row.get("text", ""))) documents[language][label] += 1 languages: Dict[str, Any] = {} for language, bags in per_language.items(): vocab = len({feature for bag in bags.values() for feature in bag}) totals = {label: sum(bag.values()) for label, bag in bags.items()} corpus = sum(documents[language].values()) priors = {label: math.log((documents[language][label] + 1) / (corpus + len(documents[language]))) for label in bags} languages[language] = {"vocab": vocab, "totals": totals, "priors": priors, "weights": complement_weights(bags, totals, vocab)} return {"alpha": ALPHA, "classes": sorted({label for bags in per_language.values() for label in bags}), "languages": languages} def complement_weights(bags: Dict[str, Counter], totals: Dict[str, int], vocab: int) -> Dict[str, Dict[str, float]]: """One signed log weight per feature and class (complement naive Bayes). A feature gets the log ratio between how often it appears in its own class and how often it appears in all the other classes together. The ratio form is what carries a request the corpus never worded this way: the raw multinomial log likelihood grows with the length of the request and with the frequency of the feature, so a common word drags a correct class down on a wording the class has only seen a few times. """ everywhere: Counter = Counter() for bag in bags.values(): everywhere.update(bag) labels = sorted(bags) others = max(1, len(labels) - 1) weights: Dict[str, Dict[str, float]] = {} for label in labels: bag = bags[label] own = totals[label] + ALPHA * vocab rest = sum(totals[other] for other in labels if other != label) + ALPHA * vocab * others weights[label] = {feature: math.log((times + ALPHA) / own) - math.log((everywhere[feature] - times + ALPHA) / rest) for feature, times in bag.items()} return weights def score(model: Dict[str, Any], language: str, counts: Counter) -> List[Tuple[str, float]]: """Log score of every class, best first: prior plus the weights its features carry.""" entry = model["languages"].get(language) if not entry: raise ModelError("no model trained for %s" % language) scored: List[Tuple[str, float]] = [] for label, table in entry["weights"].items(): value = entry["priors"][label] for feature, times in counts.items(): value += times * table.get(feature, 0.0) scored.append((label, value)) scored.sort(key=lambda pair: (-pair[1], pair[0])) return scored def classify(model: Dict[str, Any], language: str, text: str, margin: Optional[float] = None) -> Tuple[str, float]: """The frame the model votes for, or an empty string when it is not sure.""" margin = float(model.get("margin", 8.0)) if margin is None else float(margin) scored = score(model, language, features(text)) if not scored: return "", 0.0 best, best_score = scored[0] gap = best_score - scored[1][1] if len(scored) > 1 else float("inf") if best == REFUSE or gap < margin: return "", gap return best, gap def choose_margin(model: Dict[str, Any], rows: List[Dict[str, Any]], grid: Tuple[float, ...] = (0.0, 1.0, 2.0, 3.0, 5.0, 8.0, 12.0, 20.0), precision_floor: float = 0.999) -> Tuple[float, Dict[str, Any]]: """The smallest margin whose eval precision clears the floor. The grid is scored on the eval split of the corpus: the held out sets are never read here, so the margin cannot be tuned on the data the gates later measure. """ scored_rows = [] for row in rows: if row.get("split") != "eval": continue ranked = score(model, row.get("lang", ""), features(row.get("text", ""))) if not ranked: continue best, best_score = ranked[0] gap = best_score - ranked[1][1] if len(ranked) > 1 else float("inf") scored_rows.append((row.get("frame") or "", best, gap)) best_margin, best_report = grid[0], {} for margin in grid: answered = correct = in_scope = 0 for expected, label, gap in scored_rows: got = "" if label == REFUSE or gap < margin else label if expected: in_scope += 1 if got: answered += 1 if got == expected: correct += 1 precision = correct / answered if answered else 0.0 report = {"margin": margin, "eval_in_scope": in_scope, "eval_answered": answered, "eval_correct": correct, "eval_precision": round(precision, 4)} if best_report == "": best_margin, best_report = margin, report if precision >= precision_floor: return margin, report return best_margin, best_report def save(model: Dict[str, Any], path: str = MODEL_PATH) -> int: os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8", newline="\n") as handle: json.dump(model, handle, ensure_ascii=False, sort_keys=True) handle.write("\n") return os.path.getsize(path) def load(path: str = MODEL_PATH) -> Dict[str, Any]: if not os.path.isfile(path): raise ModelError("no trained model at %s: run tools/train_intent.py" % path) with open(path, "r", encoding="utf-8") as handle: model = json.load(handle) if "languages" not in model: raise ModelError("the model file is not a trained intent model") return model def exists(path: str = MODEL_PATH) -> bool: return os.path.isfile(path)