<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>
475 lines
18 KiB
Python
475 lines
18 KiB
Python
"""Reading a scanned page: detect the lines, crop them, recognise them.
|
|
|
|
The detector and the recogniser are the two graphs; everything between them is
|
|
here -- putting the quadrilaterals into reading order, warping each one flat,
|
|
and throwing away what was read too faintly to trust. The graphs are supplied
|
|
rather than loaded, so this runs without the weights.
|
|
|
|
`tests/test_knowledge_deepdoc_ocr.py` drives the same class with the real
|
|
models and skips without them, which is every CI run. What is asserted here is
|
|
the part that does not depend on what a model happens to answer.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import numpy as np
|
|
import pytest
|
|
|
|
from raven.knowledge.parser.deepdoc._ocr import OCR
|
|
|
|
|
|
def quad(x0: float, top: float, x1: float, bottom: float) -> np.ndarray:
|
|
"""A detection, as the detector answers it: four corners, clockwise from
|
|
the top left."""
|
|
return np.array([[x0, top], [x1, top], [x1, bottom], [x0, bottom]], dtype=np.float32)
|
|
|
|
|
|
def page(height: int = 200, width: int = 300) -> np.ndarray:
|
|
return np.zeros((height, width, 3), dtype=np.uint8)
|
|
|
|
|
|
class _Detector:
|
|
"""The detector answers one array of quadrilaterals, not a list of them."""
|
|
|
|
def __init__(self, boxes) -> None:
|
|
self.boxes = None if boxes is None else np.asarray(boxes, dtype=np.float32)
|
|
self.seen: list[np.ndarray] = []
|
|
|
|
def __call__(self, image):
|
|
self.seen.append(image)
|
|
return self.boxes, 0.0
|
|
|
|
|
|
class _Recogniser:
|
|
"""Answers one (text, score) per crop, in the order they arrive."""
|
|
|
|
def __init__(self, answers: list[tuple[str, float]]) -> None:
|
|
self.answers = answers
|
|
self.batches: list[list] = []
|
|
|
|
def __call__(self, crops):
|
|
self.batches.append(crops)
|
|
return self.answers[: len(crops)] or [("", 0.0)] * len(crops), 0.0
|
|
|
|
|
|
def reader(*, boxes=None, answers: list[tuple[str, float]] | None = None, drop_score: float = 0.5) -> OCR:
|
|
"""An OCR with both graphs supplied.
|
|
|
|
`__init__` opens two onnx sessions; nothing below reaches either.
|
|
"""
|
|
instance = object.__new__(OCR)
|
|
instance.text_detector = [_Detector(boxes)] # type: ignore[attr-defined]
|
|
instance.text_recognizer = [_Recogniser(answers or [])] # type: ignore[attr-defined]
|
|
instance.drop_score = drop_score # type: ignore[attr-defined]
|
|
instance.crop_image_res_index = 0 # type: ignore[attr-defined]
|
|
return instance
|
|
|
|
|
|
class TestSortedBoxes:
|
|
"""Reading order: down the page, then across each line."""
|
|
|
|
def test_lines_come_back_top_to_bottom(self) -> None:
|
|
out = reader().sorted_boxes(np.asarray([quad(0, 100, 50, 120), quad(0, 0, 50, 20)]))
|
|
|
|
assert [b[0][1] for b in out] == [0, 100]
|
|
|
|
def test_words_on_one_line_come_back_left_to_right(self) -> None:
|
|
"""Within ten points of each other counts as the same line, which is
|
|
what keeps a line of words from being read as a column."""
|
|
out = reader().sorted_boxes(np.asarray([quad(100, 2, 150, 20), quad(0, 0, 50, 18)]))
|
|
|
|
assert [b[0][0] for b in out] == [0, 100]
|
|
|
|
def test_a_gap_wider_than_a_line_is_two_lines(self) -> None:
|
|
out = reader().sorted_boxes(np.asarray([quad(100, 0, 150, 18), quad(0, 50, 50, 68)]))
|
|
|
|
assert [b[0][1] for b in out] == [0, 50]
|
|
|
|
def test_a_single_detection_comes_back_alone(self) -> None:
|
|
assert len(reader().sorted_boxes(np.asarray([quad(0, 0, 50, 20)]))) == 1
|
|
|
|
|
|
class TestRotateCrop:
|
|
"""One quadrilateral, warped flat into an upright strip.
|
|
|
|
The detector answers four corners rather than a rectangle, because a line
|
|
on a page scanned at an angle is not one; the recogniser reads left to
|
|
right, so the quad is projected before it is read.
|
|
"""
|
|
|
|
def test_a_crop_has_the_measured_size_of_its_quad(self) -> None:
|
|
out = reader().get_rotate_crop_image(page(), quad(10, 20, 110, 50))
|
|
|
|
assert out.shape[1] == pytest.approx(100, abs=1)
|
|
assert out.shape[0] == pytest.approx(30, abs=1)
|
|
|
|
def test_a_quad_of_the_wrong_shape_is_refused(self) -> None:
|
|
with pytest.raises(AssertionError):
|
|
reader().get_rotate_crop_image(page(), np.array([[0, 0], [1, 1]], dtype=np.float32))
|
|
|
|
def test_a_tall_strip_is_offered_to_the_recogniser_three_ways(self) -> None:
|
|
"""A crop half again as tall as it is wide is either a column of
|
|
vertical text or a line rotated by the scan, and nothing in the shape
|
|
says which. So all three orientations are read and the one the
|
|
recogniser is most confident about wins."""
|
|
instance = reader(answers=[("x", 0.1)])
|
|
|
|
instance.get_rotate_crop_image(page(), quad(10, 10, 30, 150))
|
|
|
|
assert len(instance.text_recognizer[0].batches) == 3
|
|
|
|
def test_the_orientation_the_recogniser_prefers_is_the_one_kept(self) -> None:
|
|
upright = reader(answers=[("x", 0.1)])
|
|
turned = reader(answers=[("x", 0.1)])
|
|
# Second call -- the clockwise turn -- reads best.
|
|
scores = iter([0.1, 0.9, 0.1])
|
|
|
|
class _Rising:
|
|
def __init__(self) -> None:
|
|
self.batches: list[list] = []
|
|
|
|
def __call__(self, crops):
|
|
self.batches.append(crops)
|
|
return [("x", next(scores))], 0.0
|
|
|
|
turned.text_recognizer[0] = _Rising()
|
|
|
|
kept_upright = upright.get_rotate_crop_image(page(), quad(10, 10, 30, 150))
|
|
kept_turned = turned.get_rotate_crop_image(page(), quad(10, 10, 30, 150))
|
|
|
|
assert kept_upright.shape[0] > kept_upright.shape[1], "no rotation beat the original"
|
|
assert kept_turned.shape[0] < kept_turned.shape[1], "the turn the recogniser preferred"
|
|
|
|
def test_a_wide_crop_is_read_as_it_is(self) -> None:
|
|
"""Only a tall crop is ambiguous; a line that is wider than it is tall
|
|
is already the way the recogniser reads."""
|
|
instance = reader(answers=[("x", 0.9)])
|
|
|
|
instance.get_rotate_crop_image(page(), quad(10, 10, 110, 40))
|
|
|
|
assert instance.text_recognizer[0].batches == [], "no orientation trial"
|
|
|
|
|
|
class TestDetect:
|
|
def test_it_answers_a_box_per_detection_with_no_text_yet(self) -> None:
|
|
found = list(reader(boxes=[quad(0, 0, 50, 20), quad(0, 50, 50, 70)]).detect(page()))
|
|
|
|
assert len(found) == 2
|
|
assert all(text == ("", 0) for _box, text in found)
|
|
|
|
def test_a_page_that_is_not_there_is_not_read(self) -> None:
|
|
assert reader(boxes=[]).detect(None) is None
|
|
|
|
def test_a_page_the_detector_found_nothing_on_answers_nothing(self) -> None:
|
|
assert reader(boxes=None).detect(page()) is None
|
|
|
|
def test_the_boxes_come_back_in_reading_order(self) -> None:
|
|
found = list(reader(boxes=[quad(0, 100, 50, 120), quad(0, 0, 50, 20)]).detect(page()))
|
|
|
|
assert [b[0][1] for b, _ in found] == [0, 100]
|
|
|
|
|
|
class TestRecognize:
|
|
def test_a_confident_reading_comes_back(self) -> None:
|
|
out = reader(answers=[("hello", 0.9)]).recognize(page(), quad(0, 0, 50, 20))
|
|
|
|
assert out == "hello"
|
|
|
|
def test_a_faint_reading_is_thrown_away(self) -> None:
|
|
"""Below the threshold the recogniser is guessing, and a guess in the
|
|
index is worse than a gap."""
|
|
out = reader(answers=[("he11o", 0.1)]).recognize(page(), quad(0, 0, 50, 20))
|
|
|
|
assert out == ""
|
|
|
|
def test_a_batch_is_read_in_one_call(self) -> None:
|
|
instance = reader(answers=[("a", 0.9), ("b", 0.9)])
|
|
|
|
out = instance.recognize_batch([page(20, 50), page(20, 50)])
|
|
|
|
assert out == ["a", "b"]
|
|
assert len(instance.text_recognizer[0].batches) == 1, "one call, not one per crop"
|
|
|
|
def test_a_faint_item_in_a_batch_is_blanked_without_dropping_the_rest(self) -> None:
|
|
"""Blanked rather than removed: the caller pairs these back with the
|
|
boxes they came from, by position."""
|
|
out = reader(answers=[("a", 0.9), ("junk", 0.1), ("c", 0.9)]).recognize_batch([page(20, 50) for _ in range(3)])
|
|
|
|
assert out == ["a", "", "c"]
|
|
|
|
def test_the_scored_form_keeps_the_score_of_a_blanked_item(self) -> None:
|
|
"""The HTTP adapter picks between rotations by score, so it needs the
|
|
number even where the text was dropped."""
|
|
out = reader(answers=[("junk", 0.1)]).recognize_batch_with_score([page(20, 50)])
|
|
|
|
assert out == [("", pytest.approx(0.1))]
|
|
|
|
def test_the_scored_form_keeps_a_confident_reading_whole(self) -> None:
|
|
out = reader(answers=[("hello", 0.9)]).recognize_batch_with_score([page(20, 50)])
|
|
|
|
assert out == [("hello", pytest.approx(0.9))]
|
|
|
|
|
|
class TestReadingAWholePage:
|
|
def test_every_confident_line_comes_back_with_its_box(self) -> None:
|
|
instance = reader(
|
|
boxes=[quad(0, 0, 50, 20), quad(0, 50, 50, 70)],
|
|
answers=[("first", 0.9), ("second", 0.9)],
|
|
)
|
|
|
|
out = instance(page())
|
|
|
|
assert [text for _box, (text, _score) in out] == ["first", "second"]
|
|
assert all(isinstance(box, list) for box, _ in out), "boxes answered as plain lists"
|
|
|
|
def test_a_faint_line_is_left_out_entirely(self) -> None:
|
|
instance = reader(
|
|
boxes=[quad(0, 0, 50, 20), quad(0, 50, 50, 70)],
|
|
answers=[("good", 0.9), ("junk", 0.1)],
|
|
)
|
|
|
|
out = instance(page())
|
|
|
|
assert [text for _box, (text, _score) in out] == ["good"]
|
|
|
|
def test_a_page_that_is_not_there_answers_nothing(self) -> None:
|
|
out, _rec, timings = reader(boxes=[])(None)
|
|
|
|
assert out is None
|
|
assert timings["all"] == 0
|
|
|
|
def test_a_page_with_no_detections_answers_nothing(self) -> None:
|
|
out, _rec, timings = reader(boxes=None)(page())
|
|
|
|
assert out is None
|
|
assert "det" in timings
|
|
|
|
def test_the_crops_reach_the_recogniser_in_reading_order(self) -> None:
|
|
instance = reader(
|
|
boxes=[quad(0, 100, 50, 120), quad(0, 0, 50, 20)],
|
|
answers=[("top", 0.9), ("bottom", 0.9)],
|
|
)
|
|
|
|
out = instance(page())
|
|
|
|
assert [text for _box, (text, _score) in out] == ["top", "bottom"]
|
|
|
|
def test_the_page_handed_in_is_not_modified(self) -> None:
|
|
"""It is copied before the crops are taken; the caller still wants the
|
|
page for the layout pass."""
|
|
original = page()
|
|
before = original.copy()
|
|
|
|
reader(boxes=[quad(0, 0, 50, 20)], answers=[("a", 0.9)])(original)
|
|
|
|
assert np.array_equal(original, before)
|
|
|
|
|
|
class _Tensor:
|
|
"""The graph's declared input: a name and a shape with a free width."""
|
|
|
|
name = "x"
|
|
shape = [-1, 3, 48, -1]
|
|
|
|
|
|
def _recogniser(answers: list[tuple[str, float]], *, batch: int = 16) -> object:
|
|
"""A TextRecognizer with its graph and its label decoder supplied."""
|
|
from raven.knowledge.parser.deepdoc._ocr import TextRecognizer
|
|
|
|
instance = object.__new__(TextRecognizer)
|
|
instance.rec_image_shape = [3, 48, 320] # type: ignore[attr-defined]
|
|
instance.rec_batch_num = batch # type: ignore[attr-defined]
|
|
instance.input_tensor = _Tensor() # type: ignore[attr-defined]
|
|
instance.batches: list = [] # type: ignore[attr-defined]
|
|
|
|
def predictor_run(_names, feed, _options=None):
|
|
instance.batches.append(feed[_Tensor.name]) # type: ignore[attr-defined]
|
|
return [np.zeros((len(feed[_Tensor.name]), 1, 1), dtype=np.float32)]
|
|
|
|
instance.predictor = type("P", (), {"run": staticmethod(predictor_run)})() # type: ignore[attr-defined]
|
|
served = iter(answers)
|
|
instance.postprocess_op = lambda preds: [next(served) for _ in range(len(preds))] # type: ignore[attr-defined]
|
|
return instance
|
|
|
|
|
|
class TestNormalisingAStrip:
|
|
"""Each crop, stretched to the height the graph wants and padded to a
|
|
common width so a batch is one tensor."""
|
|
|
|
def test_a_strip_comes_back_at_the_graphs_height(self) -> None:
|
|
out = _recogniser([]).resize_norm_img(page(24, 100), max_wh_ratio=320 / 48)
|
|
|
|
assert out.shape[0] == 3, "channels first"
|
|
assert out.shape[1] == 48
|
|
|
|
def test_the_pixels_are_centred_on_zero(self) -> None:
|
|
"""Scaled to the unit range then shifted to [-1, 1], which is what the
|
|
graph was trained on."""
|
|
out = _recogniser([]).resize_norm_img(np.full((24, 100, 3), 255, np.uint8), max_wh_ratio=320 / 48)
|
|
|
|
assert out.max() == pytest.approx(1.0)
|
|
|
|
def test_a_short_strip_is_padded_rather_than_stretched(self) -> None:
|
|
"""Stretching a short line to the batch width would distort letters
|
|
the recogniser reads by shape."""
|
|
out = _recogniser([]).resize_norm_img(page(48, 48), max_wh_ratio=320 / 48)
|
|
|
|
assert out[:, :, -1] == pytest.approx(0.0), "padded, not filled"
|
|
|
|
def test_a_channel_count_the_graph_did_not_ask_for_is_refused(self) -> None:
|
|
with pytest.raises(AssertionError):
|
|
_recogniser([]).resize_norm_img(np.zeros((24, 100, 1), np.uint8), max_wh_ratio=320 / 48)
|
|
|
|
|
|
class TestRecognisingABatch:
|
|
def test_every_strip_comes_back_against_its_own_crop(self) -> None:
|
|
"""The crops are sorted by shape before they are read, so the answers
|
|
come back in a different order than they went in and have to be put
|
|
back. Getting this wrong puts each line's text on its neighbour."""
|
|
crops = [page(20, 200), page(20, 20), page(20, 100)]
|
|
# Read narrowest first, so the answers are served in that order.
|
|
instance = _recogniser([("narrowest", 0.9), ("middle", 0.9), ("widest", 0.9)])
|
|
|
|
out, _elapsed = instance(crops)
|
|
|
|
assert [text for text, _score in out] == ["widest", "narrowest", "middle"], "each crop keeps its own"
|
|
|
|
def test_a_long_list_is_read_in_batches(self) -> None:
|
|
crops = [page(20, 100) for _ in range(5)]
|
|
instance = _recogniser([("a", 0.9)] * 5, batch=2)
|
|
|
|
instance(crops)
|
|
|
|
assert [len(b) for b in instance.batches] == [2, 2, 1] # type: ignore[attr-defined]
|
|
|
|
def test_an_empty_list_reads_nothing(self) -> None:
|
|
out, _elapsed = _recogniser([])([])
|
|
|
|
assert out == []
|
|
|
|
|
|
def _detector() -> object:
|
|
from raven.knowledge.parser.deepdoc._ocr import TextDetector
|
|
|
|
return object.__new__(TextDetector)
|
|
|
|
|
|
class TestOrderingCorners:
|
|
def test_corners_come_back_clockwise_from_the_top_left(self) -> None:
|
|
"""The detector's four points arrive in whatever order the contour was
|
|
walked; the crop assumes top-left, top-right, bottom-right, bottom-left."""
|
|
scrambled = np.array([[10, 50], [0, 0], [10, 0], [0, 50]], dtype=np.float32)
|
|
|
|
out = _detector().order_points_clockwise(scrambled)
|
|
|
|
assert out[0].tolist() == [0, 0]
|
|
assert out[2].tolist() == [10, 50]
|
|
|
|
|
|
class TestClippingToThePage:
|
|
def test_a_corner_past_the_edge_is_pulled_back(self) -> None:
|
|
points = np.array([[-5, -5], [500, 10], [500, 400], [-5, 400]], dtype=np.float32)
|
|
|
|
out = _detector().clip_det_res(points, img_height=200, img_width=300)
|
|
|
|
assert out[:, 0].min() == 0 and out[:, 0].max() == 299
|
|
assert out[:, 1].min() == 0 and out[:, 1].max() == 199
|
|
|
|
def test_a_box_inside_the_page_is_left_alone(self) -> None:
|
|
points = np.array([[10, 10], [50, 10], [50, 30], [10, 30]], dtype=np.float32)
|
|
|
|
out = _detector().clip_det_res(points.copy(), img_height=200, img_width=300)
|
|
|
|
assert out.tolist() == points.tolist()
|
|
|
|
|
|
class TestFilteringDetections:
|
|
def test_a_sliver_is_dropped(self) -> None:
|
|
"""A detection three points wide carries no readable glyph; feeding it
|
|
to the recogniser spends a batch slot on noise."""
|
|
boxes = [np.array([[0, 0], [2, 0], [2, 20], [0, 20]], dtype=np.float32)]
|
|
|
|
assert len(_detector().filter_tag_det_res(boxes, (200, 300))) == 0
|
|
|
|
def test_a_readable_box_survives(self) -> None:
|
|
boxes = [np.array([[0, 0], [80, 0], [80, 20], [0, 20]], dtype=np.float32)]
|
|
|
|
assert len(_detector().filter_tag_det_res(boxes, (200, 300))) == 1
|
|
|
|
def test_a_box_given_as_a_list_is_accepted(self) -> None:
|
|
boxes = [[[0, 0], [80, 0], [80, 20], [0, 20]]]
|
|
|
|
assert len(_detector().filter_tag_det_res(boxes, (200, 300))) == 1
|
|
|
|
def test_the_clip_only_form_keeps_every_box(self) -> None:
|
|
"""Used where the caller has already decided what is worth reading."""
|
|
boxes = [np.array([[0, 0], [2, 0], [2, 20], [0, 20]], dtype=np.float32)]
|
|
|
|
assert len(_detector().filter_tag_det_res_only_clip(boxes, (200, 300))) == 1
|
|
|
|
|
|
class _DetectorTensor:
|
|
"""A graph declaring a dynamic input, which is what the published detector
|
|
does: the resize cap decides the size rather than the graph."""
|
|
|
|
name = "x"
|
|
shape = [-1, 3, "h", "w"]
|
|
|
|
|
|
def _detector_with_graph(points: list, *, scores=None):
|
|
"""A TextDetector with its graph and both ends of its pipeline supplied."""
|
|
from raven.knowledge.parser.deepdoc._ocr import (
|
|
DetResizeForTest,
|
|
KeepKeys,
|
|
NormalizeImage,
|
|
TextDetector,
|
|
ToCHWImage,
|
|
)
|
|
|
|
instance = object.__new__(TextDetector)
|
|
instance.input_tensor = _DetectorTensor()
|
|
instance.preprocess_op = [
|
|
DetResizeForTest(limit_side_len=64, limit_type="max"),
|
|
NormalizeImage(std=[0.229, 0.224, 0.225], mean=[0.485, 0.456, 0.406], scale="1./255.", order="hwc"),
|
|
ToCHWImage(),
|
|
KeepKeys(keep_keys=["image", "shape"]),
|
|
]
|
|
instance.predictor = type(
|
|
"P", (), {"run": staticmethod(lambda _n, feed, _o=None: [np.zeros((1, 1, 8, 8), dtype=np.float32)])}
|
|
)()
|
|
instance.postprocess_op = lambda _maps, _shape: [{"points": points}]
|
|
return instance
|
|
|
|
|
|
class TestDetectingOnAPage:
|
|
def test_a_detection_comes_back_clipped_to_the_page(self) -> None:
|
|
"""The post-processor answers in the resized frame and can run past the
|
|
edge; a box outside the page cannot be cropped from it."""
|
|
points = [np.array([[-10, -10], [500, 0], [500, 400], [-10, 400]], dtype=np.float32)]
|
|
|
|
boxes, _elapsed = _detector_with_graph(points)(page(200, 300))
|
|
|
|
assert len(boxes) == 1
|
|
assert boxes[0][:, 0].min() >= 0
|
|
assert boxes[0][:, 0].max() <= 299
|
|
|
|
def test_a_sliver_is_filtered_out(self) -> None:
|
|
points = [np.array([[0, 0], [2, 0], [2, 20], [0, 20]], dtype=np.float32)]
|
|
|
|
boxes, _elapsed = _detector_with_graph(points)(page())
|
|
|
|
assert len(boxes) == 0
|
|
|
|
def test_a_page_with_nothing_on_it_answers_no_boxes(self) -> None:
|
|
boxes, _elapsed = _detector_with_graph([])(page())
|
|
|
|
assert len(boxes) == 0
|
|
|
|
def test_the_page_handed_in_is_not_modified(self) -> None:
|
|
original = page()
|
|
before = original.copy()
|
|
|
|
_detector_with_graph([np.array([[0, 0], [80, 0], [80, 20], [0, 20]], dtype=np.float32)])(original)
|
|
|
|
assert np.array_equal(original, before)
|