document_parser.py
17 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
import os
import re
import shutil
import subprocess
import tempfile
import time
import logging
import threading
from pathlib import Path
logger = logging.getLogger(__name__)
_last_extract_stats: dict[str, dict] = {}
_last_extract_stats_lock = threading.Lock()
def is_presentation_file(file_path: str) -> bool:
return os.path.splitext(file_path)[1].lower() in {".ppt", ".pptx"}
def extract_text_from_file(
file_path: str,
preview_file_id: str | None = None,
preview_dir: str | None = None,
) -> str:
"""
根据文件后缀提取文档中的纯文本内容。
支持的格式: .txt, .md, .json, .pdf, .docx, .pptx, .ppt, .xlsx, .xls
如果遇到不支持的格式,将尝试作为纯文本读取。
"""
if not os.path.exists(file_path):
raise FileNotFoundError(f"未找到文件,请检查路径是否正确: {file_path}")
_record_extract_stats(file_path, {})
# 获取文件后缀名并统一转换为小写,以进行格式路由
ext = os.path.splitext(file_path)[1].lower()
try:
# 基于常见文本格式进行路由
if ext in ['.txt', '.md', '.json', '.xml', '.csv']:
return _extract_text_plain(file_path)
# 路由到 PDF 解析器
elif ext == '.pdf':
return _extract_text_pdf(file_path)
# 路由到 Word 文档解析器
elif ext == '.docx':
return _extract_text_docx(file_path)
# 路由到 PPT 演示文稿解析器:先转 PDF,再复用 PDF VLM 路径
elif is_presentation_file(file_path):
return _extract_text_presentation(file_path, preview_file_id=preview_file_id, preview_dir=preview_dir)
# 路由到 Excel 表格解析器
elif ext in ['.xlsx', '.xls']:
return _extract_text_excel(file_path)
else:
# 对于未明确支持的文件后缀(例如 .log, .conf 等),
# 默认作为纯文本文件尝试读取,充当降级(Fallback)方案
return _extract_text_plain(file_path)
except Exception as e:
# 将底层解析错误包装为 RuntimeError 向上抛出,方便上层捕获和记录
raise RuntimeError(f"从文件 {file_path} 提取文本时发生错误: {str(e)}")
def _extract_text_plain(file_path: str) -> str:
"""
读取纯文本文件的内容,内置自动探测编码机制。
参数:
file_path (str): 文本文件路径
返回:
str: 文本文件内容
"""
# 尝试使用多种常见编码顺序读取,以兼容不同来源的文本文件(特别是 Windows 默认的 gbk)
for enc in ['utf-8', 'gbk', 'latin-1']:
try:
with open(file_path, 'r', encoding=enc) as f:
return f.read()
except UnicodeDecodeError:
# 如果当前编码解码失败,静默捕获并尝试列表中的下一种编码
continue
# 如果所有常见编码都失败,最后作为兜底方案(Fallback)
# 强制使用 utf-8 读取,并且遇到无法解码的字符时使用 'replace'(替换为 ),防止程序直接崩溃
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
return f.read()
def _extract_text_pdf(file_path: str) -> str:
"""
解析 PDF 文档并提取每一页的文本。
解析完成后将中间 Markdown 保存到 ware/intermediates/pdfVL2md/ 以便排查。
参数:
file_path (str): PDF 文件路径
返回:
str: 合并后的 PDF 文本内容
"""
blocks = _load_pdf_blocks(file_path)
_record_extract_stats(file_path, _extract_vlm_stats_from_blocks(blocks))
md_text = _blocks_to_markdown(blocks)
_save_vlm_intermediate(file_path, md_text)
return md_text
def _save_vlm_intermediate(source_pdf_path: str, md_text: str) -> None:
"""将 VLM 解析结果保存到 ware/intermediates/pdfVL2md/,写入失败不阻塞主流程。
文件命名规则:与原始文件同名,后缀改为 .md。
例:产品手册.pdf → 产品手册.md
每次重新解析时覆盖旧文件,只保留最新一份。
"""
try:
from config import VLM_MD_INTERMEDIATES_DIR
stem = Path(source_pdf_path).stem
out_path = Path(VLM_MD_INTERMEDIATES_DIR) / f"{stem}.md"
out_path.write_text(md_text, encoding="utf-8")
logger.info(
"[VLMIntermediate] saved path=%s chars=%d",
out_path,
len(md_text),
)
except Exception as e:
logger.warning(
"[VLMIntermediate] save_failed source=%s error=%s",
source_pdf_path,
e,
)
def _load_pdf_blocks(file_path: str):
"""复用 RAG 的 PDF VLM 解析器,保持 qwen-vl-max 等配置统一。"""
from src.rag.ingestion.loaders.pdf import load_pdf
return load_pdf(file_path)
def get_last_extract_stats(file_path: str) -> dict:
"""Return parser stats from the latest extraction of this source path."""
key = os.path.abspath(file_path)
with _last_extract_stats_lock:
return dict(_last_extract_stats.get(key) or {})
def _record_extract_stats(file_path: str, stats: dict | None) -> None:
key = os.path.abspath(file_path)
with _last_extract_stats_lock:
_last_extract_stats[key] = dict(stats or {})
def _extract_vlm_stats_from_blocks(blocks) -> dict:
for block in blocks:
metadata = getattr(block, "metadata", None) or {}
if metadata.get("parse_engine") == "vlm":
return {
"parse_engine": metadata.get("parse_engine"),
"vlm_page_count": int(metadata.get("vlm_page_count") or 0),
"vlm_input_tokens": int(metadata.get("vlm_input_tokens") or 0),
"vlm_output_tokens": int(metadata.get("vlm_output_tokens") or 0),
"vlm_image_tokens": int(metadata.get("vlm_image_tokens") or 0),
"vlm_total_tokens": int(metadata.get("vlm_total_tokens") or 0),
"vlm_duration_ms": int(metadata.get("vlm_duration_ms") or 0),
}
return {}
def _blocks_to_markdown(blocks) -> str:
"""将 RAG DocumentBlock 列表拼接成摄入 Agent 可读的 Markdown。"""
sorted_blocks = sorted(
blocks,
key=lambda block: (
getattr(block, "page_number", None) or 0,
getattr(block, "source_offset", None) or 0,
),
)
if not sorted_blocks:
raise RuntimeError("PDF 未提取到可用内容")
text_content = []
current_page = object()
for block in sorted_blocks:
page_number = getattr(block, "page_number", None)
if page_number is not None and page_number != current_page:
if text_content:
text_content.append("")
text_content.append(f"## Page {page_number}")
current_page = page_number
title_path = getattr(block, "title_path", "") or ""
block_text = (getattr(block, "text", "") or "").strip()
if not block_text:
continue
if title_path:
text_content.append(f"<!-- section: {title_path} -->")
text_content.append(block_text)
result = "\n\n".join(part for part in text_content if part is not None).strip()
if not result:
raise RuntimeError("PDF 未提取到可用内容")
return result
def _extract_text_docx(file_path: str) -> str:
"""
解析 Word (.docx) 文档,提取所有段落以及表格内的文本。
参数:
file_path (str): Word 文件路径
返回:
str: 拼接好的 Word 文本和表格内容
"""
import docx
doc = docx.Document(file_path)
text_content = []
# 1. 遍历文档中的所有常规段落;标题样式还原为 Markdown 前缀,
# 让长 docx 能复用摄入分块器的标题切分(无标题样式则自动落到段落切分兜底)
heading_re = re.compile(r"^Heading (\d)$")
for para in doc.paragraphs:
if not para.text.strip():
continue
m = heading_re.match(para.style.name or "")
if m:
text_content.append(f"{'#' * int(m.group(1))} {para.text}")
else:
text_content.append(para.text)
# 2. 遍历文档中所有的表格,将表格数据扁平化提取
for table in doc.tables:
for row in table.rows:
# 将同一行内的各个单元格文本通过 ' | ' 拼接,模拟 Markdown 表格格式
row_data = [cell.text.strip() for cell in row.cells if cell.text.strip()]
if row_data:
text_content.append(" | ".join(row_data))
# 使用单换行符连接所有段落和表格行
return "\n".join(text_content)
def _extract_text_presentation(
file_path: str,
preview_file_id: str | None = None,
preview_dir: str | None = None,
) -> str:
"""
解析 PPT/PPTX 演示文稿:使用 LibreOffice headless 转 PDF,再复用 PDF VLM。
参数:
file_path (str): PPT 文件路径
返回:
str: 经 PDF VLM 解析后的 Markdown 文本
"""
if preview_file_id:
pdf_path = get_or_create_office_preview_pdf(file_path, preview_file_id, preview_dir)
return _extract_text_pdf(pdf_path)
with tempfile.TemporaryDirectory(prefix="wiki_presentation_pdf_") as tmp_dir:
pdf_path = _convert_presentation_to_pdf(file_path, tmp_dir)
return _extract_text_pdf(pdf_path)
def _office_preview_root(preview_dir: str | None = None) -> Path:
if preview_dir is None:
return Path(__file__).resolve().parents[2] / "ware" / "preview" / "pdf"
return Path(preview_dir)
def get_office_preview_pdf_path(file_path: str, file_id: str, preview_dir: str | None = None) -> Path:
source_path = Path(file_path)
return _office_preview_root(preview_dir) / f"{source_path.stem}_{file_id}.pdf"
def delete_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | None = None) -> str | None:
cache_path = get_office_preview_pdf_path(file_path, file_id, preview_dir)
if not cache_path.exists():
return None
cache_path.unlink()
logger.info(
"[Preview] Deleted PPT/PPTX PDF cache: file_id=%s, cache_path=%s",
file_id,
cache_path,
)
return str(cache_path)
def get_existing_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | None = None) -> str | None:
"""Return a fresh cached PPT/PPTX preview PDF path without creating it."""
source_path = Path(file_path)
if not source_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
cache_path = get_office_preview_pdf_path(file_path, file_id, preview_dir)
if not cache_path.exists():
return None
if cache_path.stat().st_mtime < source_path.stat().st_mtime:
return None
return str(cache_path)
def get_or_create_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | None = None) -> str:
"""Create or reuse a cached PDF preview for PPT/PPTX files without running VLM parsing."""
source_path = Path(file_path)
if not source_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
preview_root = _office_preview_root(preview_dir)
preview_root.mkdir(parents=True, exist_ok=True)
cache_path = get_office_preview_pdf_path(file_path, file_id, preview_dir)
source_mtime = source_path.stat().st_mtime
cache_mtime = cache_path.stat().st_mtime if cache_path.exists() else None
if cache_mtime is not None and cache_mtime >= source_mtime:
logger.info(
"[Preview] PPT/PPTX PDF cache hit: file_id=%s, cache_path=%s",
file_id,
cache_path,
)
return str(cache_path)
if cache_mtime is None:
logger.info(
"[Preview] PPT/PPTX PDF cache missing: file_id=%s, source_mtime=%s, cache_path=%s",
file_id,
source_mtime,
cache_path,
)
else:
logger.info(
"[Preview] PPT/PPTX PDF cache stale: file_id=%s, source_mtime=%s, cache_mtime=%s, cache_path=%s",
file_id,
source_mtime,
cache_mtime,
cache_path,
)
soffice = _resolve_soffice_path()
if not soffice:
logger.error(
"[Preview] LibreOffice not found for PPT/PPTX preview: file_id=%s, source_path=%s",
file_id,
source_path,
)
raise RuntimeError("PPT/PPTX preview requires LibreOffice and soffice in PATH")
start = time.perf_counter()
logger.info(
"[Preview] Starting LibreOffice PPT/PPTX preview conversion: file_id=%s, soffice=%s, output_cache=%s",
file_id,
soffice,
cache_path,
)
try:
with tempfile.TemporaryDirectory(prefix="wiki_office_preview_pdf_") as tmp_dir:
converted_pdf = Path(_convert_presentation_to_pdf_with_soffice(str(source_path), tmp_dir, soffice))
shutil.move(str(converted_pdf), str(cache_path))
except Exception as exc:
logger.error(
"[Preview] LibreOffice PPT/PPTX preview conversion failed: file_id=%s, source_path=%s, cache_path=%s, error=%s",
file_id,
source_path,
cache_path,
exc,
exc_info=True,
)
raise
duration_ms = int((time.perf_counter() - start) * 1000)
logger.info(
"[Preview] LibreOffice PPT/PPTX preview conversion succeeded: file_id=%s, cache_path=%s, duration_ms=%s",
file_id,
cache_path,
duration_ms,
)
return str(cache_path)
def _convert_presentation_to_pdf(file_path: str, output_dir: str) -> str:
soffice = _resolve_soffice_path()
if not soffice:
raise RuntimeError("PPT/PPTX 多模态解析需要安装 LibreOffice,并确保 soffice 在 PATH 中")
return _convert_presentation_to_pdf_with_soffice(file_path, output_dir, soffice)
def _convert_presentation_to_pdf_with_soffice(file_path: str, output_dir: str, soffice: str) -> str:
timeout = int(os.environ.get("LIBREOFFICE_CONVERT_TIMEOUT", "120"))
try:
with tempfile.TemporaryDirectory(prefix="wiki_libreoffice_profile_") as profile_dir:
cmd = [
soffice,
"--headless",
"--nologo",
"--nofirststartwizard",
"--nolockcheck",
"--nodefault",
"--norestore",
f"-env:UserInstallation={Path(profile_dir).as_uri()}",
"--convert-to",
"pdf",
"--outdir",
output_dir,
file_path,
]
subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=True)
except subprocess.TimeoutExpired as exc:
raise RuntimeError(f"LibreOffice 转换 PPT/PPTX 超时: {exc}") from exc
except subprocess.CalledProcessError as exc:
detail = "\n".join(part for part in [exc.stdout, exc.stderr] if part).strip()
raise RuntimeError(f"LibreOffice 转换 PPT/PPTX 失败: {detail or exc}") from exc
expected_pdf = Path(output_dir) / f"{Path(file_path).stem}.pdf"
if expected_pdf.exists():
return str(expected_pdf)
pdf_candidates = sorted(Path(output_dir).glob("*.pdf"))
if pdf_candidates:
return str(pdf_candidates[0])
raise RuntimeError("LibreOffice 转换 PPT/PPTX 失败: 未生成 PDF 文件")
def _resolve_soffice_path() -> str | None:
configured_path = os.environ.get("LIBREOFFICE_PATH")
if configured_path and Path(configured_path).exists():
return configured_path
soffice = shutil.which("soffice")
if soffice:
return soffice
for candidate in (
Path(r"C:\Program Files\LibreOffice\program\soffice.exe"),
Path(r"C:\Program Files (x86)\LibreOffice\program\soffice.exe"),
):
if candidate.exists():
return str(candidate)
return None
def _extract_text_excel(file_path: str) -> str:
"""
解析 Excel 表格 (.xlsx, .xls) 数据。
利用 Pandas 框架一次性读取所有 Sheet,并转化为纯文本表现形式。
参数:
file_path (str): Excel 文件路径
返回:
str: 包含所有 Sheet 数据的纯文本格式
"""
import pandas as pd
text_content = []
# sheet_name=None 表示读取工作簿中的所有工作表 (Sheets),返回结果为一个字典
# 键为 Sheet 名称,值为对应的 DataFrame 对象
df_dict = pd.read_excel(file_path, sheet_name=None)
for sheet_name, df in df_dict.items():
# 添加 Sheet 标题作为明显的分隔符(摄入分块器以此为 Sheet 切点)
text_content.append(f"--- Sheet: {sheet_name} ---")
# 优先输出 Markdown 表格:比定宽文本省 token、列语义清晰,
# 且超大 Sheet 可被分块器按行组切分并重复表头
try:
text_content.append(df.to_markdown(index=False))
except ImportError:
# to_markdown 依赖 tabulate,缺失时退回定宽文本
text_content.append(df.to_string(index=False))
return "\n\n".join(text_content)