Raven-1/tests/test_knowledge_vision.py
Kevin Hu 82c76a82a9
feat(knowledge): read every format, show what the index holds, and let an agent search it (#489)
<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>
2026-10-12 19:05:16 +08:00

221 lines
7.4 KiB
Python

"""The describe call behind an indexed picture: the prompt, the answer, the pin."""
from __future__ import annotations
import asyncio
import base64
import io
import pytest
from raven.knowledge._vision import (
DESCRIPTION_BUDGET,
VisionError,
VisionModel,
build_prompt,
clean_description,
configured_language,
load_vision_model,
)
#: One transparent pixel. Small enough to pass through preparation untouched,
#: which is what keeps these tests about the call rather than about Pillow.
PNG = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
)
class _Answer:
def __init__(self, content: object) -> None:
self.content = content
class _Provider:
"""Records what it was sent and answers with whatever it was given."""
def __init__(self, content: object = "a bar chart", error: Exception | None = None, delay: float = 0.0) -> None:
self.content = content
self.error = error
self.delay = delay
self.calls: list[dict] = []
async def chat_with_retry(self, **kwargs) -> _Answer:
self.calls.append(kwargs)
if self.delay:
await asyncio.sleep(self.delay)
if self.error is not None:
raise self.error
return _Answer(self.content)
def _model(**kwargs) -> tuple[VisionModel, _Provider]:
provider = _Provider(**kwargs)
return VisionModel(provider=provider, model="qwen-vl", timeout_s=5.0), provider
# -- the prompt ----------------------------------------------------
def test_the_prompt_names_the_language_it_wants_back() -> None:
assert "descriptions and field values in Chinese" in build_prompt(language="Chinese")
def test_a_prompt_with_no_context_carries_no_context_section() -> None:
"""An empty "CONTEXT (ABOVE)" heading reads as a region the model failed to
see, and the models worth using are the ones that would try to account for
it."""
plain = build_prompt()
assert "CONTEXT" not in plain
assert "Surrounding context" not in plain
def test_context_travels_when_there_is_some() -> None:
"""A figure rarely explains itself: the sentence introducing it names what
it is of, and without that a bar chart is described as a bar chart."""
prompt = build_prompt(context_above="Revenue held up in Q2.", context_below="Q3 is not in yet.")
assert "Revenue held up in Q2." in prompt
assert "Q3 is not in yet." in prompt
assert "only for minimal clarification" in prompt
def test_one_side_of_context_is_enough_to_carry_it() -> None:
prompt = build_prompt(context_above="Figure 4.")
assert "Figure 4." in prompt
assert "(none)" in prompt, "and the empty side says so rather than looking cut off"
# -- the answer ----------------------------------------------------
def test_a_fenced_answer_is_unwrapped() -> None:
"""A model asked for prose sometimes answers in a code block, and the
fences would be indexed as content."""
assert clean_description("```\nA bar chart.\n```") == "A bar chart."
assert clean_description("```text\nA bar chart.\n```") == "A bar chart."
def test_an_answer_past_the_budget_is_clamped_not_dropped() -> None:
"""The opposite of what a session title does with one: half a description
still describes the top half of the figure."""
assert len(clean_description("x" * (DESCRIPTION_BUDGET * 2))) == DESCRIPTION_BUDGET
async def test_the_image_and_the_prompt_travel_as_one_message() -> None:
model, provider = _model()
text = await model.describe(PNG)
assert text == "a bar chart"
content = provider.calls[0]["messages"][0]["content"]
assert content[0]["type"] == "image_url"
assert content[0]["image_url"]["url"].startswith("data:image/png;base64,")
assert content[1]["type"] == "text"
assert provider.calls[0]["model"] == "qwen-vl"
async def test_an_answer_in_content_parts_is_read() -> None:
"""Some providers answer a multimodal call in parts rather than a string."""
model, _ = _model(content=[{"type": "text", "text": "a pie chart"}])
assert await model.describe(PNG) == "a pie chart"
async def test_an_endpoint_that_refuses_says_which_model() -> None:
model, _ = _model(error=RuntimeError("model_not_found"))
with pytest.raises(VisionError) as caught:
await model.describe(PNG)
assert "qwen-vl" in str(caught.value)
assert "model_not_found" in str(caught.value)
async def test_a_slow_endpoint_is_given_up_on() -> None:
"""An indexing run is not a turn somebody is waiting on, but it is also not
allowed to hang the queue behind it."""
provider = _Provider(delay=1.0)
model = VisionModel(provider=provider, model="qwen-vl", timeout_s=0.01)
with pytest.raises(VisionError) as caught:
await model.describe(PNG)
assert "did not answer" in str(caught.value)
async def test_bytes_that_are_not_an_image_are_the_callers_problem() -> None:
model, provider = _model()
with pytest.raises(VisionError):
await model.describe(b"this is not a picture")
assert provider.calls == [], "and nothing was sent"
async def test_a_large_image_is_downscaled_before_it_is_sent() -> None:
"""Endpoints that do not refuse an oversized image downscale it themselves
and bill for the original."""
from PIL import Image
buffer = io.BytesIO()
Image.new("RGB", (4000, 4000), "white").save(buffer, format="PNG")
model, provider = _model()
await model.describe(buffer.getvalue())
sent = provider.calls[0]["messages"][0]["content"][0]["image_url"]["url"]
assert sent.startswith("data:image/jpeg;base64,"), "re-encoded rather than passed through"
assert len(sent) < len(buffer.getvalue())
# -- the pin -------------------------------------------------------
def test_no_pin_is_no_model_rather_than_a_failure(monkeypatch) -> None:
"""An install with no vision model is an ordinary state: a document parses
without its figures described, and only a bare picture has to fail."""
class _Config:
class vision: # noqa: N801 - standing in for the config block
model = None
provider = None
monkeypatch.setattr("raven.config.raven.load_raven_config", lambda: _Config())
assert load_vision_model() is None
def test_an_unusable_pin_is_no_model_either(monkeypatch) -> None:
"""`bind_pin` answers None for a provider with no credential, and a pin
that cannot be bound must not become a call that fails per figure."""
class _Config:
class vision: # noqa: N801 - standing in for the config block
model = "qwen-vl"
provider = "nobody"
timeout_seconds = 90.0
max_figures = 64
monkeypatch.setattr("raven.config.raven.load_raven_config", lambda: _Config())
monkeypatch.setattr("raven.providers.pool.ProviderPool.bind_pin", lambda self, model, provider=None: None)
assert load_vision_model() is None
def test_the_language_falls_back_to_english(monkeypatch) -> None:
"""A config that cannot be read still describes pictures, in English."""
monkeypatch.setattr("raven.config.loader.load_config", lambda: (_ for _ in ()).throw(OSError("gone")))
assert configured_language() == "English"
def test_the_language_follows_the_install(monkeypatch) -> None:
class _Config:
language = "zh"
monkeypatch.setattr("raven.config.loader.load_config", lambda: _Config())
assert configured_language() == "Chinese"