<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>
297 lines
11 KiB
Python
297 lines
11 KiB
Python
"""Unit tests for the spreadsheet parser: rows, positions, and the two renders."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import io
|
|
import shutil
|
|
import zipfile
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from raven.knowledge.parser.excel_parser import ExcelParser
|
|
|
|
_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
|
|
_RELS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
|
|
|
|
|
|
def _xlsx(sheets: dict[str, list[list[str]]]) -> bytes:
|
|
"""A minimal but well-formed workbook, strings written inline.
|
|
|
|
Inline rather than shared so the fixture says what a cell holds where the
|
|
cell is; the shared table has its own test.
|
|
"""
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w") as package:
|
|
package.writestr(
|
|
"[Content_Types].xml",
|
|
'<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>',
|
|
)
|
|
entries, rels = [], []
|
|
for index, (name, rows) in enumerate(sheets.items(), start=1):
|
|
entries.append(f'<sheet name="{name}" sheetId="{index}" r:id="rId{index}"/>')
|
|
rels.append(f'<Relationship Id="rId{index}" Target="worksheets/sheet{index}.xml"/>')
|
|
body = ""
|
|
for row_at, row in enumerate(rows, start=1):
|
|
cells = ""
|
|
for col_at, cell in enumerate(row):
|
|
ref = f"{chr(65 + col_at)}{row_at}"
|
|
cells += f'<c r="{ref}" t="inlineStr"><is><t>{cell}</t></is></c>' if cell else ""
|
|
body += f'<row r="{row_at}">{cells}</row>'
|
|
package.writestr(
|
|
f"xl/worksheets/sheet{index}.xml",
|
|
f'<worksheet xmlns="{_MAIN}"><sheetData>{body}</sheetData></worksheet>',
|
|
)
|
|
package.writestr(
|
|
"xl/workbook.xml",
|
|
f'<workbook xmlns="{_MAIN}" xmlns:r="{_RELS}"><sheets>{"".join(entries)}</sheets></workbook>',
|
|
)
|
|
package.writestr(
|
|
"xl/_rels/workbook.xml.rels",
|
|
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
|
+ "".join(rels)
|
|
+ "</Relationships>",
|
|
)
|
|
return buffer.getvalue()
|
|
|
|
|
|
def _parse(payload: bytes | str, filename: str = "book.xlsx"):
|
|
return asyncio.run(ExcelParser().parse(payload, filename))
|
|
|
|
|
|
def _texts(sections) -> list[str]:
|
|
return [section.content.text for section in sections]
|
|
|
|
|
|
# -- a row is the unit ----------------------------------------------
|
|
|
|
|
|
def test_a_row_carries_the_header_that_names_its_values() -> None:
|
|
"""A value without its column name is a number nobody can ask about."""
|
|
book = _xlsx({"Sheet1": [["Region", "Revenue"], ["EU", "1.2M"], ["APAC", "0.9M"]]})
|
|
|
|
assert _texts(_parse(book)) == ["Region: EU; Revenue: 1.2M", "Region: APAC; Revenue: 0.9M"]
|
|
|
|
|
|
def test_a_row_says_where_it_came_from() -> None:
|
|
"""Sheet, row and the columns it spans -- what a reader needs to find it
|
|
again in the file they uploaded."""
|
|
book = _xlsx({"Sheet1": [["A", "B", "C"], ["", "two", "three"]]})
|
|
|
|
metadata = _parse(book)[0].metadata
|
|
|
|
assert metadata["sheet_idx"] == 0
|
|
assert metadata["sheet_name"] == "Sheet1"
|
|
assert metadata["row_idx"] == 2, "the row number the spreadsheet shows, not the offset"
|
|
assert metadata["col_idx"] == 2 and metadata["col_end"] == 3
|
|
|
|
|
|
def test_an_empty_cell_does_not_shift_the_ones_after_it() -> None:
|
|
"""A sheet stores only the cells that hold something, so the gaps have to
|
|
be put back or a row's third value reads as its second."""
|
|
book = _xlsx({"Sheet1": [["A", "B", "C"], ["one", "", "three"]]})
|
|
|
|
assert _texts(_parse(book)) == ["A: one; C: three"]
|
|
|
|
|
|
def test_a_column_with_no_header_keeps_its_value_alone() -> None:
|
|
book = _xlsx({"Sheet1": [["A"], ["one", "loose"]]})
|
|
|
|
assert _texts(_parse(book)) == ["A: one; loose"]
|
|
|
|
|
|
def test_every_sheet_is_read_and_numbered() -> None:
|
|
book = _xlsx({"First": [["A"], ["one"]], "Second": [["B"], ["two"]]})
|
|
|
|
sections = _parse(book)
|
|
|
|
assert [s.metadata["sheet_idx"] for s in sections] == [0, 1]
|
|
assert [s.metadata["sheet_name"] for s in sections] == ["First", "Second"]
|
|
|
|
|
|
def test_a_named_sheet_travels_with_the_row() -> None:
|
|
"""A row reading `Region: EU` in a sheet called `2024 Actuals` loses the
|
|
year the moment it is embedded, and the vector is all the search has."""
|
|
book = _xlsx({"2024 Actuals": [["Region"], ["EU"]]})
|
|
|
|
assert _texts(_parse(book)) == ["Region: EU -- 2024 Actuals"]
|
|
|
|
|
|
def test_a_sheet_still_called_sheet1_names_nothing() -> None:
|
|
for name in ("Sheet1", "sheet 2", "Sheet"):
|
|
book = _xlsx({name: [["Region"], ["EU"]]})
|
|
assert _texts(_parse(book)) == ["Region: EU"], name
|
|
|
|
|
|
def test_a_sheet_of_one_row_is_read_as_data() -> None:
|
|
"""It has no header to label anything with. RAGFlow drops such a sheet; a
|
|
row nobody can search is worse than a row with no labels."""
|
|
book = _xlsx({"Sheet1": [["alpha", "beta"]]})
|
|
|
|
assert _texts(_parse(book)) == ["alpha; beta"]
|
|
assert _parse(book)[0].metadata["row_idx"] == 1
|
|
|
|
|
|
def test_a_shared_string_is_read_from_its_table() -> None:
|
|
"""The common case in a real workbook: repeated text is stored once."""
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w") as package:
|
|
package.writestr(
|
|
"xl/workbook.xml",
|
|
f'<workbook xmlns="{_MAIN}" xmlns:r="{_RELS}"><sheets>'
|
|
'<sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>',
|
|
)
|
|
package.writestr(
|
|
"xl/_rels/workbook.xml.rels",
|
|
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
|
'<Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>',
|
|
)
|
|
package.writestr(
|
|
"xl/sharedStrings.xml",
|
|
f'<sst xmlns="{_MAIN}"><si><t>Region</t></si><si><r><t>E</t></r><r><t>U</t></r></si></sst>',
|
|
)
|
|
package.writestr(
|
|
"xl/worksheets/sheet1.xml",
|
|
f'<worksheet xmlns="{_MAIN}"><sheetData>'
|
|
'<row r="1"><c r="A1" t="s"><v>0</v></c></row>'
|
|
'<row r="2"><c r="A2" t="s"><v>1</v></c></row>'
|
|
"</sheetData></worksheet>",
|
|
)
|
|
|
|
assert _texts(_parse(buffer.getvalue())) == ["Region: EU"], "a string split into runs is still one string"
|
|
|
|
|
|
def test_numbers_keep_the_spelling_the_sheet_stored() -> None:
|
|
"""A count of 3 is not improved by being indexed as 3.0."""
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w") as package:
|
|
package.writestr(
|
|
"xl/workbook.xml",
|
|
f'<workbook xmlns="{_MAIN}" xmlns:r="{_RELS}"><sheets>'
|
|
'<sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>',
|
|
)
|
|
package.writestr(
|
|
"xl/_rels/workbook.xml.rels",
|
|
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
|
'<Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>',
|
|
)
|
|
package.writestr(
|
|
"xl/worksheets/sheet1.xml",
|
|
f'<worksheet xmlns="{_MAIN}"><sheetData>'
|
|
'<row r="1"><c r="A1" t="inlineStr"><is><t>Count</t></is></c></row>'
|
|
'<row r="2"><c r="A2"><v>3.0</v></c></row>'
|
|
'<row r="3"><c r="A3" t="b"><v>1</v></c></row>'
|
|
"</sheetData></worksheet>",
|
|
)
|
|
|
|
assert _texts(_parse(buffer.getvalue())) == ["Count: 3", "Count: TRUE"]
|
|
|
|
|
|
# -- separated values -----------------------------------------------
|
|
|
|
|
|
def test_a_csv_is_read_as_the_table_it_is() -> None:
|
|
body = b"Region,Revenue\nEU,1.2M\nAPAC,0.9M\n"
|
|
|
|
assert _texts(_parse(body, "book.csv")) == ["Region: EU; Revenue: 1.2M", "Region: APAC; Revenue: 0.9M"]
|
|
|
|
|
|
def test_a_csv_row_is_not_labelled_with_its_filename() -> None:
|
|
"""`Section.source` already carries it into every chunk."""
|
|
assert "book.csv" not in _texts(_parse(b"A,B\n1,2\n", "book.csv"))[0]
|
|
|
|
|
|
def test_semicolons_are_a_separator_where_a_locale_says_so() -> None:
|
|
"""A spreadsheet in a locale that writes decimals with a comma exports
|
|
semicolons, and reading it as commas gives one column of joined text."""
|
|
body = b"Region;Revenue\nEU;1,2\n"
|
|
|
|
assert _texts(_parse(body, "book.csv")) == ["Region: EU; Revenue: 1,2"]
|
|
|
|
|
|
def test_a_byte_order_mark_is_not_part_of_the_first_header() -> None:
|
|
body = "Region,Revenue\nEU,1.2M\n".encode()
|
|
|
|
assert _texts(_parse(body, "book.csv")) == ["Region: EU; Revenue: 1.2M"]
|
|
|
|
|
|
# -- the two renders, kept for a surface that shows a sheet ----------
|
|
|
|
|
|
def test_markdown_renders_every_sheet_under_its_own_heading() -> None:
|
|
book = _xlsx({"First": [["A", "B"], ["1", "2"]], "Second": [["C"], ["3"]]})
|
|
|
|
out = asyncio.run(ExcelParser().markdown(book, "book.xlsx"))
|
|
|
|
assert "## First" in out and "## Second" in out
|
|
assert "| A | B |" in out and "| 1 | 2 |" in out
|
|
|
|
|
|
def test_markdown_escapes_a_pipe_that_would_end_a_column() -> None:
|
|
book = _xlsx({"Sheet1": [["A"], ["one|two"]]})
|
|
|
|
assert "one\\|two" in asyncio.run(ExcelParser().markdown(book, "book.xlsx"))
|
|
|
|
|
|
def test_html_repeats_the_header_on_every_chunk() -> None:
|
|
"""A table of fifty thousand rows is a page nothing lays out, and a piece
|
|
without the header is a grid of unlabelled values."""
|
|
rows = [["A", "B"]] + [[str(n), "x"] for n in range(5)]
|
|
book = _xlsx({"Sheet1": rows})
|
|
|
|
tables = asyncio.run(ExcelParser().html(book, "book.xlsx", chunk_rows=2))
|
|
|
|
assert len(tables) == 3
|
|
assert all("<th>A</th><th>B</th>" in table for table in tables)
|
|
assert all(table.startswith("<table><caption>Sheet1</caption>") for table in tables)
|
|
|
|
|
|
def test_html_escapes_what_would_otherwise_be_markup() -> None:
|
|
"""The cell below holds the three characters `<b>` -- the fixture writes
|
|
them as XML entities because that is how a cell holds them. What comes back
|
|
must be escaped again, or a spreadsheet decides what the page renders."""
|
|
book = _xlsx({"Sheet1": [["A"], ["<b>"]]})
|
|
|
|
table = asyncio.run(ExcelParser().html(book, "book.xlsx"))[0]
|
|
|
|
assert "<td><b></td>" in table
|
|
assert "<td><b></td>" not in table
|
|
|
|
|
|
# -- what it claims, and what it refuses ----------------------------
|
|
|
|
|
|
def test_the_parser_claims_the_three_spreadsheet_types() -> None:
|
|
assert ExcelParser.supported_extensions() == [".csv", ".xls", ".xlsx"]
|
|
assert "text/csv" in ExcelParser.supported_media_types
|
|
|
|
|
|
def test_a_missing_path_is_reported_as_missing() -> None:
|
|
with pytest.raises(FileNotFoundError):
|
|
_parse("/nonexistent/book.xlsx")
|
|
|
|
|
|
def test_a_zip_that_is_not_a_workbook_is_refused() -> None:
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w") as package:
|
|
package.writestr("mimetype", "application/zip")
|
|
|
|
with pytest.raises(ValueError, match="as a spreadsheet"):
|
|
_parse(buffer.getvalue())
|
|
|
|
|
|
@pytest.mark.skipif(shutil.which("soffice") is None, reason="LibreOffice is not installed here")
|
|
def test_a_legacy_workbook_is_converted_and_read(tmp_path) -> None:
|
|
"""The one format with no reader here. Against the real converter, because
|
|
the stubs elsewhere prove the wiring and only this proves the argv."""
|
|
from raven.utils.office import find_soffice, to_pdf
|
|
|
|
(tmp_path / "book.csv").write_text("Region,Revenue\nEU,1.2M\n")
|
|
staged = tmp_path / "out"
|
|
staged.mkdir()
|
|
to_pdf(tmp_path / "book.csv", staged, executable=find_soffice(), timeout_s=120.0, fmt="xls")
|
|
legacy = next(Path(staged).glob("*.xls"))
|
|
|
|
assert _texts(_parse(legacy.read_bytes(), "book.xls")) == ["Region: EU; Revenue: 1.2M -- book"]
|