Files
AgentLab/backend/app/memory/parsing.py
T
ThearchyHelios 913380f738 倒排索引取代全表重算;PDF/Word 终于传得进来
**倒排**:以前每次检索都 select(Chunk) 全量载入,再在 Python 里重建一遍 BM25
——不只是扫表,是对每一段重新分词、重新统计词频,每次查询都来一遍。几百段
无感,上万段就是秒级,而那正是知识库开始有用的规模。

没用 SQLite 的 FTS5。方案里写了实施前先验证,验了:trigram 分词器要求查询
至少三个字符,中文的「商家」「订单」「权限」这些两字词一个都召不回。照搬会
让召回大幅倒退。现有分词器本来就做中文单字 + 二元组,自己存一张 chunk_terms
既保住召回,也不把知识库锁死在 SQLite 上。

快是次要的,一致才是前提——所以先写了"倒排必须和全表扫给出同一个名次"的
测试。它当场抓到两个真问题:

1. BM25 被算了两次:倒排按全集统计(N、avg_len、df)算一次,hybrid_rank
   又在候选子集上重建一次,而子集的 df 和平均长度是另一套数。改成把倒排
   算好的分传下去,不再重算。
2. 原来的 BM25.score 遍历的是**带重复**的查询词表:「导出订单最多多少行」
   里「多」出现两次,贡献就加两次。倒排用 set() 去重,顶部那条差了 2.32。
   改成按查询词频加权。

还有一处是排序确定性:分数并列时稳定排序保留输入顺序,而两条路径喂进去的
顺序天生不同——同一个查询会因为走了哪条路给出不同名次。两边都按 id 定序。

倒排跟着 ingest 建、跟着删文档清、跟着 reindex 重建;没建倒排的片段(存量
数据升级上来就是这样)退回全表扫——宁可慢,也不要因为索引没建好就说"没搜到"。

**解析**:upload 以前只收 UTF-8,PDF 传上去直接 415,而 mime 字段记了却从不
参与判断。现在认 PDF / DOCX / HTML。解析库走可选依赖 [docs](几十兆,只用
纯文本的人不该为此付出安装时间),HTML 用已在依赖里的 bs4。

几处是实际验出来的,不是想出来的:DOCX 要连表格一起取(合同和口径说明的关键
信息常常整个在表里);PDF 每行拖着排版填充空格,不清掉会混进切块和词频统计
(实测 416 字里只有 68 字是正文);扫描件提不出文字要明说,否则悄悄存一份
空文档,用户以为传成功了却永远搜不到。

PDF/DOCX 两条路径在临时 venv 里用真文件验过(含中文、表格、扫描件、坏文件),
没有动开发环境。
2026-09-19 09:44:09 +08:00

121 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""把上传的文件变成文本。
在此之前 upload 只接受 UTF-8:PDF 传上去直接 415,而 mime 字段记了却从不
参与任何判断。知识库里最常见的恰恰是 PDF 和 Word。
PDF/DOCX 的解析库走可选依赖(pyproject 的 [docs]),和 [db]、[microvm] 一样
——它们加起来几十兆,而只用纯文本的人不该为此付出安装时间。没装时给的报错
要能照着做,不是一句 ImportError。
HTML 用已经在依赖里的 beautifulsoup4,不额外引入东西。
"""
from __future__ import annotations
import io
import re
#: 认得出的扩展名 → 处理方式。mime 不可靠(浏览器给 .md 报 application/octet-stream)
_PDF = {".pdf"}
_DOCX = {".docx"}
_HTML = {".html", ".htm"}
class UnsupportedDocument(ValueError):
"""认不出或解析不了。message 直接给用户看。"""
def _ext(filename: str) -> str:
idx = filename.rfind(".")
return filename[idx:].lower() if idx >= 0 else ""
def _from_pdf(raw: bytes) -> str:
try:
from pypdf import PdfReader
except ImportError as e:
raise UnsupportedDocument(
"要读 PDF 得先装解析库:pip install 'agentlab-backend[docs]'"
) from e
try:
reader = PdfReader(io.BytesIO(raw))
except Exception as e: # noqa: BLE001
raise UnsupportedDocument(f"这个 PDF 读不开:{type(e).__name__}: {e}") from e
# 按页拼,页与页之间留空行——切块是按段落切的,页边界正好是天然的段落边界
pages = []
for i, page in enumerate(reader.pages):
try:
pages.append(page.extract_text() or "")
except Exception: # noqa: BLE001 - 单页坏了不该毁掉整份文档
pages.append(f"(第 {i + 1} 页解析失败)")
# PDF 抽出来的每行都拖着排版留下的填充空格,不清掉会混进切块和词频统计
cleaned = []
for page in pages:
lines = [ln.rstrip() for ln in page.splitlines()]
body = "\n".join(ln for ln in lines if ln.strip())
if body:
cleaned.append(body)
text = "\n\n".join(cleaned)
if not text.strip():
raise UnsupportedDocument(
"这个 PDF 里没有可提取的文字——多半是扫描件。"
"扫描件要先过 OCR,这里不做图像识别。"
)
return text
def _from_docx(raw: bytes) -> str:
try:
import docx
except ImportError as e:
raise UnsupportedDocument(
"要读 Word 得先装解析库:pip install 'agentlab-backend[docs]'"
) from e
try:
doc = docx.Document(io.BytesIO(raw))
except Exception as e: # noqa: BLE001
raise UnsupportedDocument(f"这个 Word 文档读不开:{type(e).__name__}: {e}") from e
parts = [p.text.strip() for p in doc.paragraphs if p.text.strip()]
# 表格也要:合同、口径说明这类文档的关键信息常常整个在表里,
# 只取段落等于把它们全丢了
for table in doc.tables:
for row in table.rows:
cells = [c.text.strip() for c in row.cells if c.text.strip()]
if cells:
parts.append(" | ".join(cells))
text = "\n\n".join(parts)
if not text.strip():
raise UnsupportedDocument("这个 Word 文档里没有文字内容")
return text
def _from_html(raw: bytes) -> str:
from bs4 import BeautifulSoup
soup = BeautifulSoup(raw.decode("utf-8", errors="replace"), "html.parser")
for tag in soup(["script", "style", "nav", "footer"]):
tag.decompose()
text = soup.get_text("\n")
# 连续空行压成一个:HTML 转出来到处是空行,会把切块的段落判断搅乱
return re.sub(r"\n{3,}", "\n\n", text).strip()
def extract(raw: bytes, filename: str, mime: str = "") -> str:
"""文件字节 → 文本。认不出就按 UTF-8 文本试。"""
ext = _ext(filename)
if ext in _PDF or mime == "application/pdf":
return _from_pdf(raw)
if ext in _DOCX or "wordprocessingml" in mime:
return _from_docx(raw)
if ext in _HTML or mime == "text/html":
return _from_html(raw)
try:
return raw.decode("utf-8")
except UnicodeDecodeError as e:
raise UnsupportedDocument(
f"读不了 {filename or '这个文件'}:它不是 UTF-8 文本,"
f"也不是认得出的 PDF / Word / HTML。"
) from e