pdf_loader.py
12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
from __future__ import annotations
import logging
import os
import re
from src.rag.config import RAG_PDF_VLM_PARSE
from src.rag.errors import PdfVlmParseError
from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import RAG_CHUNKER_VERSION, RAG_PARSER_VERSION
from src.rag.loaders.pdf_vlm import VlmParseStats, vlm_blocks_for_pages
from src.rag.loaders.markdown_loader import parse_markdown_text
logger = logging.getLogger(__name__)
class PdfLoader:
extensions = {".pdf"}
def load(self, path: str) -> list[DocumentBlock]:
return _load_pdf(path)
def _load_pdf(path: str) -> list[DocumentBlock]:
# 单一路线:整篇 PDF 全部走 VLM 整页转写(不再区分文本/表格/图片页)。
# VLM 对这些图文混排的产品手册最稳:图片表格、跨页、数字逐字都能正确还原。
filename = os.path.basename(path)
total_pages = _page_count(path)
logger.info("[RAG] 开始解析 PDF: %s(共 %d 页,全部走 VLM 整页转写)", filename, total_pages)
if not RAG_PDF_VLM_PARSE:
raise PdfVlmParseError(
"PDF 解析需要整页 VLM,但 RAG_PDF_VLM_PARSE 已关闭",
detail={"file": filename, "total_pages": total_pages},
)
blocks, stats = vlm_blocks_for_pages(path, list(range(1, total_pages + 1)))
blocks = _dedupe_blocks(blocks)
if not blocks:
raise RuntimeError("PDF 未提取到可索引内容。")
_attach_loader_metadata(blocks, stats)
blocks.sort(key=lambda b: (b.page_number or 0, b.source_offset or 0))
blocks = _stitch_continued_tables(blocks)
_assign_headings(blocks)
logger.info(
"[RAG] PDF 解析完成: %s, 共 %d 个块;VLM 统计: 页=%d, tokens=%d, 用时=%dms",
filename, len(blocks), stats.page_count, stats.total_tokens, stats.duration_ms,
)
return blocks
def _page_count(path: str) -> int:
import fitz
with fitz.open(path) as doc:
return doc.page_count
def _stitch_continued_tables(blocks: list[DocumentBlock]) -> list[DocumentBlock]:
"""跨页表格拼接:VLM 在页尾给未结束的表打了 table_continues 标记,下一张表是其延续。"""
result: list[DocumentBlock] = []
i = 0
while i < len(blocks):
block = blocks[i]
if block.block_type == "table" and block.metadata.get("table_continues"):
j = i + 1
if j < len(blocks) and blocks[j].block_type == "table":
cont = blocks[j]
block.text = _merge_table_markdown(block.text, cont.text)
block.metadata["page_end"] = cont.page_number or block.metadata.get("page_end")
block.metadata["continued_table"] = True
block.metadata.pop("table_continues", None)
# 续表本身可能再次续页:保留下一张表的标记到合并块上
if cont.metadata.get("table_continues"):
block.metadata["table_continues"] = True
blocks.pop(j)
continue # 不前移 i,继续尝试与再下一张表拼接
block.metadata.pop("table_continues", None)
result.append(block)
i += 1
return result
def blocks_from_markdown(markdown: str, page_number: int | None = None, parse_method: str = "markdown") -> list[DocumentBlock]:
blocks = parse_markdown_text(markdown, inherited={"parse_method": parse_method})
for block in blocks:
block.page_number = page_number or block.page_number
block.metadata["parse_method"] = parse_method
if block.block_type == "table":
block.metadata["table_markdown"] = True
return blocks
# ---------------------------------------------------------------------------
# Heading detection(VLM 已用 # 标好层级;此处仅对未标记段落按编号体系兜底识别)
# ---------------------------------------------------------------------------
def _detect_heading(text: str) -> tuple[int, str] | None:
"""按编号体系识别标题段落。Returns (level, text) or None。"""
if len(text) > 100 or "\n" in text.strip():
return None
first = text.strip()
if not first or _looks_like_table_residual(first):
return None
# Exclude footnotes and notes
if re.match(r"^(说明|注|备注|注意|提示|参考|附注|PS|ps)[::·]", first):
return None
# Numeric heading: "1.2.3 Title"
match = re.match(r"^(\d+(?:\.\d+){0,4})\s+(.{2,80})$", first)
if match:
return (match.group(1).count(".") + 1, first)
# Chinese numeric heading: "一、Title" / "(一)Title"
match = re.match(r"^[((]?[一二三四五六七八九十]+[))、..]\s*(.{2,80})$", first)
if match:
return (1, first)
return None
def _canonical_heading_level(text: str, fallback_level: int) -> int:
"""按编号体系归一标题层级,消除逐页独立转写造成的同级章节层级漂移。
“一、/二、/(三)”等中文数字一级章节 → 1;“1./1.2/1.2.3”按点分段数定级;
其余无编号标题保留 VLM 给的 markdown 层级。
"""
first = text.strip()
if re.match(r"^[((]?[一二三四五六七八九十]+[))、..]", first):
return 1
match = re.match(r"^(\d+(?:\.\d+){0,4})", first)
if match:
return match.group(1).count(".") + 1
return max(1, fallback_level)
def _update_headings(headings: list[str], heading: tuple[int, str]) -> list[str]:
level, text = heading
next_headings = list(headings[: max(0, level - 1)])
next_headings.append(text)
return next_headings
def _assign_headings(blocks: list[DocumentBlock]) -> None:
headings: list[str] = []
for block in blocks:
if block.block_type == "paragraph":
# VLM 路径已显式标记 heading(任意文案);但逐页独立转写会让同级章节的 # 层级
# 不一致(如“二、”在某页是 #、“三、”在另一页是 ##),导致 title_path 串成
# “二 / 三”。这里按编号体系归一层级,保证全局章节结构一致。
if block.metadata.get("content_role") == "heading" and block.metadata.get("heading_level"):
level = _canonical_heading_level(block.text.strip(), int(block.metadata["heading_level"]))
block.metadata["heading_level"] = level
heading = (level, block.text.strip())
else:
heading = _detect_heading(block.text)
if heading:
headings = _update_headings(headings, heading)
block.metadata["content_role"] = "heading"
block.metadata["heading_level"] = heading[0]
else:
block.metadata.setdefault("content_role", "body")
elif block.block_type == "table":
pass # Tables inherit headings from surrounding paragraphs
block.title_path = " / ".join(headings)
if headings:
block.metadata["section_title"] = headings[-1]
block.metadata["section_path"] = list(headings)
block.metadata["section_index"] = len(headings)
if block.block_type == "table":
block.metadata["content_role"] = "table"
block.metadata["table_header"] = _table_header(block.text)
block.metadata["table_id"] = f"p{block.page_number}_t{(block.metadata.get('table_index', 0)) + 1}"
if block.title_path:
block.title_path += f" / P{block.page_number} 表{(block.metadata.get('table_index', 0)) + 1}"
else:
block.title_path = f"P{block.page_number} 表{(block.metadata.get('table_index', 0)) + 1}"
# ---------------------------------------------------------------------------
# Deduplication
# ---------------------------------------------------------------------------
def _dedupe_blocks(blocks: list[DocumentBlock]) -> list[DocumentBlock]:
seen_tables: set[tuple[int | None, str]] = set()
deduped: list[DocumentBlock] = []
for block in blocks:
if block.block_type == "table":
signature = (block.page_number, _table_signature(block.text))
if signature in seen_tables:
continue
seen_tables.add(signature)
deduped.append(block)
return deduped
def _table_signature(text: str) -> str:
return re.sub(r"\s+", "", text or "").lower()
# ---------------------------------------------------------------------------
# Cross-page table merging(供 _stitch_continued_tables 拼接 VLM 续表)
# ---------------------------------------------------------------------------
def _merge_table_markdown(previous: str, current: str) -> str:
previous_rows = _table_rows(previous)
current_rows = _table_rows(current)
if len(current_rows) <= 2:
return previous
if current_rows[0] == previous_rows[0]:
return "\n".join([*previous_rows, *current_rows[2:]])
else:
return "\n".join([*previous_rows, current_rows[0], *current_rows[2:]])
# ---------------------------------------------------------------------------
# Table utility
# ---------------------------------------------------------------------------
def _table_rows(markdown: str) -> list[str]:
return [line.strip() for line in markdown.splitlines() if line.strip().startswith("|")]
def _table_header(markdown: str) -> str:
rows = _table_rows(markdown)
return rows[0] if rows else ""
# ---------------------------------------------------------------------------
# Text helpers
# ---------------------------------------------------------------------------
def _looks_like_table_residual(text: str) -> bool:
compact = re.sub(r"\s+", "", text)
return len(compact) <= 2
# ---------------------------------------------------------------------------
# Loader metadata
# ---------------------------------------------------------------------------
# 文档级 VLM 统计键(每个块都带同一份值,便于 service 落库;切块时会被剥离,不污染分片)
VLM_STAT_KEYS = (
"parse_engine", "vlm_page_count", "vlm_total_tokens",
"vlm_input_tokens", "vlm_output_tokens", "vlm_image_tokens", "vlm_duration_ms",
)
def _attach_loader_metadata(blocks: list[DocumentBlock], stats: VlmParseStats) -> None:
page_numbers = [block.page_number for block in blocks if block.page_number is not None]
parse_methods = sorted({str(block.metadata.get("parse_method")) for block in blocks if block.metadata.get("parse_method")})
quality = _text_quality("\n".join(block.text for block in blocks))
page_count = max(page_numbers) if page_numbers else None
doc_stats = {
"parse_engine": "vlm",
"vlm_page_count": stats.page_count,
"vlm_total_tokens": stats.total_tokens,
"vlm_input_tokens": stats.input_tokens,
"vlm_output_tokens": stats.output_tokens,
"vlm_image_tokens": stats.image_tokens,
"vlm_duration_ms": stats.duration_ms,
}
for block in blocks:
block.metadata.setdefault("parser_version", RAG_PARSER_VERSION)
block.metadata.setdefault("chunker_version", RAG_CHUNKER_VERSION)
block.metadata.setdefault("parse_status", "ok")
block.metadata.setdefault("parse_quality", "normal" if quality == "ok" else quality)
if page_count:
block.metadata.setdefault("source_page_count", page_count)
if parse_methods:
block.metadata.setdefault("parse_methods", parse_methods)
for key, value in doc_stats.items():
block.metadata.setdefault(key, value)
def doc_vlm_stats(blocks: list[DocumentBlock]) -> dict[str, int]:
"""从解析出的 blocks 里取出文档级 VLM 统计(token/页数/耗时),供 service 落库。"""
for block in blocks:
if block.metadata.get("parse_engine") == "vlm":
return {key: block.metadata.get(key) for key in VLM_STAT_KEYS}
return {}
def _text_quality(text: str) -> str:
if not text:
return "empty"
bad_chars = text.count("�")
cjk_chars = len(re.findall(r"[一-鿿]", text))
if bad_chars / max(1, len(text)) > 0.02:
return "suspect_encoding"
if cjk_chars == 0 and re.search(r"[A-Za-z]{20,}", text):
return "low_cjk"
return "ok"
register_loader(PdfLoader())