engine.py
23.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
"""
整页 VLM 解析路径(PDF 的唯一解析方式)。
整篇 PDF 的每一页都整页渲染后送多模态视觉模型:正文转写为 Markdown,表格转写为
HTML <table>(带 rowspan/colspan)。价格表/保障图常被做成图片,原生抽取极不可靠,
故不再区分文本/表格/图片页。HTML 表格在代码侧按 rowspan/colspan 展开成「每个合并格
逐行/逐列填满」的标准 Markdown 表,从根上解决合并单元格留空的问题(无需模型自行重复值)。
单文件内按 RAG_PDF_VLM_CONCURRENCY 路并发转写各页,转写完成后按页码顺序重新组装。
设计原则:fail-fast,无任何降级兜底。
- 模型不可用 / 超时 / 返回为空 → 抛 PdfVlmParseError,
service.index_file 会把该文件标为显式失败状态、整份不入库。
"""
from __future__ import annotations
import logging
import os
import re
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from html.parser import HTMLParser
from typing import Any
from config import API_KEY
from src.rag.core.config import RAG_PDF_PAGE_RENDER_SCALE, RAG_PDF_VLM_CONCURRENCY, RAG_PDF_VLM_MODEL
from src.rag.core.errors import PdfVlmParseError
from src.rag.ingestion.loaders.base import DocumentBlock
from src.rag.ingestion.loaders.common import RAG_CHUNKER_VERSION, RAG_PARSER_VERSION
from src.rag.core.utils import normalize_text
logger = logging.getLogger(__name__)
# VLM 在表格未结束时于页尾追加的续表标记(供切块层跨页拼接使用)
TABLE_CONTINUES_MARKER = "<!--table-continues-->"
@dataclass
class VlmParseStats:
"""整篇 PDF 的 VLM 解析统计,落库用(token 消耗、页数、耗时)。"""
page_count: int = 0
input_tokens: int = 0
output_tokens: int = 0
image_tokens: int = 0
total_tokens: int = 0
duration_ms: int = 0
def add_page(self, usage: dict[str, int]) -> None:
self.page_count += 1
self.input_tokens += usage.get("input", 0)
self.output_tokens += usage.get("output", 0)
self.image_tokens += usage.get("image", 0)
self.total_tokens += usage.get("total", 0)
# PDF 整页 VLM 转写提示词。唯一变量是续表标记,直接用 f-string 嵌入。改提示词改这段。
_TRANSCRIBE_PROMPT = f"""你是严谨的 PDF 版面转写器。请把这张 PDF 页面的全部内容转写出来(正文用 Markdown,表格用 HTML),要求:
1. 必须严格按页面从上到下、从左到右的视觉阅读顺序转写,逐个元素依次输出;位于页面最顶部的内容(哪怕是一张没有标题、承接上一页的表格)必须排在输出最前面,禁止打乱或重排顺序。
2. 标题用 #/##/### 表示层级,保留原始编号(如“六、”“1.2”“PART 1”);正文用 Markdown 段落。
3. 【表格一律用 HTML <table> 输出】用 <tr>/<th>/<td> 还原表格,禁止使用 Markdown 表格语法。凡是视觉上跨多行或多列的单元格,必须用 rowspan / colspan 标注其真实跨度(依据单元格边框的覆盖范围判断,不是依据文字出现的位置);例如某个格子在视觉上纵跨“智界、享界”两行,就写 rowspan="2"。不要遗漏任何行或列,不要把不同的表格合并成一张。
4. 多层表头照实用多行 <tr> + rowspan/colspan 表达其层级,不要自行压平或改写表头文字。
5. 正文不要编造图中没有的内容;若本页顶部存在承接上一页的表格(没有重复表头),也要照常作为本页第一个元素用 <table> 转写其数据行,不要遗漏、不要移到后面。
6. 所有数字(价格、保额、折扣、期限等)必须逐字照抄,禁止改写、补零或推断。
7. 如果某张表格在本页底部尚未结束(下一页继续),在该表 </table> 之后另起一行输出 {TABLE_CONTINUES_MARKER}。
8. 除表格用 HTML <table> 外,其余所有内容必须是纯 Markdown / 纯文本,禁止输出 <div>/<p>/<strong>/<img>/<span> 等任何 HTML 标签;图标等装饰元素直接忽略,不要输出 <img>。
只输出转写正文(Markdown 段落 + HTML 表格),不要任何解释或代码块包裹。"""
# ---------------------------------------------------------------------------
# 公共入口
# ---------------------------------------------------------------------------
def vlm_blocks_for_pages(path: str, pages: list[int]) -> tuple[list[DocumentBlock], VlmParseStats]:
"""整页 VLM 转写并产出 DocumentBlock(每页 1 次调用,最多 RAG_PDF_VLM_CONCURRENCY 路并发)。
各页并发转写,全部完成后按页码顺序重新组装,保证阅读顺序、跨页拼接与 token 累计的确定性。
任一页失败即抛 PdfVlmParseError,整本文件 fail-fast。
"""
stats = VlmParseStats()
start = time.time()
total = len(pages)
concurrency = max(1, min(RAG_PDF_VLM_CONCURRENCY, total))
logger.info("[RAG] 开始整页 VLM 转写:共 %d 页,并发 %d 路", total, concurrency)
# page_number -> (page_blocks, usage);并发产出,后续按页码顺序组装
results: dict[int, tuple[list[DocumentBlock], dict[str, int]]] = {}
with ThreadPoolExecutor(max_workers=concurrency) as pool:
future_to_page = {
pool.submit(_transcribe_one_page, path, page_number, idx, total): page_number
for idx, page_number in enumerate(pages, start=1)
}
for future in as_completed(future_to_page):
page_number = future_to_page[future]
results[page_number] = future.result() # 任一页异常在此重新抛出 → fail-fast
blocks: list[DocumentBlock] = []
for page_number in pages:
page_blocks, usage = results[page_number]
stats.add_page(usage)
blocks.extend(page_blocks)
stats.duration_ms = int((time.time() - start) * 1000)
return blocks, stats
def _transcribe_one_page(path: str, page_number: int, idx: int, total: int) -> tuple[list[DocumentBlock], dict[str, int]]:
"""单页:渲染→VLM 转写→Markdown 切块,返回 (blocks, token 用量)。可被线程池并发调用。"""
logger.info("[RAG] 正在处理 第%d/%d 页(VLM 转写)...", idx, total)
image_path = render_page_png(path, page_number)
try:
markdown, usage = transcribe_page(image_path, page_number)
page_blocks = markdown_to_blocks(markdown, page_number)
logger.info(
"[RAG] 第%d页 VLM 处理完成:产出 %d 个块,本页 tokens=%d",
page_number, len(page_blocks), usage.get("total", 0),
)
return page_blocks, usage
finally:
_safe_remove(image_path)
# ---------------------------------------------------------------------------
# 渲染 / 转写
# ---------------------------------------------------------------------------
def render_page_png(path: str, page_number: int) -> str:
import fitz
with fitz.open(path) as doc:
page = doc[page_number - 1]
matrix = fitz.Matrix(RAG_PDF_PAGE_RENDER_SCALE, RAG_PDF_PAGE_RENDER_SCALE)
pix = page.get_pixmap(matrix=matrix, alpha=False)
fd, image_path = tempfile.mkstemp(prefix="rag_pdf_page_", suffix=".png")
os.close(fd)
pix.save(image_path)
return image_path
def transcribe_page(image_path: str, page_number: int) -> tuple[str, dict[str, int]]:
text, usage = _call_vision(image_path, _TRANSCRIBE_PROMPT, page_number)
markdown = normalize_text(text).strip()
if not markdown:
raise PdfVlmParseError(
f"PDF 整页 VLM 转写返回为空: page={page_number}",
detail={"page_number": page_number, "vision_model": RAG_PDF_VLM_MODEL},
)
return markdown, usage
def _call_vision(image_path: str, prompt: str, page_number: int) -> tuple[str, dict[str, int]]:
try:
import dashscope
except Exception as exc: # pragma: no cover - 依赖缺失
raise PdfVlmParseError(
"PDF VLM 解析依赖缺失: 请安装 dashscope",
detail={"page_number": page_number, "missing_dependency": str(exc)},
) from exc
image_uri = image_path if image_path.startswith("file://") else f"file://{image_path}"
last_error: Exception | None = None
for attempt in range(3):
try:
start = time.time()
response = dashscope.MultiModalConversation.call(
model=RAG_PDF_VLM_MODEL,
api_key=API_KEY,
messages=[{"role": "user", "content": [{"image": image_uri}, {"text": prompt}]}],
)
if getattr(response, "status_code", 200) != 200:
raise RuntimeError(f"dashscope status={getattr(response, 'status_code', None)} {getattr(response, 'message', '')}")
text = _dashscope_text(response)
usage = _usage_dict(response)
logger.info(
"[RAG] VLM 转写 p%d 完成: model=%s chars=%d duration_ms=%d tokens(in=%d, out=%d, image=%d, total=%d)",
page_number, RAG_PDF_VLM_MODEL, len(text), int((time.time() - start) * 1000),
usage["input"], usage["output"], usage["image"], usage["total"],
)
return text, usage
except Exception as exc:
last_error = exc
logger.warning("[RAG] VLM 转写 p%d 调用异常(%d/3): %s", page_number, attempt + 1, exc)
time.sleep(1.0 * (attempt + 1))
raise PdfVlmParseError(
f"PDF 整页 VLM 转写失败: page={page_number}",
detail={"page_number": page_number, "vision_model": RAG_PDF_VLM_MODEL, "error": str(last_error)},
)
def _usage_dict(response: Any) -> dict[str, int]:
"""从 dashscope 响应里提取本次 VLM 调用的 token 消耗(input/output/image/total)。"""
usage = getattr(response, "usage", None)
if usage is None and isinstance(response, dict):
usage = response.get("usage")
get = (usage.get if isinstance(usage, dict) else lambda k: getattr(usage, k, None)) if usage is not None else (lambda k: None)
input_tokens = int(get("input_tokens") or 0)
output_tokens = int(get("output_tokens") or 0)
image_tokens = int(get("image_tokens") or 0)
total = int(get("total_tokens") or 0) or (input_tokens + output_tokens)
return {"input": input_tokens, "output": output_tokens, "image": image_tokens, "total": total}
def _dashscope_text(response: Any) -> str:
output = getattr(response, "output", None) or {}
if isinstance(output, dict):
choices = output.get("choices") or []
texts: list[str] = []
for choice in choices:
message = choice.get("message") if isinstance(choice, dict) else None
content = (message or {}).get("content") if isinstance(message, dict) else None
if isinstance(content, list):
texts.extend(str(item.get("text") or "") for item in content if isinstance(item, dict))
elif content:
texts.append(str(content))
if texts:
return "\n".join(texts)
return str(getattr(response, "output", response))
# ---------------------------------------------------------------------------
# Markdown → DocumentBlock(保留标题块,供 _assign_headings 跨页继承)
# ---------------------------------------------------------------------------
def markdown_to_blocks(markdown: str, page_number: int) -> list[DocumentBlock]:
markdown, continues = _strip_continue_marker(markdown)
# 表格由 VLM 以 HTML <table> 输出,先按 rowspan/colspan 展开成填满的标准 Markdown 表(零标签),
# 再清洗掉正文里残留的非表格 HTML(div/p/strong/img…),保证分片内容不含任何 HTML 标签,
# 之后沿用纯 Markdown 的行式解析逻辑。
markdown = _convert_html_tables(markdown, page_number)
markdown = _sanitize_residual_html(markdown, page_number)
blocks: list[DocumentBlock] = []
para_buf: list[str] = []
table_buf: list[str] = []
# 引擎只造结构,不造 metadata 契约:parse_method / parser_version / page_start-end /
# parse_quality 等统一由编排器末尾的 enrich_blocks 补齐(见 orchestrator.load_pdf)。
# 这里只写引擎独有、后续无法再推导的信息。
def flush_para() -> None:
text = normalize_text("\n".join(para_buf)).strip()
if text:
blocks.append(DocumentBlock(text=text, block_type="paragraph", page_number=page_number,
source_offset=len(blocks), metadata={}))
para_buf.clear()
def flush_table() -> None:
rows = [line for line in table_buf if line.strip()]
if rows:
blocks.append(DocumentBlock(text=normalize_text("\n".join(rows)), block_type="table",
page_number=page_number, source_offset=len(blocks),
metadata={"table_markdown": True}))
table_buf.clear()
for raw in markdown.splitlines():
line = raw.rstrip()
stripped = line.strip()
heading = re.match(r"^(#{1,6})\s+(.+)$", stripped)
if heading:
flush_table()
flush_para()
# heading_marker_level 是引擎内部键(# 号个数)。逐页独立转写会让同级章节的
# # 层级不一致,编排器 _assign_headings 按编号体系归一后写成 heading_level 并 pop 掉。
meta = {"content_role": "heading", "heading_marker_level": len(heading.group(1))}
blocks.append(DocumentBlock(text=heading.group(2).strip(), block_type="paragraph",
page_number=page_number, source_offset=len(blocks), metadata=meta))
continue
if _is_table_row(stripped):
if para_buf:
flush_para()
table_buf.append(_normalize_table_line(stripped))
continue
# 非表格行:结束当前表格段
if table_buf:
flush_table()
if not stripped:
flush_para()
else:
para_buf.append(line)
flush_table()
flush_para()
# 续表标记落到最后一张表上
if continues:
for block in reversed(blocks):
if block.block_type == "table":
block.metadata["table_continues"] = True
break
return blocks
# ---------------------------------------------------------------------------
# HTML <table>(带 rowspan/colspan)→ 填满的标准 Markdown 表
# ---------------------------------------------------------------------------
_HTML_TABLE_RE = re.compile(r"<table\b.*?</table\s*>", re.S | re.I)
class _TableHTMLParser(HTMLParser):
"""解析单个 <table>,收集每个 <tr> 的 (单元格文本, rowspan, colspan)。"""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.rows: list[list[tuple[str, int, int]]] = []
self._row: list[tuple[str, int, int]] | None = None
self._in_cell = False
self._buf: list[str] = []
self._span = (1, 1)
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
if tag == "tr":
self._row = []
elif tag in ("td", "th"):
self._in_cell = True
self._buf = []
a = {k.lower(): (v or "") for k, v in attrs}
self._span = (_as_span(a.get("rowspan")), _as_span(a.get("colspan")))
elif tag == "br" and self._in_cell:
self._buf.append("\n")
def handle_data(self, data: str) -> None:
if self._in_cell:
self._buf.append(data)
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if tag in ("td", "th") and self._in_cell:
text = re.sub(r"[ \t]+", " ", "".join(self._buf)).strip()
rs, cs = self._span
if self._row is not None:
self._row.append((text, rs, cs))
self._in_cell = False
elif tag == "tr" and self._row is not None:
self.rows.append(self._row)
self._row = None
def _as_span(value: str | None) -> int:
try:
return max(1, int(str(value).strip()))
except (TypeError, ValueError):
return 1
def _convert_html_tables(markdown: str, page_number: int | None = None) -> str:
"""把 VLM 输出里的每个 <table>…</table> 就地替换成填满的标准 Markdown 表。"""
dims: list[str] = []
def repl(match: re.Match[str]) -> str:
table_md = _html_table_to_markdown(match.group(0))
if not table_md:
return ""
rows = [r for r in table_md.splitlines() if r.startswith("|")]
ncol = rows[0].count("|") - 1 if rows else 0
dims.append(f"{len(rows)}×{ncol}")
return f"\n{table_md}\n"
result = _HTML_TABLE_RE.sub(repl, markdown)
if dims:
logger.info("[RAG] p%s HTML 表格转换:%d 张 → Markdown(行×列:%s)",
page_number, len(dims), ", ".join(dims))
return result
def _html_table_to_markdown(html: str) -> str:
parser = _TableHTMLParser()
try:
parser.feed(html)
parser.close()
except Exception: # pragma: no cover - 容错:HTML 异常时退化为空,由上层判空
return ""
rows = [row for row in parser.rows if row]
if not rows:
return ""
matrix = _expand_table_grid(rows)
return _matrix_to_markdown(matrix)
def _expand_table_grid(rows: list[list[tuple[str, int, int]]]) -> list[list[str]]:
"""按 rowspan/colspan 把单元格铺进二维网格:每个合并格在其覆盖的每一行/列都填同值。"""
grid: dict[tuple[int, int], str] = {}
occupied: set[tuple[int, int]] = set()
max_col = 0
for r, row in enumerate(rows):
c = 0
for text, rowspan, colspan in row:
while (r, c) in occupied:
c += 1
for dr in range(rowspan):
for dc in range(colspan):
grid[(r + dr, c + dc)] = text
occupied.add((r + dr, c + dc))
c += colspan
max_col = max(max_col, c)
return [[grid.get((r, c), "") for c in range(max_col)] for r in range(len(rows))]
def _matrix_to_markdown(matrix: list[list[str]]) -> str:
if not matrix or not matrix[0]:
return ""
n_col = max(len(row) for row in matrix)
def render(row: list[str]) -> str:
# 单元格内换行折成空格:保证展开后的 Markdown 表零 HTML 标签(含 <br>),
# 便于后续对全文做统一 HTML 清洗而不误伤表格。
cells = [(row[i] if i < len(row) else "").replace("\n", " ").replace("|", "\\|").strip()
for i in range(n_col)]
return "| " + " | ".join(cells) + " |"
lines = [render(matrix[0]), "| " + " | ".join(["---"] * n_col) + " |"]
lines.extend(render(row) for row in matrix[1:])
return "\n".join(lines)
# ---------------------------------------------------------------------------
# 清洗正文里残留的非表格 HTML(保证分片内容不含任何 HTML 标签)
# ---------------------------------------------------------------------------
_HTML_TAG_RE = re.compile(r"</?[a-zA-Z][\w-]*")
# 纯装饰/无文本价值的标签:连同内部文本一起丢弃
_DROP_WITH_CONTENT = {"img", "style", "script", "svg", "figure", "figcaption"}
class _ResidualHTMLCleaner(HTMLParser):
"""把正文里残留的 HTML 转成纯 Markdown/文本:
h1-6→#,p/div/ul/ol/li→段落或列表边界,br→换行,行内标签只取文本,img 等装饰整体丢弃。
"""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
self.tags_seen: list[str] = []
self._drop_depth = 0 # 处于 img/style/script 等丢弃标签内部的深度
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
self.tags_seen.append(tag)
if tag in _DROP_WITH_CONTENT:
if tag != "img": # img 是空元素,没有 endtag,不计深度
self._drop_depth += 1
return
if self._drop_depth:
return
if tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
self.parts.append("\n" + "#" * int(tag[1]) + " ")
elif tag == "li":
self.parts.append("\n- ")
elif tag in ("p", "div", "ul", "ol", "tr", "table", "section", "header", "footer"):
self.parts.append("\n")
elif tag == "br":
self.parts.append("\n")
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if tag in _DROP_WITH_CONTENT and tag != "img":
self._drop_depth = max(0, self._drop_depth - 1)
return
if self._drop_depth:
return
if tag in ("h1", "h2", "h3", "h4", "h5", "h6", "p", "div", "li", "ul", "ol", "tr", "table"):
self.parts.append("\n")
def handle_data(self, data: str) -> None:
if not self._drop_depth:
self.parts.append(data)
def text(self) -> str:
out = "".join(self.parts)
out = re.sub(r"[ \t]+", " ", out)
out = "\n".join(line.strip() for line in out.split("\n"))
return re.sub(r"\n{3,}", "\n\n", out).strip()
def _sanitize_residual_html(markdown: str, page_number: int | None = None) -> str:
"""清洗正文里残留的非表格 HTML。无标签时走快速路径原样返回。"""
if not _HTML_TAG_RE.search(markdown):
return markdown
cleaner = _ResidualHTMLCleaner()
try:
cleaner.feed(markdown)
cleaner.close()
cleaned = cleaner.text()
tag_names = sorted(set(cleaner.tags_seen))
logger.info("[RAG] p%s 清理非表格残留 HTML:标签 %d 个 %s",
page_number, len(cleaner.tags_seen), tag_names)
return cleaned
except Exception: # pragma: no cover - 兜底:解析异常则正则硬剥标签,绝不把标签带进块
logger.warning("[RAG] p%s 残留 HTML 解析失败,退化为正则剥离标签", page_number)
return re.sub(r"<[^>]+>", "", markdown)
def _is_table_row(line: str) -> bool:
"""识别 Markdown 表格行。VLM 对跨页续表常省略行首竖线,故不能只看 startswith('|')。"""
if not line:
return False
if line.startswith("|"):
return True
# 无行首竖线的分隔行,如 ---|---|---
if "---" in line and set(line) <= set("|-: "):
return True
# 无行首竖线的数据行:含至少两个竖线分隔
return line.count("|") >= 2
def _normalize_table_line(line: str) -> str:
"""把表格行规范成标准 `| a | b | c |`,使下游切块的 startswith('|') 判定可靠。"""
cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
if all(set(cell) <= set("-: ") and "-" in cell for cell in cells if cell):
cells = ["---" for _ in cells]
return "| " + " | ".join(cells) + " |"
def _strip_continue_marker(markdown: str) -> tuple[str, bool]:
if TABLE_CONTINUES_MARKER in markdown:
return markdown.replace(TABLE_CONTINUES_MARKER, "").rstrip(), True
return markdown, False
def _safe_remove(path: str) -> None:
try:
os.remove(path)
except OSError:
pass