<img width="2318" height="1448" alt="image" src="https://github.com/user-attachments/assets/bca71d69-4972-420c-b14e-c8cf74a17de9" /> ## Summary Everything a knowledge base could not read, and the pieces it cut them into saying what they are. **Reading a PDF.** A PDF records glyphs at coordinates; whether they are a heading, a table cell or a running footer is inferred from how they look. There are now two readers. The geometric one infers structure from type size and position and needs nothing but the file. The other asks deepdoc's models, ported into `raven/knowledge/parser/deepdoc`: a layout model that says what each region is, a detector and recognizer that read a page carrying no text at all, and a table-structure model that rebuilds a grid from a picture of one. Detecting boxes around text the file already spells out exactly costs an inference pass per page to learn less, and recognising it costs accuracy. The layout graph answers with a shape its own postprocessing raises on, and its classes are DocLayout-YOLO's order rather than the list Both were established by running the model, and the label order is pinned by a test. **Tables go in as tables.** `<table>` is the only shape that keeps what a grid states -- which column a cell stood under, which cells are merged, which row is the header -- and it is the shape a model reads a table in, which is what these chunks are for. PDF, Word and PowerPoint all state their merges exactly, and they now survive as `colspan` and `rowspan`. The flat form this replaces had to repeat a header standing over two columns across both of them, because there was nowhere to record a span; it had no callers left afterwards and is gone. Two deviations from upstream, both about what the string is for: every cell's text is escaped, where upstream interpolates it raw and a cell holding a `<` produces markup that is no longer a table, and the span attributes are written only where there is a span, where upstream emits `<td >` for every ordinary cell. **A picture of where each chunk came from.** A chunk is a few hundred words with a page number on it, which is enough to cite and not enough to answer whether the parser read the page correctly. So every PDF chunk that knows where it sits carries one image: the regions it covers, cropped out of the rendered pages and stacked. here they are already structured in the parser's element spans, so the markers would only put text nobody wrote into the thing being embedded. The panel draws a chunk's tables as tables, parsed and rebuilt as elements rather than injected: a person can rewrite any piece from that same panel, so what comes back from the store is user input however it got there. **The page that reads them.** Upstream retired the knowledge page while this branch was out; it is rebuilt against the new architecture, and the half that never existed is the one a reader needs -- what a document actually became once it was cut and embedded. Documents sit in one-level folders and arrive by four routes: a file, a folder, a URL, a written note. Adding and indexing are two calls on the contract and nothing drains that queue on its own, so a page that stopped after the first left every upload saying Queued for good. Opening a file takes the whole page: the document on the left, the pieces the index holds of it on the right. The left half is the file drawn as its own pages rather than framed by the browser's PDF viewer, which reads where to open once and answers to nothing afterwards -- and which nothing can be drawn on. Pages are rendered once and kept, and the region a piece was cut from is washed over the page it came from, placed in fractions of the page so the picture's own scale never enters the arithmetic. Clicking a piece takes the file there; double-clicking opens it for rewriting. The pieces can be searched, filtered by state, turned on and off, deleted, rewritten and added to, one at a time or in a batch. Every one of those was already on the contract with no reader for it. A base's settings are back and fuller: how many pieces a search returns, how documents are cut, and how much prose comes with a table or a figure. The embedding model is a picker while the base holds no pieces and a stated fact once it does -- moving it then is the collection made again at the new width and every document re-cut, which is not a thing a panel does by being saved. **An agent can read them.** The retrieval engine was there and nothing could reach it: no agent had a tool that opened a library. A reader now points a conversation at bases from the composer, the way they pin a working directory, and the selection rides in the same place -- the session's metadata, bound around the turn. The tool takes a query and never a base. The scope is the reader's choice, so a model cannot reach material nobody offered it, and it is withheld where nothing was picked rather than offered and refused. A hit says which document and page it came from, because a hit a reader cannot place is a hit they cannot check -- and the passages are pressable in the transcript, walking into the base, the document, the folder it is filed under and then the piece. A citation a reader cannot follow is a claim they have to take on trust, and the whole point of searching their own material is that they can go and look. **The word segmenter and the resources.** `raven.core.Tokenizer` is Infinity's `rag_tokenizer`, ported: a forward and backward maximum match over a dictionary trie, with stemming and lemmatisation on the latin path. XGBoost is not carried over. None of the data lives in git -- the dictionary, the NLTK corpora and the ONNX graphs run to about a hundred megabytes, so `make fetch-resources` on an install and an optional Docker layer behind `RAVEN_RESOURCES` both point at one script. A checkout that could not reach the network still works, and every feature that reads this data says so when asked. ## Type - [ ] Fix - [x] Feature - [ ] Docs - [ ] CI / tooling - [ ] Refactor - [ ] Other ## Verification Run on macOS against Python 3.12, with the deepdoc weights fetched (the model tests skip without them): ``` uv run pytest 27450 passed, 111 skipped, 3 failed npm run test --prefix ui-web 3276 passed npm run test --prefix ui-tui 2106 passed npm run type-check --prefix ui-web clean (tsc) npm run lint --prefix ui-web clean (4 pre-existing hook warnings) make lint-python clean (ruff check + format) make lint-types clean (ty) make lint-imports 10 contracts kept, 0 broken make check-source-language clean make check-large-files clean make build-ui built, both boot snapshots match node ui-web/scripts/check-css.mjs clean node ui-web/scripts/check-class-namespace.mjs clean ``` The three Python failures are not this branch's and were each confirmed on the base alone: one asks a host without LibreOffice to refuse a render and this host has LibreOffice installed, and two simulation cases fail on an unmodified checkout of the base commit. The RPC contract was regenerated for both consumers and both match it (`npm run gen --prefix ui-web`, `npm run gen:rpc --prefix ui-tui`, then `gen:check`). The page's boot snapshots and region goldens were refreshed where the composer bar gained a button, and each records that button and nothing else. - [x] Relevant tests pass locally - [x] Relevant lint / type checks pass locally - [x] User-facing docs or screenshots are updated when needed ## Risk A PDF's tables, and a Word or PowerPoint file's, are now indexed as HTML rather than as header-prefixed lines. Chunk text changes shape for those documents, so a base indexed before this and searched after it holds both forms until its documents are reindexed; retrieval keeps working either way, because both forms are text. The same applies to how much prose a table or a figure carries with it: the setting now reaches as far as it says, where before it stopped at the nearest paragraph, so a chunk cut before this keeps the narrower context until its document is rebuilt. Rolling back is reverting the branch and reindexing. The deepdoc models are optional. An install that never ran `make fetch-resources` reads PDFs geometrically, exactly as before, and says so when the models are asked for by name. Nothing here reaches the network at request time. Chunk crops and rendered pages are written at index time and on first view, both under the state directory rather than in the repository, and both are deleted with their document. A page is immutable for the life of its document id, so the route serving them caches; the document route does not. All three routes take ids and no path, and the two image routes answer under the strictest sandbox in the tree. What an agent may search is the reader's choice and nothing else. The tool takes no base argument, so a model cannot name one, and it is absent from the schema entirely for a conversation that named none -- a lane nobody pointed at a base is unchanged by this branch. The bases a session carries are stored beside its working directory and travel no further. - [x] Security impact considered - [x] Backward compatibility considered - [x] Rollback path is clear for risky changes ## Related Issues N/A --------- Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
516 lines
21 KiB
Python
516 lines
21 KiB
Python
"""Segmentation itself, against a dictionary written by the test.
|
|
|
|
:mod:`tests.test_core_tokenizer` covers the same class against the real 8 MB
|
|
word list and skips whole when it has not been fetched -- which is every
|
|
machine but a developer's, and every CI run. So the segmenter, the part of this
|
|
package that exists because a keyword search over Chinese is noise without it,
|
|
was never exercised where it is actually checked.
|
|
|
|
`Tokenizer(user_dict=...)` takes any dictionary, so the cases here build a
|
|
twenty-word one and assert on segmentations that follow from it alone. Nothing
|
|
here needs the download.
|
|
|
|
Lemmatization is the one exception: WordNet is a corpus, fetched by the same
|
|
step, and the cases that reach it say so.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from raven.core import tokenizer as tok
|
|
|
|
#: word, frequency, part-of-speech tag -- the three space-separated fields the
|
|
#: published list uses. The frequencies only have to order the candidates: the
|
|
#: segmenter scores a split by the sum of its words' frequencies, so "database"
|
|
#: outranking "data" is what makes the longer word win.
|
|
_WORDS = [
|
|
("\u6570\u636e", 500, "n"), # data
|
|
("\u6570\u636e\u5e93", 900, "n"), # database
|
|
("\u7ba1\u7406", 400, "n"), # management
|
|
("\u7cfb\u7edf", 400, "n"), # system
|
|
("\u7ba1\u7406\u7cfb\u7edf", 800, "n"), # management system
|
|
("\u5317\u4eac", 600, "ns"), # Beijing
|
|
("\u5927\u5b66", 600, "n"), # university
|
|
("hello", 300, "n"),
|
|
("world", 300, "n"),
|
|
("running", 200, "v"),
|
|
]
|
|
|
|
|
|
def _corpora_available() -> bool:
|
|
"""Whether the latin half of the tokenizer has what it reads.
|
|
|
|
Two corpora, both from the same fetch step: the sentence splitter
|
|
`word_tokenize` loads, and the WordNet data the lemmatizer reads. Any line
|
|
carrying latin text goes through both, so a case with so much as an English
|
|
word in it needs them; a line of Chinese alone is segmented from the
|
|
dictionary and needs neither.
|
|
|
|
Asked after this module's import of `raven.core.tokenizer`, which is what
|
|
puts the package's own `res/nltk_data` on nltk's search path.
|
|
"""
|
|
try:
|
|
import nltk
|
|
from nltk.corpus import wordnet
|
|
|
|
wordnet.ensure_loaded()
|
|
nltk.data.find("tokenizers/punkt_tab")
|
|
except Exception:
|
|
return False
|
|
return True
|
|
|
|
|
|
needs_corpora = pytest.mark.skipif(not _corpora_available(), reason="the nltk corpora have not been fetched")
|
|
|
|
|
|
@pytest.fixture
|
|
def dictionary(tmp_path: Path) -> Path:
|
|
path = tmp_path / "mini.txt"
|
|
path.write_text("\n".join(f"{word} {freq} {tag}" for word, freq, tag in _WORDS), encoding="utf-8")
|
|
return path
|
|
|
|
|
|
@pytest.fixture
|
|
def segmenter(dictionary: Path) -> tok.Tokenizer:
|
|
return tok.Tokenizer(user_dict=str(dictionary))
|
|
|
|
|
|
class TestBuildingFromADictionary:
|
|
def test_a_dictionary_file_builds_a_working_segmenter(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.tokenize("\u6570\u636e\u5e93").split() == ["\u6570\u636e\u5e93"]
|
|
|
|
def test_the_trie_is_cached_beside_the_dictionary(self, segmenter: tok.Tokenizer, dictionary: Path) -> None:
|
|
"""Six seconds of trie building, spent once. The cache is what a second
|
|
process loads instead of reading the word list again."""
|
|
assert dictionary.with_suffix(".txt.trie").is_file()
|
|
|
|
def test_a_second_segmenter_loads_the_cache_rather_than_rebuilding(self, dictionary: Path) -> None:
|
|
tok.Tokenizer(user_dict=str(dictionary))
|
|
|
|
again = tok.Tokenizer(user_dict=str(dictionary))
|
|
|
|
assert again.tokenize("\u6570\u636e\u5e93").split() == ["\u6570\u636e\u5e93"]
|
|
|
|
@needs_corpora
|
|
def test_a_missing_user_dictionary_falls_back_to_the_shipped_one(self, tmp_path: Path) -> None:
|
|
"""A path that is not there is a misconfiguration, not a reason to
|
|
refuse to segment -- but with no shipped dictionary either, the error
|
|
names the command that fetches it."""
|
|
absent = str(tmp_path / "nowhere.txt")
|
|
|
|
if tok.available():
|
|
assert tok.Tokenizer(user_dict=absent).tokenize("hello")
|
|
else:
|
|
with pytest.raises(tok.DictionaryMissingError):
|
|
tok.Tokenizer(user_dict=absent)
|
|
|
|
def test_a_user_dictionary_can_be_added_to_a_built_segmenter(
|
|
self, segmenter: tok.Tokenizer, tmp_path: Path
|
|
) -> None:
|
|
extra = tmp_path / "extra.txt"
|
|
extra.write_text("\u4eba\u5de5\u667a\u80fd 900 n\n", encoding="utf-8")
|
|
|
|
segmenter.add_user_dict(str(extra))
|
|
|
|
assert "\u4eba\u5de5\u667a\u80fd" in segmenter.tokenize("\u4eba\u5de5\u667a\u80fd")
|
|
|
|
def test_a_user_dictionary_can_replace_the_loaded_one(self, segmenter: tok.Tokenizer, tmp_path: Path) -> None:
|
|
other = tmp_path / "other.txt"
|
|
other.write_text("\u4e0a\u6d77 900 ns\n", encoding="utf-8")
|
|
|
|
segmenter.load_user_dict(str(other))
|
|
|
|
assert "\u4e0a\u6d77" in segmenter.tokenize("\u4e0a\u6d77")
|
|
|
|
def test_an_unreadable_dictionary_does_not_take_the_process_down(
|
|
self, segmenter: tok.Tokenizer, tmp_path: Path
|
|
) -> None:
|
|
"""A library that exits on a bad file takes the gateway with it. The
|
|
original calls `exit(1)` here."""
|
|
segmenter.add_user_dict(str(tmp_path / "does-not-exist.txt"))
|
|
|
|
assert segmenter.tokenize("\u6570\u636e\u5e93")
|
|
|
|
|
|
class TestKeys:
|
|
"""How a word is stored, forwards and backwards.
|
|
|
|
The backward key is what the right-to-left pass looks up, and it carries a
|
|
`DD` prefix so the two directions cannot collide in one trie.
|
|
"""
|
|
|
|
def test_a_word_keys_on_its_own_lowercased_bytes(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.key_("Hello") == segmenter.key_("hello")
|
|
|
|
def test_the_reverse_key_is_distinct_from_the_forward_one(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.rkey_("hello") != segmenter.key_("hello")
|
|
|
|
def test_the_reverse_key_reverses_the_word(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.rkey_("ab") == segmenter.rkey_("ab")
|
|
assert segmenter.rkey_("ab") != segmenter.rkey_("ba")
|
|
|
|
|
|
class TestSegmentation:
|
|
"""Where the word boundaries fall, given the dictionary above."""
|
|
|
|
def test_the_longer_word_wins_when_the_dictionary_prefers_it(self, segmenter: tok.Tokenizer) -> None:
|
|
""" "database" is one word, not "data" plus a character. This is the
|
|
whole job: the frequencies decide, and a wrong comparison produces a
|
|
split that still looks like words."""
|
|
assert segmenter.tokenize("\u6570\u636e\u5e93").split() == ["\u6570\u636e\u5e93"]
|
|
|
|
def test_a_run_of_words_splits_at_every_boundary(self, segmenter: tok.Tokenizer) -> None:
|
|
out = segmenter.tokenize("\u6570\u636e\u5e93\u7ba1\u7406\u7cfb\u7edf").split()
|
|
|
|
assert "\u6570\u636e\u5e93" in out
|
|
assert out != ["\u6570\u636e\u5e93\u7ba1\u7406\u7cfb\u7edf"], "it did split"
|
|
|
|
def test_a_word_the_dictionary_does_not_have_still_comes_back(self, segmenter: tok.Tokenizer) -> None:
|
|
"""Unknown text is not dropped: it falls through per character, which
|
|
is the behaviour an absent dictionary gives for everything."""
|
|
assert "\u55b5" in segmenter.tokenize("\u55b5")
|
|
|
|
def test_known_words_survive_unknown_neighbours(self, segmenter: tok.Tokenizer) -> None:
|
|
assert "\u5317\u4eac" in segmenter.tokenize("\u55b5\u5317\u4eac\u55b5")
|
|
|
|
def test_empty_text_segments_to_nothing(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.tokenize("").strip() == ""
|
|
|
|
def test_full_width_punctuation_is_narrowed_first(self, segmenter: tok.Tokenizer) -> None:
|
|
"""A full-width comma is the same comma; left as-is it is a character
|
|
the dictionary has never seen, sitting inside a word."""
|
|
assert segmenter._strQ2B("\uff21\uff22\uff0c") == "AB,"
|
|
|
|
def test_a_full_width_space_becomes_an_ordinary_one(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter._strQ2B("\u3000") == " "
|
|
|
|
def test_a_character_with_no_half_width_form_is_left_alone(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter._strQ2B("\u6570") == "\u6570"
|
|
|
|
def test_traditional_characters_are_folded_to_simplified(self, segmenter: tok.Tokenizer) -> None:
|
|
"""The dictionary is simplified; without this every traditional page
|
|
misses every word in it."""
|
|
assert segmenter._tradi2simp("\u8cc7\u6599") == "\u8d44\u6599"
|
|
|
|
def test_a_traditional_page_segments_through_the_simplified_dictionary(self, segmenter: tok.Tokenizer) -> None:
|
|
assert "\u6570\u636e\u5e93" in segmenter.tokenize("\u6578\u64da\u5eab")
|
|
|
|
|
|
class TestFineGrainedTokenize:
|
|
"""The second pass: the long words split again, so a search for the part
|
|
still finds the whole."""
|
|
|
|
def test_a_compound_is_split_into_its_parts(self, segmenter: tok.Tokenizer) -> None:
|
|
out = segmenter.fine_grained_tokenize(segmenter.tokenize("\u6570\u636e\u5e93"))
|
|
|
|
assert "\u6570\u636e" in out
|
|
|
|
def test_text_with_no_compounds_passes_through(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.fine_grained_tokenize("\u5317\u4eac").strip() == "\u5317\u4eac"
|
|
|
|
def test_empty_input_stays_empty(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.fine_grained_tokenize("").strip() == ""
|
|
|
|
|
|
class TestFrequencyAndTag:
|
|
def test_a_known_word_reports_the_dictionary_frequency(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.freq("\u6570\u636e\u5e93") > 0
|
|
|
|
def test_an_unknown_word_reports_nothing(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.freq("\u55b5\u55b5\u55b5") == 0
|
|
|
|
def test_a_known_word_reports_its_part_of_speech(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.tag("\u5317\u4eac") == "ns"
|
|
|
|
def test_an_unknown_word_has_no_part_of_speech(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.tag("\u55b5\u55b5\u55b5") == ""
|
|
|
|
|
|
class TestLanguages:
|
|
def test_a_snowball_language_switches_the_stemmer(self, segmenter: tok.Tokenizer) -> None:
|
|
segmenter.set_language("Dutch")
|
|
|
|
assert segmenter._use_lemmatizer is False, "WordNet is English only"
|
|
|
|
def test_english_turns_the_lemmatizer_back_on(self, segmenter: tok.Tokenizer) -> None:
|
|
segmenter.set_language("Dutch")
|
|
|
|
segmenter.set_language("English")
|
|
|
|
assert segmenter._use_lemmatizer is True
|
|
|
|
def test_a_language_with_no_stemmer_keeps_the_defaults(self, segmenter: tok.Tokenizer) -> None:
|
|
"""Chinese is segmented by dictionary, not stemmed."""
|
|
segmenter.set_language("Chinese")
|
|
|
|
assert segmenter.tokenize("\u6570\u636e\u5e93")
|
|
|
|
def test_the_name_is_read_case_insensitively(self, segmenter: tok.Tokenizer) -> None:
|
|
segmenter.set_language(" dUtCh ")
|
|
|
|
assert segmenter._use_lemmatizer is False
|
|
|
|
@pytest.mark.parametrize("language", ["Czech", "Slovak"])
|
|
def test_a_diacritic_folding_language_folds_rather_than_stems(
|
|
self, segmenter: tok.Tokenizer, language: str
|
|
) -> None:
|
|
"""Neither has a Snowball stemmer, and the split pattern keeps only
|
|
ASCII letter runs whole -- so an accented word would be fragmented
|
|
before it was indexed."""
|
|
segmenter.set_language(language)
|
|
|
|
assert segmenter._fold_diacritics is True
|
|
assert segmenter._normalize_token("running") == "running", "left unstemmed"
|
|
|
|
@needs_corpora
|
|
def test_a_folding_language_strips_the_accents_from_its_words(self, segmenter: tok.Tokenizer) -> None:
|
|
segmenter.set_language("Czech")
|
|
|
|
assert "skola" in segmenter.tokenize("\u0161kola")
|
|
|
|
@pytest.mark.xfail(
|
|
reason="turkish is the one entry in the snowball map nltk has no stemmer for, so this raises ValueError",
|
|
raises=ValueError,
|
|
strict=True,
|
|
)
|
|
def test_turkish_is_claimed_by_the_snowball_map_but_has_no_stemmer(self, segmenter: tok.Tokenizer) -> None:
|
|
"""Pinned as a known defect rather than left uncovered.
|
|
|
|
Turkish is neither folded nor stemmable: it sits in the Snowball map,
|
|
`set_language` therefore skips the folding branch, and `SnowballStemmer`
|
|
then refuses the name. It belongs with czech and slovak, which are
|
|
exactly the other languages with accented letters and no stemmer.
|
|
"""
|
|
segmenter.set_language("Turkish")
|
|
|
|
|
|
class TestDiacritics:
|
|
def test_an_accented_letter_folds_to_its_base(self) -> None:
|
|
assert tok.fold_diacritics("\u00e9cole") == "ecole"
|
|
|
|
def test_an_unaccented_word_is_unchanged(self) -> None:
|
|
assert tok.fold_diacritics("school") == "school"
|
|
|
|
def test_a_character_with_no_base_is_left_alone(self) -> None:
|
|
assert tok.fold_diacritics("\u6570") == "\u6570"
|
|
|
|
def test_the_turkish_dotless_i_is_handled(self) -> None:
|
|
assert tok.fold_diacritics("\u0131") in {"i", "\u0131"}
|
|
|
|
|
|
class TestIsChinese:
|
|
def test_han_characters_are_chinese(self) -> None:
|
|
assert tok.is_chinese("\u6570")
|
|
|
|
def test_latin_is_not(self) -> None:
|
|
assert not tok.is_chinese("a")
|
|
|
|
def test_a_digit_is_not(self) -> None:
|
|
assert not tok.is_chinese("1")
|
|
|
|
|
|
class TestEnglishNormalisation:
|
|
@needs_corpora
|
|
def test_an_english_word_is_lemmatised_then_stemmed(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.tokenize("running").strip() == "run"
|
|
|
|
@needs_corpora
|
|
def test_case_is_folded(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.tokenize("Hello World").split() == ["hello", "world"]
|
|
|
|
def test_a_non_alphabetic_token_is_left_alone(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter._normalize_token("2024") == "2024"
|
|
|
|
def test_stemming_without_the_lemmatizer_still_works(self, segmenter: tok.Tokenizer) -> None:
|
|
"""The path every non-English Snowball language takes, and the one an
|
|
install without the corpora falls back to."""
|
|
segmenter._use_lemmatizer = False
|
|
|
|
assert segmenter._normalize_token("running") == "run"
|
|
|
|
|
|
class TestMixedScripts:
|
|
@needs_corpora
|
|
def test_a_line_of_both_scripts_splits_at_the_script_boundary(self, segmenter: tok.Tokenizer) -> None:
|
|
out = segmenter.tokenize("\u5317\u4eac hello").split()
|
|
|
|
assert "\u5317\u4eac" in out
|
|
assert "hello" in out
|
|
|
|
|
|
class TestTheSearch:
|
|
"""`dfs_` enumerates the ways a run of characters can be cut.
|
|
|
|
It is the expensive half of segmentation, which is why it carries a memo, a
|
|
depth ceiling and a shortcut for repeated characters -- a page of one
|
|
character repeated is otherwise exponential, and the three guards are the
|
|
kind that go wrong quietly: the search still answers, with fewer splits.
|
|
"""
|
|
|
|
def test_it_finds_the_split_the_dictionary_knows(self, segmenter: tok.Tokenizer) -> None:
|
|
found: list = []
|
|
|
|
segmenter.dfs_("\u6570\u636e\u5e93", 0, [], found)
|
|
|
|
assert found, "at least one way to cut it"
|
|
assert any(["\u6570\u636e\u5e93"] == [tk for tk, _ in way] for way in found)
|
|
|
|
def test_it_finds_more_than_one_way_where_there_is_more_than_one(self, segmenter: tok.Tokenizer) -> None:
|
|
"""`database` is also `data` plus a character, and the scoring below is
|
|
what chooses between them."""
|
|
found: list = []
|
|
|
|
segmenter.dfs_("\u6570\u636e\u5e93", 0, [], found)
|
|
|
|
assert len(found) > 1
|
|
|
|
def test_a_long_run_of_one_character_does_not_explode(self, segmenter: tok.Tokenizer) -> None:
|
|
"""Five of the same character turns on the repetition shortcut. Without
|
|
it the search walks every partition of the run."""
|
|
found: list = []
|
|
|
|
segmenter.dfs_("\u55b5" * 40, 0, [], found)
|
|
|
|
assert found
|
|
assert len(found) < 100, "the shortcut kept the search bounded"
|
|
|
|
def test_a_long_mixed_run_stops_at_the_depth_ceiling(self, segmenter: tok.Tokenizer) -> None:
|
|
"""Past the ceiling the rest of the run is taken whole rather than
|
|
split, which is a worse segmentation and a finite one."""
|
|
found: list = []
|
|
|
|
segmenter.dfs_("\u5317\u4eac\u5927\u5b66" * 12, 0, [], found)
|
|
|
|
assert found
|
|
assert all(way for way in found)
|
|
|
|
def test_an_exhausted_run_answers_with_what_it_has(self, segmenter: tok.Tokenizer) -> None:
|
|
found: list = []
|
|
|
|
segmenter.dfs_("", 0, [], found)
|
|
|
|
assert found == [[]]
|
|
|
|
|
|
class TestScoring:
|
|
"""What makes one cut better than another: total frequency, a bonus for
|
|
words longer than a character, and a penalty for using many tokens."""
|
|
|
|
def test_a_known_word_scores_above_the_same_characters_apart(self, segmenter: tok.Tokenizer) -> None:
|
|
whole = [("\u6570\u636e\u5e93", (9, "n"))]
|
|
apart = [("\u6570", (0, "")), ("\u636e", (0, "")), ("\u5e93", (0, ""))]
|
|
|
|
_tks, whole_score = segmenter.score_(whole)
|
|
_tks, apart_score = segmenter.score_(apart)
|
|
|
|
assert whole_score > apart_score
|
|
|
|
def test_fewer_tokens_score_better_at_equal_frequency(self, segmenter: tok.Tokenizer) -> None:
|
|
one = [("ab", (0, ""))]
|
|
two = [("a", (0, "")), ("b", (0, ""))]
|
|
|
|
assert segmenter.score_(one)[1] > segmenter.score_(two)[1]
|
|
|
|
def test_the_tokens_come_back_with_the_score(self, segmenter: tok.Tokenizer) -> None:
|
|
tks, _score = segmenter.score_([("a", (0, "")), ("b", (0, ""))])
|
|
|
|
assert tks == ["a", "b"]
|
|
|
|
def test_the_best_cut_sorts_first(self, segmenter: tok.Tokenizer) -> None:
|
|
ways = [
|
|
[("\u6570", (0, "")), ("\u636e", (0, "")), ("\u5e93", (0, ""))],
|
|
[("\u6570\u636e\u5e93", (9, "n"))],
|
|
]
|
|
|
|
ranked = segmenter._sort_tokens(ways)
|
|
|
|
assert ranked[0][0] == ["\u6570\u636e\u5e93"]
|
|
|
|
|
|
class TestMaximumMatching:
|
|
"""The two single-pass fallbacks, left to right and right to left.
|
|
|
|
They disagree on exactly the text the search is for, which is why both run
|
|
and the better-scoring answer wins.
|
|
"""
|
|
|
|
def test_the_forward_pass_takes_the_longest_word_it_can(self, segmenter: tok.Tokenizer) -> None:
|
|
tks, _score = segmenter._max_forward("\u6570\u636e\u5e93")
|
|
|
|
assert tks == ["\u6570\u636e\u5e93"]
|
|
|
|
def test_the_backward_pass_agrees_where_there_is_one_answer(self, segmenter: tok.Tokenizer) -> None:
|
|
tks, _score = segmenter._max_backward("\u6570\u636e\u5e93")
|
|
|
|
assert tks == ["\u6570\u636e\u5e93"]
|
|
|
|
def test_the_forward_pass_falls_through_unknown_characters(self, segmenter: tok.Tokenizer) -> None:
|
|
tks, _score = segmenter._max_forward("\u55b5\u55b5")
|
|
|
|
assert tks == ["\u55b5", "\u55b5"]
|
|
|
|
def test_the_backward_pass_falls_through_them_too(self, segmenter: tok.Tokenizer) -> None:
|
|
tks, _score = segmenter._max_backward("\u55b5\u55b5")
|
|
|
|
assert tks == ["\u55b5", "\u55b5"]
|
|
|
|
def test_both_passes_keep_a_known_word_beside_an_unknown_one(self, segmenter: tok.Tokenizer) -> None:
|
|
for pass_ in (segmenter._max_forward, segmenter._max_backward):
|
|
tks, _score = pass_("\u55b5\u5317\u4eac")
|
|
|
|
assert "\u5317\u4eac" in tks
|
|
|
|
def test_an_empty_line_matches_nothing(self, segmenter: tok.Tokenizer) -> None:
|
|
"""`score_` divides by the token count, so an empty line is the one
|
|
input that could raise rather than answer."""
|
|
for pass_ in (segmenter._max_forward, segmenter._max_backward):
|
|
with pytest.raises(ZeroDivisionError):
|
|
pass_("")
|
|
|
|
|
|
class TestMerge:
|
|
"""Putting back a split the punctuation pattern made inside a word."""
|
|
|
|
def test_a_word_the_dictionary_knows_is_rejoined(self, segmenter: tok.Tokenizer, tmp_path) -> None:
|
|
extra = tmp_path / "dotted.txt"
|
|
extra.write_text("a.b 900 n\n", encoding="utf-8")
|
|
segmenter.add_user_dict(str(extra))
|
|
|
|
assert segmenter.merge_("a . b") == "a.b"
|
|
|
|
def test_runs_the_dictionary_does_not_know_are_left_apart(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.merge_("\u5317\u4eac \u5927\u5b66") == "\u5317\u4eac \u5927\u5b66"
|
|
|
|
def test_repeated_spaces_are_collapsed(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.merge_("\u5317\u4eac \u5927\u5b66") == "\u5317\u4eac \u5927\u5b66"
|
|
|
|
def test_an_empty_line_merges_to_nothing(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.merge_("") == ""
|
|
|
|
|
|
class TestFineGrainedPaths:
|
|
def test_a_latin_line_is_split_on_slashes_rather_than_searched(self, segmenter: tok.Tokenizer) -> None:
|
|
"""Under a fifth Chinese, the second pass is not segmentation at all --
|
|
it is the one split the first pass leaves joined."""
|
|
assert segmenter.fine_grained_tokenize("and/or").split() == ["and", "or"]
|
|
|
|
def test_a_short_token_is_left_whole(self, segmenter: tok.Tokenizer) -> None:
|
|
assert segmenter.fine_grained_tokenize("\u5317\u4eac").strip() == "\u5317\u4eac"
|
|
|
|
def test_a_number_is_left_whole(self, segmenter: tok.Tokenizer) -> None:
|
|
"""`1,234.56` is one thing; cutting it is how a figure stops being
|
|
findable."""
|
|
out = segmenter.fine_grained_tokenize("1,234.56 \u6570\u636e\u5e93 \u5317\u4eac")
|
|
|
|
assert "1,234.56" in out.split()
|
|
|
|
def test_a_very_long_token_is_not_searched(self, segmenter: tok.Tokenizer) -> None:
|
|
"""Past ten characters the search is skipped: it is the expensive half,
|
|
and a run that long is rarely one word."""
|
|
long = "\u6570\u636e\u5e93" * 5
|
|
|
|
assert long in segmenter.fine_grained_tokenize(long).split()
|