<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>
533 lines
21 KiB
Python
533 lines
21 KiB
Python
"""Fetching the files that cannot live in git, without fetching anything.
|
|
|
|
Three hosts and about 110 MB, so every case here supplies the download. What is
|
|
asserted is the part that is ours: where the files land, what counts as already
|
|
present, that a partial download cannot be mistaken for a whole one, and that
|
|
`--optional` really does let an install finish when a host is unreachable --
|
|
which is the contract install.sh leans on.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
from raven import resources
|
|
|
|
|
|
@pytest.fixture
|
|
def res(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
|
"""Point both resource trees at a temporary directory.
|
|
|
|
The real ones live inside the installed package; a test that wrote there
|
|
would leave 110 MB behind, or worse, a truncated file the next run trusts.
|
|
"""
|
|
core, knowledge = tmp_path / "core", tmp_path / "knowledge"
|
|
monkeypatch.setattr(resources, "CORE_RES", core)
|
|
monkeypatch.setattr(resources, "KNOWLEDGE_RES", knowledge)
|
|
monkeypatch.setattr(resources, "NLTK_DATA", core / "nltk_data")
|
|
return tmp_path
|
|
|
|
|
|
class TestWhereTheFilesGo:
|
|
def test_the_destinations_are_derived_from_the_package(self) -> None:
|
|
"""Not from the repository root, which a wheel install does not have.
|
|
This is what makes one call correct for both installs."""
|
|
assert resources.CORE_RES == resources.PACKAGE / "core" / "res"
|
|
assert resources.KNOWLEDGE_RES == resources.PACKAGE / "knowledge" / "res"
|
|
|
|
def test_a_resource_knows_its_own_path(self) -> None:
|
|
item = resources.Resource("huqie.txt", Path("/tmp/x"), "the word dictionary")
|
|
|
|
assert item.path == Path("/tmp/x/huqie.txt")
|
|
|
|
def test_a_resource_can_be_saved_under_another_name(self) -> None:
|
|
"""The publisher's name and the reader's are not always the same."""
|
|
item = resources.Resource("published.bin", Path("/tmp/x"), "a model", saved_as="expected.onnx")
|
|
|
|
assert item.path == Path("/tmp/x/expected.onnx")
|
|
|
|
|
|
class TestPresence:
|
|
"""What counts as already here, so a re-run is cheap and a truncated file
|
|
is not trusted."""
|
|
|
|
def test_a_file_of_the_published_size_is_present(self, tmp_path: Path) -> None:
|
|
path = tmp_path / "f.bin"
|
|
path.write_bytes(b"x" * 10)
|
|
|
|
assert resources._present(resources.Resource("f.bin", tmp_path, "a file"), 10)
|
|
|
|
def test_a_file_that_is_not_there_is_not_present(self, tmp_path: Path) -> None:
|
|
assert not resources._present(resources.Resource("f.bin", tmp_path, "a file"), 10)
|
|
|
|
def test_a_short_file_is_refetched(self, tmp_path: Path) -> None:
|
|
"""The failure this guards is a connection dropped mid-file, which
|
|
leaves a file of the right name and the wrong length."""
|
|
path = tmp_path / "f.bin"
|
|
path.write_bytes(b"x" * 3)
|
|
|
|
assert not resources._present(resources.Resource("f.bin", tmp_path, "a file"), 10)
|
|
|
|
def test_a_file_is_accepted_when_the_published_size_is_unknown(self, tmp_path: Path) -> None:
|
|
"""The index is a convenience. Without it, a file that exists is taken
|
|
on trust rather than downloaded on every run."""
|
|
path = tmp_path / "f.bin"
|
|
path.write_bytes(b"x")
|
|
|
|
assert resources._present(resources.Resource("f.bin", tmp_path, "a file"), None)
|
|
|
|
|
|
class TestHumanSizes:
|
|
@pytest.mark.parametrize(
|
|
("size", "shown"),
|
|
[(0, "0B"), (512, "512B"), (1024, "1.0KB"), (1536, "1.5KB"), (1024 * 1024, "1.0MB")],
|
|
)
|
|
def test_sizes_read_as_a_person_would_write_them(self, size: int, shown: str) -> None:
|
|
assert resources._human(size) == shown
|
|
|
|
|
|
class _FakeResponse:
|
|
def __init__(self, chunks: list[bytes]) -> None:
|
|
self._chunks = chunks
|
|
self.headers = {"content-length": str(sum(len(c) for c in chunks))}
|
|
|
|
def raise_for_status(self) -> None:
|
|
return None
|
|
|
|
def iter_bytes(self, _size: int):
|
|
yield from self._chunks
|
|
|
|
def __enter__(self) -> "_FakeResponse":
|
|
return self
|
|
|
|
def __exit__(self, *_exc: object) -> None:
|
|
return None
|
|
|
|
|
|
class _FakeClient:
|
|
"""Stands in for httpx, recording what was asked for."""
|
|
|
|
def __init__(self, chunks: list[bytes], *, fail: bool = False) -> None:
|
|
self.chunks = chunks
|
|
self.fail = fail
|
|
self.urls: list[str] = []
|
|
|
|
def __enter__(self) -> "_FakeClient":
|
|
return self
|
|
|
|
def __exit__(self, *_exc: object) -> None:
|
|
return None
|
|
|
|
def head(self, url: str):
|
|
self.urls.append(url)
|
|
return SimpleNamespace(headers={"content-length": str(sum(len(c) for c in self.chunks))})
|
|
|
|
def stream(self, _method: str, url: str):
|
|
self.urls.append(url)
|
|
if self.fail:
|
|
raise RuntimeError("the host is unreachable")
|
|
return _FakeResponse(self.chunks)
|
|
|
|
|
|
class TestFetchDictionary:
|
|
@staticmethod
|
|
def _install(monkeypatch: pytest.MonkeyPatch, client: _FakeClient) -> None:
|
|
import httpx
|
|
|
|
monkeypatch.setattr(httpx, "Client", lambda **_kw: client)
|
|
|
|
def test_a_download_lands_at_the_readers_path(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
self._install(monkeypatch, _FakeClient([b"abc", b"def"]))
|
|
item = resources.Resource("huqie.txt", resources.CORE_RES, "the word dictionary")
|
|
|
|
written = resources.fetch_dictionary((item,), force=False)
|
|
|
|
assert written == 1
|
|
assert item.path.read_bytes() == b"abcdef"
|
|
|
|
def test_a_file_already_here_is_left_alone(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
client = _FakeClient([b"abcdef"])
|
|
self._install(monkeypatch, client)
|
|
item = resources.Resource("huqie.txt", resources.CORE_RES, "the word dictionary")
|
|
item.into.mkdir(parents=True)
|
|
item.path.write_bytes(b"abcdef")
|
|
|
|
assert resources.fetch_dictionary((item,), force=False) == 0
|
|
|
|
def test_force_downloads_over_a_file_that_is_already_here(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
self._install(monkeypatch, _FakeClient([b"new"]))
|
|
item = resources.Resource("huqie.txt", resources.CORE_RES, "the word dictionary")
|
|
item.into.mkdir(parents=True)
|
|
item.path.write_bytes(b"old")
|
|
|
|
assert resources.fetch_dictionary((item,), force=True) == 1
|
|
assert item.path.read_bytes() == b"new"
|
|
|
|
def test_nothing_is_left_behind_when_the_download_fails(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""A half-written file under the real name is one every later run
|
|
treats as present, so the download goes to a staging name first."""
|
|
self._install(monkeypatch, _FakeClient([], fail=True))
|
|
item = resources.Resource("huqie.txt", resources.CORE_RES, "the word dictionary")
|
|
|
|
with pytest.raises(RuntimeError):
|
|
resources.fetch_dictionary((item,), force=False)
|
|
|
|
assert not item.path.exists()
|
|
|
|
def test_it_asks_the_publisher_for_the_file_by_name(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
client = _FakeClient([b"x"])
|
|
self._install(monkeypatch, client)
|
|
item = resources.Resource("huqie.txt", resources.CORE_RES, "the word dictionary")
|
|
|
|
resources.fetch_dictionary((item,), force=False)
|
|
|
|
assert any(url.endswith("/huqie.txt") for url in client.urls)
|
|
|
|
|
|
class TestFetchDeepdoc:
|
|
@staticmethod
|
|
def _install(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, *, sizes: dict[str, int] | None = None):
|
|
cached = tmp_path / "hf-cache"
|
|
cached.mkdir(exist_ok=True)
|
|
calls: list[str] = []
|
|
|
|
def fake_download(*, repo_id: str, filename: str) -> str:
|
|
calls.append(filename)
|
|
blob = cached / filename
|
|
blob.write_bytes(b"m" * (sizes or {}).get(filename, 4))
|
|
return str(blob)
|
|
|
|
def fake_info(_repo: str, files_metadata: bool = False):
|
|
siblings = [SimpleNamespace(rfilename=name, size=size) for name, size in (sizes or {}).items()]
|
|
return SimpleNamespace(siblings=siblings)
|
|
|
|
import huggingface_hub
|
|
|
|
monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_download)
|
|
monkeypatch.setattr(huggingface_hub, "model_info", fake_info)
|
|
return calls
|
|
|
|
def test_a_model_is_copied_out_of_the_cache(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Copied rather than symlinked: an image build throws the cache layer
|
|
away, and a link into a directory that is gone is worse than no file."""
|
|
self._install(monkeypatch, res, sizes={"det.onnx": 4})
|
|
item = resources.Resource("det.onnx", resources.KNOWLEDGE_RES, "text detection")
|
|
|
|
written = resources.fetch_deepdoc((item,), force=False)
|
|
|
|
assert written == 1
|
|
assert item.path.is_file() and not item.path.is_symlink()
|
|
|
|
def test_a_model_already_here_is_left_alone(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
calls = self._install(monkeypatch, res, sizes={"det.onnx": 4})
|
|
item = resources.Resource("det.onnx", resources.KNOWLEDGE_RES, "text detection")
|
|
item.into.mkdir(parents=True)
|
|
item.path.write_bytes(b"m" * 4)
|
|
|
|
assert resources.fetch_deepdoc((item,), force=False) == 0
|
|
assert calls == []
|
|
|
|
def test_an_unreadable_index_does_not_stop_the_download(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""The published sizes are a convenience; without them the files are
|
|
fetched anyway rather than the whole step failing."""
|
|
import huggingface_hub
|
|
|
|
self._install(monkeypatch, res, sizes={"det.onnx": 4})
|
|
monkeypatch.setattr(
|
|
huggingface_hub,
|
|
"model_info",
|
|
lambda *_a, **_kw: (_ for _ in ()).throw(RuntimeError("no index")),
|
|
)
|
|
item = resources.Resource("det.onnx", resources.KNOWLEDGE_RES, "text detection")
|
|
|
|
assert resources.fetch_deepdoc((item,), force=False) == 1
|
|
|
|
|
|
class TestMain:
|
|
"""The entry point install.sh calls, and the `--optional` contract."""
|
|
|
|
@staticmethod
|
|
def _plan(monkeypatch: pytest.MonkeyPatch) -> list[str]:
|
|
ran: list[str] = []
|
|
|
|
def record(name: str):
|
|
def step(_resources=(), *, force=False):
|
|
ran.append(name)
|
|
return 0
|
|
|
|
return step
|
|
|
|
monkeypatch.setattr(resources, "fetch_dictionary", record("dictionary"))
|
|
monkeypatch.setattr(resources, "fetch_nltk", lambda *, force=False: ran.append("nltk") or 0)
|
|
monkeypatch.setattr(resources, "warm_dictionary", lambda: ran.append("warm"))
|
|
monkeypatch.setattr(resources, "fetch_deepdoc", record("deepdoc"))
|
|
return ran
|
|
|
|
def test_it_fetches_both_sets_by_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
ran = self._plan(monkeypatch)
|
|
|
|
assert resources.main([]) == 0
|
|
assert "dictionary" in ran and "deepdoc" in ran
|
|
|
|
def test_only_dictionary_leaves_the_models_alone(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
ran = self._plan(monkeypatch)
|
|
|
|
assert resources.main(["--only", "dictionary"]) == 0
|
|
assert "deepdoc" not in ran
|
|
|
|
def test_only_deepdoc_leaves_the_dictionary_alone(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
ran = self._plan(monkeypatch)
|
|
|
|
assert resources.main(["--only", "deepdoc"]) == 0
|
|
assert "dictionary" not in ran and "nltk" not in ran
|
|
|
|
def test_a_failure_is_fatal_by_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
self._plan(monkeypatch)
|
|
monkeypatch.setattr(
|
|
resources,
|
|
"fetch_dictionary",
|
|
lambda *_a, **_kw: (_ for _ in ()).throw(RuntimeError("unreachable")),
|
|
)
|
|
|
|
assert resources.main([]) == 1
|
|
|
|
def test_optional_reports_the_failure_and_carries_on(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""The contract install.sh leans on: a host that cannot be reached
|
|
leaves a working raven rather than an install that stopped halfway."""
|
|
ran = self._plan(monkeypatch)
|
|
monkeypatch.setattr(
|
|
resources,
|
|
"fetch_dictionary",
|
|
lambda *_a, **_kw: (_ for _ in ()).throw(RuntimeError("unreachable")),
|
|
)
|
|
|
|
assert resources.main(["--optional"]) == 0
|
|
assert "deepdoc" in ran, "the step after the failure still ran"
|
|
|
|
def test_optional_survives_a_missing_library(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""The deepdoc half needs huggingface-hub, which is not a declared
|
|
dependency -- it arrives under litellm. If that ever changes, the fetch
|
|
reports itself missing rather than breaking the install."""
|
|
self._plan(monkeypatch)
|
|
monkeypatch.setattr(
|
|
resources,
|
|
"fetch_deepdoc",
|
|
lambda *_a, **_kw: (_ for _ in ()).throw(ImportError("no huggingface_hub")),
|
|
)
|
|
|
|
assert resources.main(["--optional"]) == 0
|
|
|
|
def test_the_extra_layout_models_are_opt_in(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Three more at 76 MB each, which nothing selects between yet."""
|
|
asked: list[tuple] = []
|
|
self._plan(monkeypatch)
|
|
monkeypatch.setattr(resources, "fetch_deepdoc", lambda res, *, force=False: asked.append(res) or 0)
|
|
|
|
resources.main([])
|
|
default = len(asked[0])
|
|
asked.clear()
|
|
resources.main(["--all-layouts"])
|
|
|
|
assert len(asked[0]) > default
|
|
|
|
|
|
class TestFetchNltk:
|
|
"""The corpora the latin half of the tokenizer reads, into the package
|
|
rather than a user's home -- so an install is self-contained and two
|
|
checkouts do not fight over one cache."""
|
|
|
|
@staticmethod
|
|
def _install(monkeypatch: pytest.MonkeyPatch, *, answer: bool = True) -> list[str]:
|
|
asked: list[str] = []
|
|
|
|
def download(corpus: str, download_dir: str = "", quiet: bool = False, halt_on_error: bool = True) -> bool:
|
|
asked.append(corpus)
|
|
return answer
|
|
|
|
import nltk
|
|
|
|
monkeypatch.setattr(nltk, "download", download)
|
|
return asked
|
|
|
|
def test_every_corpus_is_fetched(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
asked = self._install(monkeypatch)
|
|
|
|
written = resources.fetch_nltk(force=False)
|
|
|
|
assert written == len(resources.NLTK_CORPORA)
|
|
assert asked == list(resources.NLTK_CORPORA)
|
|
|
|
def test_the_order_puts_the_dependency_first(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""nltk gates wordnet behind omw-1.4, so a run that fetched wordnet
|
|
alone still raises the first time the lemmatizer is asked."""
|
|
asked = self._install(monkeypatch)
|
|
|
|
resources.fetch_nltk(force=False)
|
|
|
|
assert asked.index("omw-1.4") < asked.index("wordnet")
|
|
|
|
def test_a_corpus_unpacked_into_a_directory_counts_as_present(
|
|
self, res: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
asked = self._install(monkeypatch)
|
|
(resources.NLTK_DATA / "corpora" / "wordnet").mkdir(parents=True)
|
|
|
|
resources.fetch_nltk(force=False)
|
|
|
|
assert "wordnet" not in asked
|
|
|
|
def test_a_corpus_left_as_its_zip_counts_as_present_too(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""nltk unpacks some and leaves others zipped; checking only for the
|
|
directory re-downloaded wordnet on every run."""
|
|
asked = self._install(monkeypatch)
|
|
(resources.NLTK_DATA / "corpora").mkdir(parents=True)
|
|
(resources.NLTK_DATA / "corpora" / "wordnet.zip").write_bytes(b"x")
|
|
|
|
resources.fetch_nltk(force=False)
|
|
|
|
assert "wordnet" not in asked
|
|
|
|
def test_the_sentence_splitter_is_looked_for_under_tokenizers(
|
|
self, res: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
asked = self._install(monkeypatch)
|
|
(resources.NLTK_DATA / "tokenizers" / "punkt_tab").mkdir(parents=True)
|
|
|
|
resources.fetch_nltk(force=False)
|
|
|
|
assert "punkt_tab" not in asked
|
|
|
|
def test_force_fetches_what_is_already_here(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
asked = self._install(monkeypatch)
|
|
(resources.NLTK_DATA / "corpora" / "wordnet").mkdir(parents=True)
|
|
|
|
resources.fetch_nltk(force=True)
|
|
|
|
assert "wordnet" in asked
|
|
|
|
def test_a_refused_download_is_raised(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""`halt_on_error=False` keeps nltk from aborting the batch itself, so
|
|
the return value is what this has to report on."""
|
|
self._install(monkeypatch, answer=False)
|
|
|
|
with pytest.raises(RuntimeError):
|
|
resources.fetch_nltk(force=False)
|
|
|
|
def test_the_proxy_guard_is_opted_out_of(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""nltk's SSRF guard cannot tell an intentional corporate proxy from a
|
|
redirect it was tricked into following, and this is an explicit fetch
|
|
of named corpora run by an operator installing raven."""
|
|
import os
|
|
|
|
monkeypatch.delenv("NLTK_ALLOW_PROXIED_URLOPEN", raising=False)
|
|
self._install(monkeypatch)
|
|
|
|
resources.fetch_nltk(force=False)
|
|
|
|
assert os.environ["NLTK_ALLOW_PROXIED_URLOPEN"] == "1"
|
|
|
|
def test_a_host_that_already_decided_keeps_its_answer(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
import os
|
|
|
|
monkeypatch.setenv("NLTK_ALLOW_PROXIED_URLOPEN", "0")
|
|
self._install(monkeypatch)
|
|
|
|
resources.fetch_nltk(force=False)
|
|
|
|
assert os.environ["NLTK_ALLOW_PROXIED_URLOPEN"] == "0"
|
|
|
|
|
|
class TestWarmDictionary:
|
|
"""Building the trie cache at install time rather than inside a reader's
|
|
first query, which is six seconds."""
|
|
|
|
def test_a_cache_already_built_is_left_alone(
|
|
self, res: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
from raven.core import tokenizer as tok
|
|
|
|
dictionary = tmp_path / "huqie.txt"
|
|
dictionary.write_text("", encoding="utf-8")
|
|
dictionary.with_suffix(".txt.trie").write_bytes(b"cached")
|
|
monkeypatch.setattr(tok, "dictionary_path", lambda **_kw: dictionary)
|
|
built: list[int] = []
|
|
monkeypatch.setattr(tok, "Tokenizer", lambda *a, **k: built.append(1))
|
|
|
|
resources.warm_dictionary()
|
|
|
|
assert built == []
|
|
|
|
def test_a_missing_cache_is_built(self, res: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
|
from raven.core import tokenizer as tok
|
|
|
|
dictionary = tmp_path / "huqie.txt"
|
|
dictionary.write_text("", encoding="utf-8")
|
|
monkeypatch.setattr(tok, "dictionary_path", lambda **_kw: dictionary)
|
|
built: list[int] = []
|
|
monkeypatch.setattr(tok, "Tokenizer", lambda *a, **k: built.append(1))
|
|
|
|
resources.warm_dictionary()
|
|
|
|
assert built == [1]
|
|
|
|
def test_a_failure_to_build_does_not_stop_the_install(
|
|
self, res: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
"""It costs six seconds later, not correctness."""
|
|
from raven.core import tokenizer as tok
|
|
|
|
dictionary = tmp_path / "huqie.txt"
|
|
dictionary.write_text("", encoding="utf-8")
|
|
monkeypatch.setattr(tok, "dictionary_path", lambda **_kw: dictionary)
|
|
monkeypatch.setattr(tok, "Tokenizer", lambda *a, **k: (_ for _ in ()).throw(RuntimeError("no datrie here")))
|
|
|
|
resources.warm_dictionary()
|
|
|
|
|
|
class TestWithoutTheSegmenter:
|
|
"""The segmenter is an extra, because datrie compiles from source on every
|
|
platform PyPI publishes for -- so a core install has none of it, and both
|
|
steps that reach it have to be steps to skip rather than errors."""
|
|
|
|
def test_the_corpora_step_skips(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
import builtins
|
|
|
|
real = builtins.__import__
|
|
|
|
def refuse(name: str, *args: object, **kw: object):
|
|
if name == "nltk":
|
|
raise ImportError("No module named 'nltk'")
|
|
return real(name, *args, **kw) # type: ignore[arg-type]
|
|
|
|
monkeypatch.setattr(builtins, "__import__", refuse)
|
|
|
|
assert resources.fetch_nltk(force=False) == 0
|
|
|
|
def test_the_index_warm_up_skips(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
import builtins
|
|
|
|
real = builtins.__import__
|
|
|
|
def refuse(name: str, *args: object, **kw: object):
|
|
if name.startswith("raven.core"):
|
|
raise ImportError("No module named 'datrie'")
|
|
return real(name, *args, **kw) # type: ignore[arg-type]
|
|
|
|
monkeypatch.setattr(builtins, "__import__", refuse)
|
|
|
|
resources.warm_dictionary()
|
|
|
|
def test_the_dictionary_is_still_fetched(self, res: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""It is a word list, not code: an install with no segmenter can still
|
|
hold it, and the one that adds the extra later finds it already here."""
|
|
import httpx
|
|
|
|
client = _FakeClient([b"words"])
|
|
monkeypatch.setattr(httpx, "Client", lambda **_kw: client)
|
|
item = resources.Resource("huqie.txt", resources.CORE_RES, "the word dictionary")
|
|
|
|
assert resources.fetch_dictionary((item,), force=False) == 1
|