Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix(doclib): preserve punctuation in FTS queries

Ymmcce9c8001e23e7
diff --git a/mineru/doclib/core/fts.py b/mineru/doclib/core/fts.py
index 1e9ec098..6d1e028e 100644
--- a/mineru/doclib/core/fts.py
+++ b/mineru/doclib/core/fts.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import unicodedata
from typing import cast
try:
@@ -70,7 +71,7 @@ class FTSManager:
)
async def search(self, query: str, limit: int = 200) -> list[FtsContentSearchRow]:
- tokens = _sanitize_query_tokens(tokenize_for_query(query))
+ tokens = _literal_query_tokens(tokenize_for_query(query))
if not tokens:
return []
fts_query = " ".join(tokens)
@@ -110,10 +111,10 @@ class FTSManager:
async def search_filenames(self, query: str, limit: int | None = 50) -> list[FtsFilenameSearchRow]:
"""仅对文件名查询的最后一个词默认启用前缀匹配;None 获取完整候选快照。"""
- tokens = _sanitize_query_tokens(tokenize_for_query(query))
+ tokens = _literal_query_tokens(tokenize_for_query(query))
if not tokens:
return []
- if not query.rstrip().endswith("*"):
+ if not tokens[-1].endswith("*"):
tokens[-1] += "*"
fts_query = " ".join(tokens)
sql = (
@@ -140,14 +141,26 @@ class FTSManager:
# ── helpers ────────────────────────────────────────────────────────
-def _sanitize_query_tokens(tokenized: str) -> list[str]:
- """Remove special characters and FTS5 operators from query tokens."""
- safe: list[str] = []
- for t in tokenized.split():
- t = t.strip().replace('"', "").replace(".", "").replace("-", "")
- if t and t.upper() not in ("AND", "OR", "NOT", "NEAR"):
- safe.append(t)
- return safe
+def _literal_query_tokens(tokenized: str) -> list[str]:
+ """Quote search terms for FTS5 and keep prefix markers outside quotes."""
+ terms: list[str] = []
+ for token in tokenized.split():
+ term = token.rstrip("*")
+ prefix = term != token
+ if not term:
+ # Jieba emits a trailing asterisk as a separate token.
+ if terms and not terms[-1].endswith("*"):
+ terms[-1] += "*"
+ continue
+ if term.upper() in ("AND", "OR", "NOT", "NEAR"):
+ continue
+ # The unicode61 index treats letters, numbers, and private-use characters as token text.
+ if not any(char.isalnum() or unicodedata.category(char) == "Co" for char in term):
+ continue
+ escaped = term.replace('"', '""')
+ suffix = "*" if prefix else ""
+ terms.append(f'"{escaped}"{suffix}')
+ return terms
MAX_FTS_CHARS = 30_000
diff --git a/tests/unittest/test_doclib_find_pagination.py b/tests/unittest/test_doclib_find_pagination.py
index 79b8fc50..234b69a7 100644
--- a/tests/unittest/test_doclib_find_pagination.py
+++ b/tests/unittest/test_doclib_find_pagination.py
@@ -76,6 +76,25 @@ def test_filename_prefix_is_applied_only_to_final_token(tmp_path: Path) -> None:
asyncio.run(run())
+def test_doclib_search_accepts_punctuation_in_queries(tmp_path: Path) -> None:
+ """使用真实 SQLite 索引验证普通标点不会使文件名或正文查询失效。"""
+
+ async def run() -> None:
+ db, fts, _ = await _filename_library(tmp_path, ["C++ guide.pdf", "Python guide.pdf"])
+ try:
+ await fts.replace(sha256="a" * 64, tier="standard", text="C++ guide to AT&T services", title="", author="")
+ await fts.replace(sha256="b" * 64, tier="standard", text="Python guide to other services", title="", author="")
+ for query in ("C++ guide", "(C++) gui", "C++ gui*"):
+ assert [row["file_id"] for row in await fts.search_filenames(query)] == [1]
+ for query in ("C++: guide", "AT&T", "(AT&T) serv*"):
+ assert [row["sha256"] for row in await fts.search(query)] == ["a" * 64]
+ assert await fts.search("!()++") == []
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
def test_find_paginates_all_candidates_in_stable_order(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""六百余条同分候选跨过旧上限与元信息批次,每页无遗漏且总数不随 limit 变化。"""