"""Tests of the installed package: the stored outputs of every function and of the pipeline (golden.json), the SHA-256 of the model files, texts without words, one test per item of the iapp-ai team's review of 0.1.0, the module functions and the command line. Run after `pip install` of the wheel: python -m pytest tests""" import json import re import subprocess import sys from pathlib import Path import pytest import openthai_nlp_core_lite as pkg from openthai_nlp_core_lite import NLPCore from openthai_nlp_core_lite import _runtime as M from openthai_nlp_core_lite._runtime import ASSETS, HeadsRuntime GOLDEN = json.loads(Path(__file__).with_name("golden.json").read_text(encoding="utf-8")) TEAM = "ผมไปตลาดซื้อผักแล้วก็กลับบ้าน แม่ทำกับข้าวรอไว้แล้ว น้องสาวยังไม่กลับจากโรงเรียน" # the review's B1 and B7 text def norm(x): return json.loads(json.dumps(x, ensure_ascii=False)) # tuples as lists, as stored def leaves(tree: str) -> list: """The leaves of a tree in Penn brackets, read as a bracket reader (nltk.Tree.fromstring) reads it: a token right after "(" is a label, every other token a leaf. Fails on unbalanced brackets.""" depth, prev, out = 0, None, [] for tok in re.findall(r"\(|\)|[^\s()]+", tree): if tok == "(": depth += 1 elif tok == ")": depth -= 1 assert depth >= 0, tree elif prev != "(": out.append(tok) prev = tok assert depth == 0, tree return out def escaped(word: str) -> str: return word.replace("(", "-LRB-").replace(")", "-RRB-") @pytest.fixture(scope="module") def nlp(): return NLPCore() def test_model_files_have_the_sha256_of_the_manifest(): HeadsRuntime(ASSETS, verify=True) @pytest.mark.parametrize("g", GOLDEN, ids=lambda g: g["text"][:12] or "empty") def test_every_function_gives_the_stored_output(nlp, g): t = g["text"] assert norm({u: nlp.word_tokenize(t, u) for u in ("long", "short", "minimal")}) == g["word_tokenize"] assert norm({u: nlp.tokenize(t, unit=u) for u in ("long", "short", "minimal")}) == g["tokenize"] got = nlp.tokenize_nbest(t[:60], n=3) assert [x for x, _ in got] == [x for x, _ in g["tokenize_nbest"]] assert [round(p, 4) for _, p in got] == [round(p, 4) for _, p in g["tokenize_nbest"]] assert nlp.sent_tokenize(t) == g["sent_tokenize"] assert nlp.clause_tokenize(t) == g["clause_tokenize"] assert norm(nlp.sent_spans(t)) == g["sent_spans"] and norm(nlp.clause_spans(t)) == g["clause_spans"] assert norm({f"{u}/{ts}": nlp.pos_tag(t, u, ts) for u in ("long", "short", "minimal") for ts in ("ud", "orchid")}) \ == g["pos_tag"] assert norm([[w._asdict() for w in s] for s in nlp.dependency_parse(t)]) == g["dependency_parse"] assert nlp.constituency_parse(t) == g["constituency_parse"] assert nlp.constituency_parse(t, inside_words=True) == g["constituency_parse_inside"] assert {lab: nlp.word_trees(t, lab) for lab in ("tag", "phrase")} == g["word_trees"] assert norm(nlp.analyze(t).to_dict()) == g["analyze"] if "ner" in g: assert norm(nlp.ner(t)) == g["ner"] assert norm(nlp.ner_batch([t, t])) == [g["ner"]] * 2 def test_texts_without_words(nlp): for t in ("", " ", "\n\n", "\t \n", "​"): assert nlp.word_tokenize(t) == [] and nlp.sent_tokenize(t) == [] and nlp.pos_tag(t) == [] assert nlp.dependency_parse(t) == [] and nlp.constituency_parse(t) == [] and nlp.clause_tokenize(t) == [] doc = nlp.analyze(t) assert doc.words == [] and doc.sentences == [] and doc.entities == [] and doc.to_conllu() == "" if "ner" in nlp.rt.manifest["heads"]: assert nlp.ner(t) == [] def test_words_cover_the_text_without_whitespace(nlp): t = GOLDEN[0]["text"] for unit in ("long", "short", "minimal"): assert "".join(nlp.word_tokenize(t, unit)) == "".join(t.split()) def test_the_word_segmenter_interface(nlp): t = "ผู้ว่าราชการจังหวัด ไปตากลม\nที่ Bangkok 2024" toks = nlp.tokenize(t) assert "".join(toks) == t # every character, whitespace included, as the word segmenter returns them assert [x for x in toks if not x.isspace()] == nlp.word_tokenize(t) == nlp.tokenize(t, keep_whitespace=False) assert nlp.tokenize_batch([t, t], unit="long") == [nlp.tokenize(t, unit="long")] * 2 assert nlp.tokenize_nbest(t, n=3)[0][0] == toks # the tokenize result first assert "Bangkok" in toks and "2024" in toks # runs of Latin letters or digits stay whole with pytest.raises(TypeError): nlp.tokenize_batch(t) assert NLPCore(user_words=["ไอแอพพ์"]).word_tokenize("ไอแอพพ์เปิดตัว") # user words are accepted # ---------------------------------------------------------------------------------------------------------------- pipeline def test_the_pipeline_gives_every_task_on_one_cut_of_words(nlp): doc = nlp(TEAM) assert doc.tasks == M.TASKS and doc.words and doc.sentences and doc.clauses words = [w.text for w in doc.words] assert words == nlp.word_tokenize(TEAM) == [w for w, _ in nlp.pos_tag(TEAM)] assert words == [w.text for s in nlp.dependency_parse(TEAM) for w in s] assert [w.text for s in doc.sentences for w in s.words] == words assert all(w.upos and w.xpos and w.deprel and w.head is not None for w in doc.words) assert [(w.text, w.upos) for w in doc.words] == nlp.pos_tag(TEAM) assert [(w.text, w.xpos) for w in doc.words] == nlp.pos_tag(TEAM, tagset="orchid") assert [s.words for s in doc.sentences] == nlp.dependency_parse(TEAM) assert doc.trees == nlp.constituency_parse(TEAM) assert doc.entities == nlp.ner(TEAM) assert [c.text for c in doc.clauses] == nlp.clause_tokenize(TEAM) for s in doc.sentences: assert TEAM[s.start:s.end] == s.text and [w.id for w in s.words] == list(range(1, len(s.words) + 1)) assert sum(w.head == 0 for w in s.words) == 1 assert leaves(s.tree) == [escaped(w.text) for w in s.words] json.dumps(doc.to_dict(), ensure_ascii=False) def test_tasks_choose_what_runs(nlp): assert nlp.analyze(TEAM, ["pos"]).tasks == ("words", "pos") assert nlp.analyze(TEAM, "pos,ner").tasks == ("words", "pos", "ner") assert nlp.analyze(TEAM, ["dep"]).tasks == ("sentences", "words", "dependency") # the parsers need sentences assert nlp.analyze(TEAM, ["con"]).tasks == ("sentences", "words", "constituency") assert nlp.analyze(TEAM, ["clauses"]).tasks == ("sentences", "clauses", "words") doc = nlp.analyze(TEAM, ["pos"]) assert doc.sentences == [] and all(w.head is None and w.deprel is None for w in doc.words) assert [w.id for w in doc.words] == list(range(1, len(doc.words) + 1)) assert set(doc.to_dict()) == {"text", "tasks", "words"} and set(doc.to_dict()["words"][0]) == \ {"id", "text", "start", "end", "upos", "xpos"} words = nlp.analyze(TEAM, ["words"]).words assert [w.text for w in words] == nlp.word_tokenize(TEAM) and all(w.upos is None for w in words) with pytest.raises(ValueError, match="unknown task"): nlp.analyze(TEAM, ["parse"]) with pytest.raises(TypeError): nlp.analyze(TEAM, 3) def test_batches_and_streams_give_the_same_documents(nlp): # copies of one text, and empty texts, which no call reads: the int8 network scales its numbers per call, so # different texts in one call can differ a little from one call each (as the word segmenter's tokenize_batch) t = TEAM texts = [t, "", t] one = [nlp.analyze(x) for x in texts] assert nlp.analyze_batch(texts) == one assert list(nlp.pipe(iter(texts), batch_size=2)) == one assert nlp.sent_tokenize_batch(texts) == [nlp.sent_tokenize(x) for x in texts] assert nlp.clause_tokenize_batch(texts) == [nlp.clause_tokenize(x) for x in texts] assert nlp.pos_tag_batch(texts) == [nlp.pos_tag(x) for x in texts] assert nlp.pos_tag_batch(texts, "orchid") == [nlp.pos_tag(x, tagset="orchid") for x in texts] assert nlp.dependency_parse_batch(texts) == [nlp.dependency_parse(x) for x in texts] assert nlp.constituency_parse_batch(texts) == [nlp.constituency_parse(x) for x in texts] assert nlp.ner_batch(texts) == [nlp.ner(x) for x in texts] def test_conllu(nlp): doc = nlp(TEAM) lines = doc.to_conllu().split("\n") rows = [x.split("\t") for x in lines if x and not x.startswith("#")] assert len(rows) == len(doc.words) and all(len(r) == 10 for r in rows) assert [r[1] for r in rows] == [w.text for w in doc.words] and [r[3] for r in rows] == [w.upos for w in doc.words] assert sum(x.startswith("# text = ") for x in lines) == len(doc.sentences) assert M.to_conllu(nlp.dependency_parse(TEAM)).count("\n\n") == len(doc.sentences) with pytest.raises(ValueError): nlp.analyze(TEAM, ["pos"]).to_conllu() def test_pos_tag_takes_words_already_cut(nlp): toks = nlp.tokenize(TEAM) # with the whitespace tokens, so that the model reads the same text got = nlp.pos_tag(toks) assert [x for x in got if not x[0].isspace()] == nlp.pos_tag(TEAM) assert all(tag == "SPACE" for w, tag in got if w.isspace()) assert nlp.pos_tag(["ฉัน", " ", "กิน", "ข้าว"])[1] == (" ", "SPACE") assert [w for w, _ in nlp.pos_tag(["ฉัน", "กินข้าว"], tagset="orchid")] == ["ฉัน", "กินข้าว"] with pytest.raises(ValueError): nlp.pos_tag(toks, unit="long") def test_entities_unpack_as_before(nlp): t = "นายสมชาย ใจดี เดินทางไปเชียงใหม่" for e in nlp.ner(t): s, label, a, b = e assert t[a:b] == s == e.text and label == e.label # ---------------------------------------------------------------------------------------------------------------- review def test_b1_a_clause_never_crosses_a_sentence(nlp): for t in (TEAM, "ก " + TEAM, TEAM.replace(" ", "")): sents, clauses = nlp.sent_spans(t), nlp.clause_spans(t) assert {s.start for s in sents} <= {c.start for c in clauses} assert all(any(s.start <= c.start and c.end <= s.end for s in sents) for c in clauses) def test_b2_brackets_of_the_text_do_not_break_the_trees(nlp): t = "นายสมชาย (ประธานบริษัท) กล่าวว่า (1) ราคาขึ้น ค่าใช้จ่าย (บาท) 100" words = [w for s in nlp.dependency_parse(t) for w in s] for trees in (nlp.constituency_parse(t), nlp.constituency_parse(t, inside_words=True)): got = [x for tree in trees for x in leaves(tree)] assert "(" not in "".join(got) and ")" not in "".join(got) assert [x for tree in nlp.constituency_parse(t) for x in leaves(tree)] == [escaped(w.text) for w in words] for tree in nlp.word_trees("บริษัท จำกัด (มหาชน) (1)", "tag") + nlp.word_trees("(มหาชน)", "phrase"): leaves(tree) def test_b3_b4_long_sentences_are_parsed_in_bounded_pieces(nlp): t = "ซื้อ" + "".join(["ข้าว", "ปลา", "หมู", "ไก่", "ผัก", "ไข่", "กุ้ง", "เนื้อ"][i % 8] + "กับ" for i in range(2300)) + "น้ำ" sents = nlp.dependency_parse(t) assert sum(len(s) for s in sents) > 4096 and max(len(s) for s in sents) <= M.MAX_SENTENCE_WORDS assert all(w.head is not None and w.deprel for s in sents for w in s) assert [len(s) for s in sents] == [len(s.words) for s in nlp.analyze(t, ["sentences"]).sentences] trees = nlp.constituency_parse(t[:3000]) assert all(leaves(x) for x in trees) and len(trees) == len(nlp.sent_tokenize(t[:3000])) assert max(len(s) for s in NLPCore(max_sentence_words=50).dependency_parse(t[:2000])) <= 50 def test_b5_half_of_a_broken_emoji_is_read(nlp): t = "ฉัน\ud83dกินข้าว" assert "".join(nlp.tokenize(t)) == t assert "".join(nlp.word_tokenize(t)) == t assert nlp.pos_tag(t) and nlp.dependency_parse(t) and nlp.constituency_parse(t) and nlp.analyze(t).words nlp.ner(t) nlp.tokenize_nbest(t, 2) def test_b6_inputs_are_checked_the_same_way_everywhere(nlp): one = [nlp.word_tokenize, nlp.tokenize, nlp.sent_tokenize, nlp.clause_tokenize, nlp.sent_spans, nlp.clause_spans, nlp.pos_tag, nlp.dependency_parse, nlp.constituency_parse, nlp.word_trees, nlp.ner, nlp.analyze, nlp.tokenize_nbest] for f in one: for bad in (None, 123, b"\xe0\xb8\x81"): with pytest.raises(TypeError): f(bad) many = [nlp.tokenize_batch, nlp.ner_batch, nlp.analyze_batch, nlp.sent_tokenize_batch, nlp.pos_tag_batch, nlp.dependency_parse_batch, nlp.constituency_parse_batch] for f in many: with pytest.raises(TypeError): f("one text") with pytest.raises(TypeError): f([None]) assert f(x for x in ["ก", "ข"]) == f(["ก", "ข"]) # any iterable of texts for call in (lambda: nlp.pos_tag("ตากลม", tagset="UD"), lambda: nlp.pos_tag("ตากลม", "short", "foo"), lambda: nlp.word_tokenize("ตากลม", "foo"), lambda: nlp.constituency_parse("ตากลม", labels="foo"), lambda: nlp.word_trees("ตากลม", labels="phrases"), lambda: nlp.constituency_parse("ตากลม", True, "bogus"), lambda: nlp.constituency_parse("ตากลม", labels="phrase"), lambda: nlp.tokenize_nbest("ตากลม", 0), lambda: NLPCore(threads=0), lambda: NLPCore(threads=-1), lambda: NLPCore(max_sentence_words=0)): with pytest.raises(ValueError): call() for call in (lambda: nlp.tokenize_nbest("ตากลม", 2.5), lambda: NLPCore(threads="2"), lambda: NLPCore(threads=True)): with pytest.raises(TypeError): call() assert nlp.word_tokenize("ตากลม", None) == nlp.word_tokenize("ตากลม") assert nlp.pos_tag("ตากลม", None) == nlp.pos_tag("ตากลม", "short") def test_b7_every_task_reads_the_same_words(nlp): for t in (TEAM, "#ข่าวด่วน ฝนตกหนัก น้ำท่วมโรงเรียน"): words = nlp.word_tokenize(t) assert [w for w, _ in nlp.pos_tag(t)] == words assert [w.text for s in nlp.dependency_parse(t) for w in s] == words assert [x for tree in nlp.constituency_parse(t) for x in leaves(tree)] == [escaped(w) for w in words] def test_b9_latin_words_with_accents_stay_whole(nlp): for unit in ("long", "short", "minimal"): words = nlp.word_tokenize("Pokémon และ café ที่ Zürich", unit) assert {"Pokémon", "café", "Zürich"} <= set(words) assert any("café" in x for x in nlp.word_trees("ร้าน café")) assert [p for toks, _ in nlp.tokenize_nbest("ร้านcafé", 5) for p in toks if "caf" in p] == \ ["café"] * len(nlp.tokenize_nbest("ร้านcafé", 5)) def test_b10_zero_width_spaces_and_controls_are_no_words(nlp): for z in ("​", "\x00", ""): t = "ฉัน" + z + "กิน" + z + "ข้าว" assert all(z not in w for w, _ in nlp.pos_tag(t)) and nlp.word_tokenize(t) == ["ฉัน", "กิน", "ข้าว"] assert all(z not in w.text for s in nlp.dependency_parse(t) for w in s) assert "".join(nlp.tokenize(t)) == t and z not in nlp.tokenize(t, keep_whitespace=False) # ---------------------------------------------------------------------------------------------------------------- package def test_the_module_functions_call_one_shared_model(nlp): t = GOLDEN[0]["text"] assert pkg.analyze(t) == nlp.analyze(t) and pkg.analyze(t, "pos,ner") == nlp.analyze(t, ["pos", "ner"]) assert pkg.analyze_batch([t, t]) == nlp.analyze_batch([t, t]) assert pkg.tokenize(t) == nlp.tokenize(t) and pkg.tokenize(t, unit="long") == nlp.tokenize(t, unit="long") assert pkg.tokenize_batch([t, t]) == nlp.tokenize_batch([t, t]) assert [x for x, _ in pkg.tokenize_nbest(t[:60], 3)] == [x for x, _ in nlp.tokenize_nbest(t[:60], 3)] assert pkg.word_tokenize(t, "minimal") == nlp.word_tokenize(t, "minimal") assert pkg.sent_tokenize(t) == nlp.sent_tokenize(t) and pkg.clause_tokenize(t) == nlp.clause_tokenize(t) assert pkg.sent_spans(t) == nlp.sent_spans(t) and pkg.clause_spans(t) == nlp.clause_spans(t) assert pkg.pos_tag(t) == nlp.pos_tag(t) and pkg.pos_tag(t, "long", "orchid") == nlp.pos_tag(t, "long", "orchid") assert pkg.dependency_parse(t) == nlp.dependency_parse(t) assert pkg.constituency_parse(t) == nlp.constituency_parse(t) assert pkg.constituency_parse(t, inside_words=True) == nlp.constituency_parse(t, inside_words=True) assert pkg.word_trees(t) == nlp.word_trees(t) assert pkg.ner(t) == nlp.ner(t) and pkg.ner_batch([t, t]) == nlp.ner_batch([t, t]) assert pkg.to_conllu(pkg.analyze(t)) == nlp.analyze(t).to_conllu() assert pkg._nlp() is pkg._nlp() assert all(hasattr(pkg, n) for n in pkg.__all__) and pkg.__version__ def cli(*args, stdin=None): r = subprocess.run([sys.executable, "-m", "openthai_nlp_core_lite", *args], input=stdin, capture_output=True, encoding="utf-8") return r.returncode, r.stdout.split("\n")[:-1], r.stderr def test_the_command_line(): t = GOLDEN[0]["text"] def run(*args): code, out, err = cli(*args, t) assert code == 0, err return out assert run("--unit", "long") == ["|".join(GOLDEN[0]["word_tokenize"]["long"])] assert [x for x in run("--task", "sentences") if x] == GOLDEN[0]["sent_tokenize"] assert [x for x in run("--task", "clauses") if x] == GOLDEN[0]["clause_tokenize"] assert run("--task", "pos")[0].split(" ") == [f"{w}/{g}" for w, g in GOLDEN[0]["pos_tag"]["short/ud"]] assert [x for x in run("--task", "con") if x] == GOLDEN[0]["constituency_parse"] assert [x.split("\t")[1] for x in run("--task", "dep") if x] == \ [w["text"] for s in GOLDEN[0]["dependency_parse"] for w in s] assert [x.split("\t") for x in run("--task", "ner") if x] == [[str(c) for c in e] for e in GOLDEN[0]["ner"]] assert [json.loads(x) for x in run("--task", "all")] == [GOLDEN[0]["analyze"]] assert json.loads(run("--task", "pos,ner")[0])["tasks"] == ["words", "pos", "ner"] rows = [x.split("\t") for x in run("--format", "conllu") if x and not x.startswith("#")] assert [r[1] for r in rows] == [w["text"] for s in GOLDEN[0]["dependency_parse"] for w in s] def test_the_command_line_keeps_one_output_line_per_input_line(): # macOS report, bug 5: str.splitlines split the input at these characters too for sep in ("\u2028", "\u2029", "\x0b", "\x0c", "\x1c", "\x1d", "\x1e", "\x85"): code, out, err = cli(stdin=f"ก{sep}ข\nค\n") assert code == 0 and len(out) == 2, (repr(sep), out, err) code, out, _ = cli(stdin="ก\r\n\nค") assert code == 0 and out == ["ก", "", "ค"] def test_the_command_line_refuses_options_its_task_does_not_use(): # B11: --unit and --nbest were ignored by the tasks that do not use them for args in (["--task", "ner", "--unit", "long"], ["--task", "pos", "--nbest", "3"], ["--task", "dep", "--sep", ","], ["--task", "sentences", "--tagset", "orchid"], ["--task", "all", "--unit", "long"], ["--format", "conllu", "--task", "pos"], ["--task", "parse"], ["--threads", "0"]): code, _, err = cli(*args, "ตากลม") assert code == 2 and "error" in err, (args, code, err)