Raven-1/tests/test_knowledge_deepdoc_geometry.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

287 lines
9.9 KiB
Python

"""Where a detected quadrilateral goes before anything reads it.
Between the detector and the recognizer sits arithmetic: four corners put in a
fixed order, clipped to the page, thrown away if they enclose nothing, sorted
into reading order, and warped flat. None of it needs a session -- and all of
it decides what the recognizer is handed, so an error here reads a page in the
wrong order or reads a sliver of one.
The classes load their models in ``__init__``, which is the whole reason this
was reachable only from tests that skip wherever the weights are not installed.
These methods touch no attribute a constructor sets, so the tests build the
objects without running it and stay honest about what they cover.
"""
from __future__ import annotations
import cv2
import numpy as np
import pytest
from raven.knowledge.parser.deepdoc import _ocr
from raven.knowledge.parser.deepdoc._ocr import OCR, TextDetector, TextRecognizer, transform
def _detector() -> TextDetector:
"""A detector with no session behind it. None of the geometry asks for one."""
return object.__new__(TextDetector)
def _reader() -> OCR:
return object.__new__(OCR)
def _quad(left: float, top: float, right: float, bottom: float) -> np.ndarray:
return np.array([[left, top], [right, top], [right, bottom], [left, bottom]], dtype=np.float32)
# -- four corners, one order ---------------------------------------
def test_the_corners_come_back_top_left_first_going_clockwise() -> None:
"""Every later step indexes the corners rather than searching them: the
crop reads 0-1 as the top edge and 0-3 as the left."""
scrambled = np.array([[30, 20], [10, 20], [10, 5], [30, 5]], dtype=np.float32)
ordered = _detector().order_points_clockwise(scrambled)
assert ordered.tolist() == [[10, 5], [30, 5], [30, 20], [10, 20]]
def test_a_box_already_in_order_is_left_alone() -> None:
box = _quad(10, 5, 30, 20)
assert _detector().order_points_clockwise(box).tolist() == box.tolist()
def test_a_tilted_box_keeps_its_tilt() -> None:
"""A line scanned at an angle is a quadrilateral, not a rectangle, and
ordering it must not square it off."""
tilted = np.array([[12, 4], [34, 9], [32, 22], [10, 17]], dtype=np.float32)
ordered = _detector().order_points_clockwise(tilted)
assert ordered.tolist() == tilted.tolist()
# -- the page's own edges ------------------------------------------
def test_a_corner_past_the_page_is_pulled_back_inside() -> None:
"""The boxes are scaled up from a smaller map, so rounding can put one a
pixel or two off the page. A crop taken there would raise."""
box = _quad(-5, -2, 500, 400)
clipped = _detector().clip_det_res(box.copy(), 100, 200)
assert clipped.min() == 0
assert clipped[:, 0].max() == 199, "the last column, not the width"
assert clipped[:, 1].max() == 99
def test_clipping_leaves_a_box_that_is_already_inside() -> None:
box = _quad(10, 5, 30, 20)
assert _detector().clip_det_res(box.copy(), 100, 200).tolist() == box.tolist()
# -- what is not worth reading -------------------------------------
def test_a_box_too_thin_to_hold_a_glyph_is_dropped() -> None:
"""Three pixels of height is not a line of text; it is an artifact of the
map, and sending it to the recognizer spends a model call on noise."""
boxes = [_quad(10, 5, 60, 25), _quad(10, 40, 60, 42)]
kept = _detector().filter_tag_det_res(boxes, (100, 200, 3))
assert len(kept) == 1
assert kept[0][0].tolist() == [10, 5]
def test_filtering_orders_and_clips_what_it_keeps() -> None:
"""One pass: the caller gets boxes that are in order and on the page."""
scrambled = np.array([[260, 60], [10, 60], [10, 5], [260, 5]], dtype=np.float32)
[kept] = _detector().filter_tag_det_res([scrambled], (100, 200, 3))
assert kept[0].tolist() == [10, 5], "top-left first"
assert kept[:, 0].max() == 199, "clipped to the page"
def test_a_list_of_corners_is_read_like_an_array() -> None:
"""What the postprocessor hands over is not always an ndarray."""
boxes = [[[10, 5], [60, 5], [60, 25], [10, 25]]]
kept = _detector().filter_tag_det_res(boxes, (100, 200, 3))
assert len(kept) == 1
def test_clipping_alone_keeps_boxes_the_filter_would_drop() -> None:
"""The other pass, for a caller that has already decided what is a box --
a table's cells, say, where a rule really is two pixels tall."""
boxes = [_quad(10, 5, 60, 25), _quad(10, 40, 60, 42)]
kept = _detector().filter_tag_det_res_only_clip(boxes, (100, 200, 3))
assert len(kept) == 2
# -- reading order -------------------------------------------------
def test_boxes_are_ordered_down_the_page() -> None:
top, middle, bottom = _quad(10, 5, 60, 25), _quad(10, 40, 60, 60), _quad(10, 80, 60, 100)
ordered = _reader().sorted_boxes(np.array([bottom, top, middle]))
assert [box[0][1] for box in ordered] == [5, 40, 80]
def test_two_boxes_on_one_line_are_ordered_left_to_right() -> None:
"""Two columns of a header sit at the same height to the eye and a few
pixels apart in the map; reading order is still left, then right."""
left, right = _quad(10, 7, 60, 25), _quad(120, 5, 180, 25)
ordered = _reader().sorted_boxes(np.array([right, left]))
assert [box[0][0] for box in ordered] == [10, 120]
def test_a_box_far_enough_down_is_a_new_line_however_far_left_it_sits() -> None:
"""Ten pixels is the whole of what separates 'beside' from 'below'."""
first, second = _quad(120, 5, 180, 25), _quad(10, 40, 60, 60)
ordered = _reader().sorted_boxes(np.array([second, first]))
assert [box[0][1] for box in ordered] == [5, 40]
def test_one_box_sorts_to_itself() -> None:
assert len(_reader().sorted_boxes(np.array([_quad(10, 5, 60, 25)]))) == 1
# -- the crop the recognizer reads ---------------------------------
def test_a_crop_comes_out_the_size_of_its_own_box() -> None:
page = np.zeros((100, 200, 3), dtype=np.uint8)
page[5:25, 10:60] = 255
crop = _reader().get_rotate_crop_image(page, _quad(10, 5, 60, 25))
assert crop.shape[:2] == (20, 50)
assert crop.mean() > 200, "the ink, not the margin beside it"
def test_a_tilted_box_is_warped_upright() -> None:
"""The point of taking four corners rather than a rectangle: the strip the
recognizer reads is straight even where the page was not."""
page = np.zeros((100, 200, 3), dtype=np.uint8)
tilted = np.array([[12, 10], [92, 20], [90, 40], [10, 30]], dtype=np.float32)
cv2.fillPoly(page, np.array([tilted], dtype=np.int32), (255, 255, 255))
crop = _reader().get_rotate_crop_image(page, tilted)
height, width = crop.shape[:2]
assert width > height * 3, "a flat strip, whatever angle it was found at"
assert crop[height // 2, width // 2].mean() > 200
# -- what a session is handed, and what happens when it refuses ----
class _Stub:
"""A recognizer's input tensor, without the session behind it."""
def __init__(self, width: object) -> None:
self.shape = ["batch", 3, 48, width]
def _recognizer(width: object) -> TextRecognizer:
reader = object.__new__(TextRecognizer)
reader.rec_image_shape = [3, 48, 320]
reader.input_tensor = _Stub(width)
return reader
def test_a_crop_is_padded_out_to_the_batch_width() -> None:
"""A batch is one array, so every strip in it is the width of the widest;
the narrow ones are padded rather than stretched, which would deform the
glyphs the model was trained on."""
crop = np.full((24, 60, 3), 255, dtype=np.uint8)
ready = _recognizer("width").resize_norm_img(crop, 320 / 48)
assert ready.shape == (3, 48, 320)
assert ready[:, :, -1].max() == 0, "padding, not a stretched glyph"
def test_a_crop_wider_than_the_batch_is_cut_to_it() -> None:
crop = np.full((24, 600, 3), 255, dtype=np.uint8)
ready = _recognizer("width").resize_norm_img(crop, 2.0)
assert ready.shape == (3, 48, 96)
def test_a_fixed_shape_model_gets_its_own_width_whatever_the_batch_asked() -> None:
"""A model compiled to one input size ignores the batch's ratio; sending
it anything else raises inside onnxruntime."""
crop = np.full((24, 60, 3), 255, dtype=np.uint8)
ready = _recognizer(160).resize_norm_img(crop, 320 / 48)
assert ready.shape == (3, 48, 160)
def test_the_operators_run_in_the_order_they_were_given() -> None:
assert transform("a", [lambda data: data + "b", lambda data: data + "c"]) == "abc"
def test_an_operator_that_rejects_the_image_ends_the_chain() -> None:
"""A page too small to resize comes back as nothing, and the operators
after it would read that as an image."""
seen: list[str] = []
assert transform("a", [lambda _: None, lambda data: seen.append("ran") or data]) is None
assert seen == []
def test_no_operators_leaves_the_image_alone() -> None:
assert transform("a") == "a"
def test_a_session_that_fails_once_is_asked_again(monkeypatch) -> None:
"""Indexing a long document is thousands of these calls, and onnxruntime
can fail one under memory pressure that the next one survives."""
monkeypatch.setattr(_ocr.time, "sleep", lambda _: None)
attempts: list[int] = []
class _Flaky:
def run(self, _out, _inputs, _opts):
attempts.append(1)
if len(attempts) < 2:
raise RuntimeError("busy")
return ["ok"]
assert _ocr._run_with_retry(_Flaky(), {}) == ["ok"]
assert len(attempts) == 2
def test_a_session_that_keeps_failing_surfaces_the_failure(monkeypatch) -> None:
"""Retried briefly, then raised: a document that cannot be read has to
say so rather than index as empty."""
monkeypatch.setattr(_ocr.time, "sleep", lambda _: None)
attempts: list[int] = []
class _Broken:
def run(self, _out, _inputs, _opts):
attempts.append(1)
raise RuntimeError("the graph is gone")
with pytest.raises(RuntimeError, match="the graph is gone"):
_ocr._run_with_retry(_Broken(), {})
assert len(attempts) == 3, "tried, not tried forever"