"""Tests for the classifier trained from the corpus: tools/train_intent.py and ngram.py.""" import json import os import sys import tempfile import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT) sys.path.insert(0, os.path.join(ROOT, "tools")) from lingologos_thinkingpython import ngram # noqa: E402 import train_intent # noqa: E402 def tiny_rows(): rows = [] for lang in ("en", "it"): frames = (["remove the mutable default", "default list argument"] if lang == "en" else ["rimuovi il default mutabile", "lista di default condivisa"]) for phrase in frames: for suffix in range(4): rows.append({"lang": lang, "frame": "mutable-default", "split": "train", "text": phrase + " in collect " + str(suffix)}) rows.append({"lang": lang, "frame": "magic-literal", "split": "train", "text": phrase.replace("default", "magic number " + str(suffix))}) rows.append({"lang": lang, "frame": "", "split": "train", "text": "make this module faster please"}) rows.append({"lang": lang, "frame": "", "split": "eval", "text": "make this module faster please"}) rows.append({"lang": lang, "frame": "mutable-default", "split": "eval", "text": frames[0] + " in collect now"}) return rows class FeaturesTest(unittest.TestCase): def test_word_bigram_and_char_ngrams(self): counts = ngram.features("Remove the default") self.assertEqual(counts["w:remove"], 1) self.assertEqual(counts["b:remove the"], 1) self.assertGreater(counts["c:def"], 0) self.assertEqual(ngram.features(""), ngram.features(None)) def test_train_one_model_per_variety(self): model = ngram.train(tiny_rows()) self.assertEqual(sorted(model["languages"]), ["en", "it"]) self.assertIn(ngram.REFUSE, model["classes"]) with self.assertRaises(ngram.ModelError): ngram.score(model, "de", ngram.features("x")) class ClassifyTest(unittest.TestCase): def setUp(self): self.model = ngram.train(tiny_rows()) def test_votes_for_the_closer_frame(self): frame, _gap = ngram.classify(self.model, "en", "remove the mutable default in collect", 0.0) self.assertEqual(frame, "mutable-default") def test_abstains_on_the_refusal_class(self): frame, _gap = ngram.classify(self.model, "en", "make this module faster please", 0.0) self.assertEqual(frame, "") def test_abstains_below_the_margin(self): _frame, gap = ngram.classify(self.model, "en", "remove the mutable default", 0.0) self.assertEqual(ngram.classify(self.model, "en", "remove the mutable default", gap + 1.0)[0], "") class MarginTest(unittest.TestCase): def test_margin_chosen_on_the_eval_split_only(self): model = ngram.train(tiny_rows()) margin, report = ngram.choose_margin(model, tiny_rows(), grid=(0.0, 3.0, 9.0)) self.assertIn(margin, (0.0, 3.0, 9.0)) self.assertGreaterEqual(report["eval_precision"], 0.999) self.assertGreaterEqual(report["eval_in_scope"], 1) def test_rows_outside_the_eval_split_are_ignored(self): model = ngram.train(tiny_rows()) rows = tiny_rows() + [{"lang": "en", "frame": "magic-literal", "split": "train", "text": "zzz qqq"}] self.assertEqual(ngram.choose_margin(model, rows)[1]["eval_correct"], ngram.choose_margin(model, tiny_rows())[1]["eval_correct"]) class ArtifactTest(unittest.TestCase): def test_save_and_load_roundtrip(self): model = ngram.train(tiny_rows()) model["margin"] = 7.0 with tempfile.TemporaryDirectory() as folder: path = os.path.join(folder, "intent_model.json") self.assertGreater(ngram.save(model, path), 0) self.assertTrue(ngram.exists(path)) loaded = ngram.load(path) self.assertEqual(loaded, model) self.assertEqual(ngram.classify(loaded, "it", "lista di default condivisa")[1] >= 0, True) def test_missing_file_is_an_error(self): with tempfile.TemporaryDirectory() as folder: with self.assertRaises(ngram.ModelError): ngram.load(os.path.join(folder, "absent.json")) def test_a_foreign_document_is_rejected(self): with tempfile.TemporaryDirectory() as folder: path = os.path.join(folder, "model.json") with open(path, "w", encoding="utf-8") as handle: json.dump({"nope": 1}, handle) with self.assertRaises(ngram.ModelError): ngram.load(path) class ToolTest(unittest.TestCase): def test_writes_the_model_and_the_eval_booklet(self): with tempfile.TemporaryDirectory() as folder: corpus = os.path.join(folder, "corpus.jsonl") with open(corpus, "w", encoding="utf-8") as handle: for row in tiny_rows(): handle.write(json.dumps(row) + "\n") code = train_intent.main(["--corpus", corpus, "--model", os.path.join(folder, "model.json"), "--out", os.path.join(folder, "eval.json")]) self.assertEqual(code, 0) with open(os.path.join(folder, "eval.json"), encoding="utf-8") as handle: booklet = json.load(handle) self.assertEqual(sorted(booklet["languages"]), ["en", "it"]) self.assertIn("top1_ci95", booklet["overall"]) self.assertIn("margin_rule", booklet) def test_check_compares_the_saved_model_with_the_corpus(self): with tempfile.TemporaryDirectory() as folder: corpus = os.path.join(folder, "corpus.jsonl") model_path = os.path.join(folder, "model.json") with open(corpus, "w", encoding="utf-8") as handle: for row in tiny_rows(): handle.write(json.dumps(row) + "\n") train_intent.main(["--corpus", corpus, "--model", model_path, "--out", os.path.join(folder, "eval.json")]) self.assertEqual(train_intent.main(["--corpus", corpus, "--model", model_path, "--out", os.path.join(folder, "eval.json"), "--check"]), 0) with open(model_path, "w", encoding="utf-8") as handle: json.dump({"alpha": 0.0, "languages": {}}, handle) self.assertEqual(train_intent.main(["--corpus", corpus, "--model", model_path, "--out", os.path.join(folder, "eval.json"), "--check"]), 1) def test_wilson_interval_of_a_small_sample_is_wide(self): low, high = train_intent.wilson(3, 4) self.assertLess(low, 0.75) self.assertGreater(high, 0.75) self.assertEqual(train_intent.wilson(0, 0), [0.0, 0.0]) if __name__ == "__main__": unittest.main()