WeKnora icon indicating copy to clipboard operation
WeKnora copied to clipboard

[Bug]: 内置 PDF 解析丢失正文数字,并破坏简单表格的行列对应

Open gongwen opened this issue 2 months ago • 3 comments

Affected Component

Document Reader Service

Bug Description

内置 PDFParser 解析原生、可选中文字的 PDF 时,布局重建和后处理会拆坏数字、丢弃数量列,并破坏简单表格中项目与数量的对应关系。解析没有抛出错误,调用方收到成功结果,但正文已经缺损。

问题最初在飞书附件问答中发现,随后直接调用 DocReader 用同一份合成 PDF 复现;复现不依赖飞书、网络资源或 LLM。PDFium 原始文本包含完整数据,因此缺失发生在内置布局/清理阶段。所有使用同一内置解析器的入口都可能受影响。

Steps to Reproduce

  1. 在仓库根目录使用已安装 DocReader 依赖的 Python 环境,采用内置解析器的默认配置(开启布局重建,未强制扫描模式)。

  2. 将下方脚本保存为 reproduce_pdf.py,运行:

    uv run --project docreader --python 3.10.18 python reproduce_pdf.py
    
  3. 对比脚本打印的 PDFium 原始文本和 PDFParser 最终输出;最后的数量保留断言失败。

脚本内含原始合成 PDF 的压缩编码,不需要额外下载样本,也不需要安装 PDF 生成库。样本为两页、3,303 字节,SHA-256 为 363b41b90351914dfa2f7f1ef74870f7be604ef3bf1cdf57a540254a07fce973。已在现有 DocReader 容器中实际运行以下脚本并复现失败。

完整复现脚本(含合成 PDF)
import base64
import hashlib
import re
import zlib

import pypdfium2 as pdfium
from docreader.parser.pdf_parser import PDFParser, _postprocess_pdf_text

# Original 3,303-byte synthetic PDF, compressed only to keep this report small.
data = zlib.decompress(base64.b64decode("""
eNrVV8mW6sgR3fMVKiYxa0ITiFkIMc+zEAgpAYGmkoT9nhf+AXvnvb/Vgqr3mu7q4+7jnbVQZkZG3oi4kZEnMzbihSyWy4di
//rnP/4NTYBju35POUItYAFX8YEGBRqQZqt3E1g+lLAdYHn23VVBMoRBKGQfryGOCyECBuHBcAIhAg4Rj16oXA4BS3so4C+K
dcUDgh1AISIw/gJ8XVUgpGmptqZbZwhZ6lbN8vRfBAPFBNADHpnej/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Bk7s4qgXqNL
/BZPdCtZOJo+bEVOcPg6GDZgwlhLuIeRNkyslIrE3mr8JJw97wbFZarrHWQ8eh9kvFZMnjj18JF6c3bmDm9N8r9TcN9ccAqh
EIaF0J8fRJEkQUIn6KeMCq47zxnrpwxD8S8yHGW/yAj861oSz3+R0TjzVcZSv5VhKEt/kWHUF18wlnnxxXeV4DrgPk+VNg+F
thxOKSRNkRiuaCcKHBUSQzFFJfPUkaAV8oSX/1hjF4q9vDLOv//KyGYhTQ+uB795bwRuWCcbop+vi+BKaPsQ9dGf6n8Dj3Q8
TzLF9Z8JwhkaDcVizaEQ+g/9wLKi
"""))
assert hashlib.sha256(data).hexdigest() == (
    "363b41b90351914dfa2f7f1ef74870f7be604ef3bf1cdf57a540254a07fce973"
)

print("=== PDFium plain text ===")
with pdfium.PdfDocument(data) as pdf:
    for page in pdf:
        textpage = page.get_textpage()
        try:
            print(textpage.get_text_range())
        finally:
            textpage.close()
            page.close()

print("=== PDFParser final content ===")
doc = PDFParser(file_name="C26-file-sample.pdf", file_type="pdf").parse_into_text(data)
print(doc.content)
print(doc.metadata)
print("=== Numeric-only body lines, without any chart ===")
print(_postprocess_pdf_text("Quantity\n124\n237\n68\n91\nEnd of inventory."))

assert all(re.search(rf"(?<!\d){n}(?!\d)", doc.content)
           for n in (124, 237, 68, 91)), "Body quantities were dropped or split"

Expected Behavior

保留可读正文、完整数字及其行列对应关系:

项目 数量
Aster 124
Willow 237
Hazel 68
Rowan 91

下游应能根据四行得到合计 520;文件编号 FILE-OAK-9357 和末页标记 TAIL-5826 保留。允许保留少量页码,优先避免误删正文;本报告不要求解析器计算合计。

Actual Behavior

项目/内容 最终解析结果
Aster / 124 名称与数量被拆入不同阅读列,数量变成 1 24
Willow / 237 名称变成 Wi l low,数量 237 被删除
Hazel / 68 数量列被删除,68 缺失
Rowan / 91 数量列被删除,91 缺失
Inventory sample 标题被拆成 Inventor sam le 和另一行 y p

编号和末页标记仍在,但不能据此认定正文提取完整。完整输出为 627 个字符,元数据仍正常返回两页原生文本:

page_count=2
scanned_page_count=0
text_page_count=2
image_source_type=pdf_text_layer

WeKnora Version

源代码核对基线:462999ec3f5c1467ef0ccf5cf8c422393f40a0e6。

本次复现容器中的 docreader/parser/pdf_parser.py 与该基线文件逐字节一致,SHA-256 为 6e95dc00777058172ab485bc540eed62e62d246d4c60555f02e3ec1bd6b190c4。这里核对的是实际解析器源文件,不以镜像的 latest 标签作为版本依据。

Deployment Method

Docker Compose,直接在 DocReader 容器内调用 Python 解析器。

Operating System

Linux arm64 容器,Python 3.10.18。

Relevant Logs

解析器未报错。完整脚本末尾输出:

=== Numeric-only body lines, without any chart ===
Quantity
End of inventory.
AssertionError: Body quantities were dropped or split

其中传入后处理的原文为 Quantity\n124\n237\n68\n91\nEnd of inventory.,没有任何图表。四行数字被全部删除。

已确认的原因与修复边界

  • 窄列过滤 将第二页 QUANTITY / 68 / 91 / 2 / 2 识别为边栏噪声,删除整列。
  • 页码清理 删除任意 1–3 位纯数字行,没有位置判定;图表碎片清理 也可能删除没有图表的连续数字行。
  • 布局质量回退 未发现该样本中的丢失,且判断早于后处理。

修复需要同时保留数值和对应关系,并回归真正双栏、重复数量、空单元格、隐藏/页外文字及扫描/图表图片路径。仅增加“数字有缺失就整页回退到原始文本”的判断不足:原始文本可能包含已被布局路径过滤的隐藏文字,也可能使真正双栏变成交错顺序。此前隔离验证已复现前一种退化,因此尚未应用该候选。

本 issue 记录已复现缺陷,目前没有对应修复 PR。

Confirmation

  • [x] I have searched existing issues and confirmed this is a new one

gongwen avatar Sep 12 '26 14:09 gongwen

I've verified the three culprits line-by-line against current main (the parser file is byte-identical to your pinned SHA) and have a layered fix plan before opening PRs. Your root-cause analysis and the fix boundary (no whole-page raw-text fallback) all check out; a few additional mechanics worth recording:

  • Word splitting ("Wi l low", "Inventor sam le"): _find_split cuts at any full-height empty x-band. In a table, the name/quantity gutter qualifies — but so does an inter-letter tracking gap once rows are aligned, because the recursive _split_columns re-searches inside sub-columns with the same min_gap. So the same recursion both isolates the quantity column and slices words apart; one veto can fix both.
  • Cheap chart gating is already possible: vector_clips is computed before _postprocess_pdf_text runs in the page loop, so a has_charts flag can be threaded in with zero reordering — chart debris can only originate from charts, so stripping numeric runs on a chart-less page (your _postprocess_pdf_text repro) is semantically wrong today.
  • Per-page postprocessing is a free position proxy: _postprocess_pdf_text is called per page, so "first/last non-empty line of the page" is available without any coordinate plumbing — enough to stop ^\d{1,3}$ from killing mid-body quantities.

Proposed layering:

  1. PR-1 — postprocess gating (low risk): pass has_charts into _postprocess_pdf_text and skip the numeric-run debris strip when the page has no vector clips; restrict page-number removal to pure-number lines at the first/last line of the page (optionally AND value ≈ page index). Regression: your pinned synthetic PDF as a fixture (same pattern as the existing issue_2634 fixture) plus the numeric-only postprocess case.
  2. PR-2 — layout row-alignment veto: a column whose lines share baselines (y-centers within line height) with lines of an adjacent column is a table column, not a margin watermark — veto both the _is_artifact_column condemnation and further recursive splits between row-aligned halves. This addresses the dropped QUANTITY column and the intra-word cuts together. Regressions per your list: real two-column pages, repeated quantities, empty cells, hidden/off-page text, scanned/chart-image paths (chart axis debris must still be cleaned).
  3. Optional PR-3 — integrity guard: make the strippers record dropped lines; after postprocess, restore dropped digit-bearing lines that were not in page-number position. Line-selective restore only — we agree whole-page fallback to raw text reintroduces hidden text and interleaves true two-column order.

Unless there are objections to the layering, I'll start with PR-1.

vicfei avatar Sep 15 '26 10:09 vicfei

PR-1 (postprocess gating) is up: #3283. Numeric-run debris stripping now requires the page to actually have vector figure clips, and page-number removal is gated on first/last-line position plus page-sequence value match — your isolated _postprocess_pdf_text repro and mid-body quantities are covered by tests. The layout-side work (artifact-column veto, intra-word split veto) follows as PR-2 as discussed.

vicfei avatar Sep 15 '26 11:09 vicfei

The layout layer has joined #3283 as a second commit (kept in one PR because the end-to-end regression on your fixture only passes with both layers, and stacked PRs don't work across forks). Instrumenting your PDF exposed three layout defects beyond the postprocess ones:

  1. Row-aligned table cells were split into reading-order columns, which is what delivered the QUANTITY column to the margin-noise filter — splits whose narrower side is a row-aligned cell column are now vetoed (watermark stacks excluded by per-line glyph count, not height — your quantity column is as tall as the page).
  2. Line grouping used glyph-center distance; ascender/descender boxes shift centers by ~1/3 font size — exactly why Inventory sample became Inventor sam le + y p. Lines are now grouped by vertical interval overlap.
  3. Word-space inference fired below letter tracking because narrow glyphs (i, l, 1) drag the width median down — that's the 124 → 1 24. The gap threshold now also floors at a share of glyph height.

Your reproduce_pdf.py passes end to end now, and the fixture (your exact PDF, SHA pinned, regenerable) is committed with assertions for quantities, words, markers, and row correspondence (Aster\s+124 …). Result on page 1: ITEM QUANTITY / Aster 124 / Willow 237. Thanks for the exceptional report — the pinned fixture and pre-analyzed root causes made this tractable.

vicfei avatar Sep 15 '26 12:09 vicfei