fix(knowdge-base): 手册/设计类 PDF 不抑制图片,并对保留图片跑 OCR,把 图中文写进md再同步

This commit is contained in:
sophie committed 2026-07-10 10:18:08 +08:00
1 parent 64205b72bd
commit 0939aeb0d8
5 files changed
+626 -17

No files matched your search

+375
View File
@@ -0,0 +1,375 @@
#!/usr/bin/env python3
"""
scripts/split_large_pdfs_for_kb.py
用途:将超大扫描 PDF(如机械设计手册整卷)按固定页数切成适合知识库上传/清洗的小文件。
依赖:pypdf(`pip install pypdf`)。
逻辑:运维/入库前离线执行;产出小 PDF + manifest.csv,再由知识库路径上传导入 HXOPS。
"""
from __future__ import annotations
import argparse
import csv
import re
import sys
import time
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class SplitPlan:
"""单卷 PDF 的切分计划。"""
source: Path
total_pages: int
chunk_count: int
pages_per_chunk: int
def _slugify_stem(name: str) -> str:
"""
将文件名主干整理为适合输出的安全片段(保留中文与常见字符)。
核心逻辑:去掉扩展名无关字符中的路径分隔与空白折叠,避免输出路径非法。
Args:
name: 原始文件名(可含扩展名)。
Returns:
清理后的 stem 字符串。
"""
stem = Path(name).stem.strip()
stem = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", stem)
stem = re.sub(r"\s+", "_", stem)
return stem or "document"
def _iter_pdfs(input_dir: Path, recursive: bool) -> list[Path]:
"""
收集待拆分的 PDF 路径列表。
Args:
input_dir: 输入目录。
recursive: 是否递归子目录。
Returns:
按文件名排序的 PDF 路径列表。
"""
pattern = "**/*.pdf" if recursive else "*.pdf"
files = [p for p in input_dir.glob(pattern) if p.is_file()]
return sorted(files, key=lambda p: p.name.lower())
def plan_split(source: Path, pages_per_chunk: int) -> SplitPlan:
"""
读取 PDF 页数并计算切分份数(不写文件)。
核心逻辑:用 pypdf.PdfReader 取页数,按 pages_per_chunk 向上取整。
Args:
source: 源 PDF 路径。
pages_per_chunk: 每份页数,须 >= 1。
Returns:
SplitPlan。
Raises:
ValueError: 页数无效或无法打开 PDF。
"""
from pypdf import PdfReader
reader = PdfReader(str(source), strict=False)
total = len(reader.pages)
if total <= 0:
raise ValueError(f"PDF 页数为 0: {source}")
chunk_count = (total + pages_per_chunk - 1) // pages_per_chunk
return SplitPlan(
source=source,
total_pages=total,
chunk_count=chunk_count,
pages_per_chunk=pages_per_chunk,
)
def split_one_pdf(
source: Path,
output_dir: Path,
pages_per_chunk: int,
*,
dry_run: bool = False,
overwrite: bool = False,
) -> list[dict[str, object]]:
"""
将单个 PDF 按固定页数切分为多个小 PDF,并返回 manifest 行。
核心逻辑:一次打开源文件,按页区间用 PdfWriter 写出;文件名含起止页码便于溯源。
Args:
source: 源 PDF。
output_dir: 输出目录(不存在则创建)。
pages_per_chunk: 每份页数。
dry_run: 为 True 时只规划不写文件。
overwrite: 为 False 时若目标已存在则跳过该份。
Returns:
manifest 行字典列表(source/output/pages/size 等)。
"""
from pypdf import PdfReader, PdfWriter
plan = plan_split(source, pages_per_chunk)
stem = _slugify_stem(source.name)
output_dir.mkdir(parents=True, exist_ok=True)
rows: list[dict[str, object]] = []
if dry_run:
for idx in range(plan.chunk_count):
start = idx * pages_per_chunk
end = min(start + pages_per_chunk, plan.total_pages)
out_name = f"{stem}_p{start + 1:04d}-{end:04d}.pdf"
rows.append(
{
"source": str(source),
"output": str(output_dir / out_name),
"part_index": idx + 1,
"part_count": plan.chunk_count,
"page_start": start + 1,
"page_end": end,
"page_count": end - start,
"size_bytes": "",
"status": "planned",
}
)
return rows
# [STEP 1] 打开源 PDF(扫描件可能很大,保持单次打开复用)
print(f"[open] {source.name} pages={plan.total_pages} parts={plan.chunk_count}")
reader = PdfReader(str(source), strict=False)
t0 = time.time()
for idx in range(plan.chunk_count):
start = idx * pages_per_chunk
end = min(start + pages_per_chunk, plan.total_pages)
out_name = f"{stem}_p{start + 1:04d}-{end:04d}.pdf"
out_path = output_dir / out_name
if out_path.exists() and not overwrite:
size = out_path.stat().st_size
print(f" [skip] {out_name} (exists, {size / (1024 * 1024):.1f} MB)")
rows.append(
{
"source": str(source),
"output": str(out_path),
"part_index": idx + 1,
"part_count": plan.chunk_count,
"page_start": start + 1,
"page_end": end,
"page_count": end - start,
"size_bytes": size,
"status": "skipped_exists",
}
)
continue
# [STEP 2] 按页区间写出小 PDF
writer = PdfWriter()
for page_i in range(start, end):
writer.add_page(reader.pages[page_i])
with out_path.open("wb") as fh:
writer.write(fh)
size = out_path.stat().st_size
size_mb = size / (1024 * 1024)
warn = " !! >50MB" if size_mb > 50 else ""
print(
f" [{idx + 1}/{plan.chunk_count}] {out_name} "
f"pages={start + 1}-{end} {size_mb:.1f} MB{warn}"
)
rows.append(
{
"source": str(source),
"output": str(out_path),
"part_index": idx + 1,
"part_count": plan.chunk_count,
"page_start": start + 1,
"page_end": end,
"page_count": end - start,
"size_bytes": size,
"status": "written",
}
)
print(f"[done] {source.name} elapsed={time.time() - t0:.1f}s")
return rows
def write_manifest(rows: list[dict[str, object]], manifest_path: Path) -> None:
"""
将切分结果写入 CSV,便于核对与后续批量上传。
Args:
rows: manifest 行。
manifest_path: 输出 CSV 路径。
"""
if not rows:
return
fieldnames = [
"source",
"output",
"part_index",
"part_count",
"page_start",
"page_end",
"page_count",
"size_bytes",
"status",
]
manifest_path.parent.mkdir(parents=True, exist_ok=True)
with manifest_path.open("w", encoding="utf-8-sig", newline="") as fh:
writer = csv.DictWriter(fh, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
def build_arg_parser() -> argparse.ArgumentParser:
"""
构建命令行参数解析器。
Returns:
ArgumentParser 实例。
"""
parser = argparse.ArgumentParser(
description="按固定页数拆分超大 PDF,便于知识库上传与 OCR 清洗。"
)
parser.add_argument(
"--input",
required=True,
help="源 PDF 文件或包含 PDF 的目录",
)
parser.add_argument(
"--output",
required=True,
help="拆分结果输出目录",
)
parser.add_argument(
"--pages",
type=int,
default=40,
help="每份页数(扫描件建议 20–40;默认 40)",
)
parser.add_argument(
"--recursive",
action="store_true",
help="输入为目录时递归查找 PDF",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="只打印/写出计划,不真正切分",
)
parser.add_argument(
"--overwrite",
action="store_true",
help="覆盖已存在的输出文件",
)
parser.add_argument(
"--manifest",
default="",
help="manifest CSV 路径(默认写到输出目录/manifest.csv)",
)
return parser
def main(argv: list[str] | None = None) -> int:
"""
CLI 入口:解析参数、切分 PDF、写出 manifest。
Args:
argv: 可选命令行参数列表;默认使用 sys.argv。
Returns:
进程退出码:0 成功,非 0 失败。
"""
args = build_arg_parser().parse_args(argv)
if args.pages < 1:
print("ERROR: --pages 必须 >= 1", file=sys.stderr)
return 2
input_path = Path(args.input)
output_dir = Path(args.output)
if not input_path.exists():
print(f"ERROR: 输入不存在: {input_path}", file=sys.stderr)
return 2
if input_path.is_file():
sources = [input_path]
else:
sources = _iter_pdfs(input_path, recursive=args.recursive)
if not sources:
print(f"ERROR: 目录下未找到 PDF: {input_path}", file=sys.stderr)
return 2
print(
f"sources={len(sources)} pages_per_chunk={args.pages} "
f"dry_run={args.dry_run} output={output_dir}"
)
all_rows: list[dict[str, object]] = []
failed = 0
for source in sources:
try:
# 每卷单独子目录,避免 6 卷文件混在一起难管理
vol_out = output_dir / _slugify_stem(source.name)
rows = split_one_pdf(
source,
vol_out,
args.pages,
dry_run=args.dry_run,
overwrite=args.overwrite,
)
all_rows.extend(rows)
if args.dry_run and rows:
plan_pages = int(rows[0]["page_end"]) # type: ignore[arg-type]
# dry-run 时用 plan_split 再打一行摘要
plan = plan_split(source, args.pages)
size_mb = source.stat().st_size / (1024 * 1024)
print(
f"[plan] {source.name} {size_mb:.1f} MB "
f"pages={plan.total_pages} -> {plan.chunk_count} parts "
f"(~{args.pages} pages each) first_end_check={plan_pages}"
)
except Exception as exc: # noqa: BLE001 - CLI 汇总错误后继续下一卷
failed += 1
print(f"[FAIL] {source}: {exc}", file=sys.stderr)
manifest_path = (
Path(args.manifest) if args.manifest else output_dir / "manifest.csv"
)
write_manifest(all_rows, manifest_path)
written = sum(1 for r in all_rows if r["status"] in {"written", "planned"})
skipped = sum(1 for r in all_rows if r["status"] == "skipped_exists")
print(
f"\nsummary: parts={len(all_rows)} written_or_planned={written} "
f"skipped={skipped} failed_sources={failed}"
)
print(f"manifest: {manifest_path}")
if not args.dry_run and all_rows:
oversized = [
r
for r in all_rows
if isinstance(r.get("size_bytes"), int) and int(r["size_bytes"]) > 50 * 1024 * 1024
]
if oversized:
print(
f"WARNING: {len(oversized)} 个分片 > 50MB,建议减小 --pages 后重跑 "
f"(知识库 Nginx 上限约 100MB,OCR 也更易超时)"
)
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())