diff --git a/backend/edkb_system/controller.py b/backend/edkb_system/controller.py index b8e831b2..c12487e3 100644 --- a/backend/edkb_system/controller.py +++ b/backend/edkb_system/controller.py @@ -1,3 +1,11 @@ +""" +edkb_system/controller.py + +用途:edkb 单文件清洗编排(intake → loader → OCR → clean → export)。 +依赖:edkb_system.skills.*、SystemConfig、common.is_figure_rich_handbook。 +逻辑:由 knowledge_cleaning.edkb_adapter / CLI 调用;手册类跳过丢图并强制 OCR。 +""" + from __future__ import annotations import json @@ -30,7 +38,7 @@ from edkb_system.skills import ( quality_gate, table_linearize, ) -from edkb_system.skills.common import blocks_to_plain_markdown +from edkb_system.skills.common import blocks_to_plain_markdown, is_figure_rich_handbook from edkb_system.skills.word_bridge import _kill_winword_pids, _list_winword_pids @@ -281,6 +289,21 @@ def _cleanup_input_temp_files(input_path: Path) -> list[Path]: def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None) -> bool: + """ + 判断当前文档是否需要跑 OCR。 + + 核心逻辑:PPT 跳过;Word 仅在 pipeline 显式请求时跑;PDF 在扫描/整页图模式 + 或图文手册(有 image block)时强制跑,以便写入「图中文字」供问答。 + + Args: + profile: intake 文档画像。 + cfg: SystemConfig。 + blocks: loader 产出的块。 + context: 可选上下文(含 scan_likely / figure_rich_handbook 等 extras)。 + + Returns: + True 表示应执行 edkb-ocr。 + """ if not blocks or not cfg.ocr.enable: return False if profile.file_type in {"ppt", "pptx"}: @@ -288,6 +311,11 @@ def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None) pipeline_requests_ocr = "edkb-ocr" in profile.recommended_pipeline has_image_blocks = any(b.type == "image" for b in blocks) + extras = getattr(context, "extras", {}) or {} if context is not None else {} + + # [STEP] 机械设计手册等:只要有图就 OCR,避免只剩正文导致问答丢图信息 + if has_image_blocks and extras.get("figure_rich_handbook"): + return True # Word documents often contain decorative or embedded images. If intake # did not explicitly request OCR, do not force a slow OCR pass just because @@ -296,7 +324,6 @@ def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None) return False if profile.file_type == "pdf" and not pipeline_requests_ocr: - extras = getattr(context, "extras", {}) or {} return bool(extras.get("scan_likely") or extras.get("pdf_page_image_mode_pages")) return pipeline_requests_ocr or has_image_blocks @@ -592,6 +619,13 @@ def _run_one( if blocks: ctx.images = sum(1 for b in blocks if b.type == "image") + figure_rich_handbook = bool( + ctx.extras.get("figure_rich_handbook") + or is_figure_rich_handbook(file_path.name) + ) + if figure_rich_handbook: + ctx.extras["figure_rich_handbook"] = True + should_ocr = _should_run_ocr(profile, cfg, blocks, ctx) if should_ocr: _announce("ocr") @@ -614,8 +648,13 @@ def _run_one( for b in blocks if b.type in {"heading", "paragraph"} ) + # [STEP] policy_text/flow 默认丢图;手册类必须保留 image+ocr_text 供问答 suppress_images = False - if profile.file_type not in {"ppt", "pptx"} and not has_figure_anchor: + if ( + profile.file_type not in {"ppt", "pptx"} + and not has_figure_anchor + and not figure_rich_handbook + ): if policy_text and not has_non_flow_info and not has_page_image_mode: suppress_images = True elif ( @@ -627,6 +666,8 @@ def _run_one( if suppress_images: blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}] trace_steps.append("edkb-image-suppress(no_figure_anchor)") + elif figure_rich_handbook: + trace_steps.append("edkb-image-keep(figure_rich_handbook)") flow_info = {} if "edkb-flow-reconstruct" in profile.recommended_pipeline: @@ -642,7 +683,9 @@ def _run_one( encoding="utf-8", ) - text = blocks_to_plain_markdown(blocks) + text = blocks_to_plain_markdown( + blocks, keep_figure_ocr=figure_rich_handbook + ) text = _inject_doc_header_from_flow(text, flow_mds) elif tables is not None: _announce("table linearize") diff --git a/backend/edkb_system/skills/clean.py b/backend/edkb_system/skills/clean.py index 35f79d2a..89a74c05 100644 --- a/backend/edkb_system/skills/clean.py +++ b/backend/edkb_system/skills/clean.py @@ -1,3 +1,11 @@ +""" +edkb_system/skills/clean.py + +用途:对 loader/OCR 产出的 markdown 做去重、排版与图注附着等清洗。 +依赖:edkb_system.contracts.Context。 +逻辑:由 controller 在 blocks→markdown 之后调用;需保留手册页图「图中文字」。 +""" + from __future__ import annotations import base64 @@ -907,13 +915,28 @@ def _compact_remarks_to_single_line(text: str) -> str: def _attach_ocr_lines_to_images(text: str) -> str: + """ + 将散落的「图中文字」行重新挂到对应图片 markdown 行之后。 + + 核心逻辑:抽出全部 OCR 行后,按出现顺序挂到 image/page-image 标记后; + 支持带 URL 的 `![](data:…)` 以及手册整页图占位 `![page-image-N]`(无 URL)。 + + Args: + text: 清洗中的 markdown。 + + Returns: + OCR 行已附着到图片后的 markdown;无图时原样返回。 + """ lines = text.splitlines() ocr_lines = [ln.strip() for ln in lines if ln.strip().startswith("图中文字:")] if not ocr_lines: return text kept = [ln for ln in lines if not ln.strip().startswith("图中文字:")] - img_pat = re.compile(r"^!\[(?:image|page-image)-\d+\]\((?:data:image/|https?://)") + # 含 data/http URL 的图,以及无 URL 的 page-image 占位(手册整页 OCR) + img_pat = re.compile( + r"^!\[(?:image|page-image)-\d+\](?:\((?:data:image/|https?://)[^)]*\))?$" + ) img_count = sum(1 for ln in kept if img_pat.match(ln.strip())) if img_count <= 0: return text @@ -927,6 +950,10 @@ def _attach_ocr_lines_to_images(text: str) -> str: if img_pat.match(ln.strip()): out.append(ocr_lines[o_idx]) o_idx += 1 + # 多余 OCR 行仍保留,避免手册图注被静默丢弃 + while o_idx < len(ocr_lines): + out.append(ocr_lines[o_idx]) + o_idx += 1 return "\n".join(out) diff --git a/backend/edkb_system/skills/common.py b/backend/edkb_system/skills/common.py index 9aed779a..b63b1f80 100644 --- a/backend/edkb_system/skills/common.py +++ b/backend/edkb_system/skills/common.py @@ -1,3 +1,11 @@ +""" +edkb_system/skills/common.py + +用途:edkb 清洗链路的通用工具(哈希、OCR 载荷整理、blocks→markdown)。 +依赖:edkb_system.contracts.Block。 +逻辑:controller / export / loader 等技能复用;手册类图文保留策略也集中在此判定。 +""" + from __future__ import annotations import hashlib @@ -9,6 +17,45 @@ from typing import Any from edkb_system.contracts import Block +# 机械设计手册等图文密集文档:清洗时需保留图片并写入 OCR「图中文字」供问答检索。 +_FIGURE_RICH_HANDBOOK_KEYWORDS = ( + "手册", + "圖冊", + "图册", + "图集", + "圖集", + "机械设计", + "機械設計", + "handbook", + "design manual", +) + + +def is_figure_rich_handbook(name: str) -> bool: + """ + 判断文件名是否像「图文密集手册/设计手册」。 + + 核心逻辑:文件名命中手册/图册/机械设计等关键词时返回 True,供 loader/controller + 放宽嵌图保留、跳过 policy_text 丢图、并强制 OCR。 + + Args: + name: 文件名或 stem(可含扩展名)。 + + Returns: + True 表示应按图文手册策略处理。 + """ + text = str(name or "").strip() + if not text: + return False + lowered = text.lower() + for keyword in _FIGURE_RICH_HANDBOOK_KEYWORDS: + if keyword.isascii(): + if keyword in lowered: + return True + elif keyword in text: + return True + return False + def hash_text(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() @@ -162,7 +209,23 @@ def _page_image_structured_lines(payload: str) -> list[str]: return lines -def blocks_to_plain_markdown(blocks: list[Block]) -> str: +def blocks_to_plain_markdown( + blocks: list[Block], *, keep_figure_ocr: bool = False +) -> str: + """ + 将 block 列表转为纯文本 markdown(含可选图片与「图中文字」OCR)。 + + 核心逻辑:按页排序输出 heading/paragraph/image;PDF 整页图在正文较多时默认抑制, + 但 keep_figure_ocr=True(手册类)时始终保留 OCR 文案供问答检索。 + + Args: + blocks: 清洗后的内容块。 + keep_figure_ocr: 为 True 时不因页内正文较多而丢弃 PDF 页图 OCR。 + + Returns: + markdown 字符串(末尾带换行)。 + """ + def _is_meaningful_ocr_segment(text: str) -> bool: token = re.sub(r"\s+", "", text or "") if not token or re.fullmatch(r"[\W_]+", token): @@ -237,10 +300,15 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str: ) if is_pdf_page_image: ocr_text = ocr_by_image.get(b.id) + # [STEP] 手册类保留页图 OCR;普通 PDF 仍避免与正文重复的整页图噪声 suppress_pdf_page_image = ( - page_body_chars.get(b.page, 0) >= 80 - or page_text_chars.get(b.page, 0) >= 120 - ) and not _is_rich_ocr_payload(ocr_text or "") + not keep_figure_ocr + and ( + page_body_chars.get(b.page, 0) >= 80 + or page_text_chars.get(b.page, 0) >= 120 + ) + and not _is_rich_ocr_payload(ocr_text or "") + ) if not suppress_pdf_page_image: lines.append(f"![page-image-{b.page}]") if ocr_text and not suppress_pdf_page_image: @@ -253,11 +321,13 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str: lines.append(f"![image-{image_idx}]({data_uri})") ocr_text = ocr_by_image.get(b.id) if ocr_text: - suppress_pptx_ocr = bool( - b.meta and b.meta.get("page_image_source") == "pptx" - ) and ( - page_body_chars.get(b.page, 0) >= 15 - or page_text_chars.get(b.page, 0) >= 40 + suppress_pptx_ocr = ( + not keep_figure_ocr + and bool(b.meta and b.meta.get("page_image_source") == "pptx") + and ( + page_body_chars.get(b.page, 0) >= 15 + or page_text_chars.get(b.page, 0) >= 40 + ) ) if b.meta and b.meta.get("page_image"): lines.extend(_page_image_structured_lines(ocr_text)) @@ -265,6 +335,9 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str: lines.append(f"图中文字:{ocr_text}") else: lines.append("![image]") + ocr_text = ocr_by_image.get(b.id) + if ocr_text and keep_figure_ocr: + lines.append(f"图中文字:{ocr_text}") else: lines.append(txt) return "\n\n".join(lines).strip() + "\n" diff --git a/backend/edkb_system/skills/loader_pdf.py b/backend/edkb_system/skills/loader_pdf.py index 1b8bb97d..06a7df9f 100644 --- a/backend/edkb_system/skills/loader_pdf.py +++ b/backend/edkb_system/skills/loader_pdf.py @@ -1,3 +1,11 @@ +""" +edkb_system/skills/loader_pdf.py + +用途:解析 PDF 为 Block 列表(正文、嵌入图、扫描页整页图)。 +依赖:pypdf / pypdfium2、edkb_system.contracts、common.is_figure_rich_handbook。 +逻辑:由 controller 在 PDF 分支调用;手册类文件名会放宽嵌图保留阈值。 +""" + from __future__ import annotations import base64 @@ -7,6 +15,7 @@ import re import xml.etree.ElementTree as ET from edkb_system.contracts import Block, Context +from edkb_system.skills.common import is_figure_rich_handbook _PAGE_IMAGE_RENDER_SCALE = 0.75 _PAGE_IMAGE_JPEG_QUALITY = 82 @@ -15,6 +24,9 @@ _DEFAULT_PAGE_TEXT_LIMIT = 120 _MIN_SCAN_IMAGE_BYTES = 4 * 1024 _MIN_DEFAULT_IMAGE_BYTES = 16 * 1024 _MIN_TEXT_HEAVY_IMAGE_BYTES = 24 * 1024 +# 图文手册:正文页也保留较大嵌入图,供后续 OCR「图中文字」。 +_MIN_FIGURE_HANDBOOK_IMAGE_BYTES = 12 * 1024 +_FIGURE_HANDBOOK_PAGE_TEXT_LIMIT = 400 _XFA_ROW_CONTAINER_TAGS = {"DATA"} _XFA_SKIP_TAGS = { "config", @@ -44,11 +56,33 @@ def _should_keep_embedded_image( page_text_chars: int, scan_likely: bool, text_heavy_pdf: bool, + figure_rich_handbook: bool = False, ) -> bool: + """ + 判断 PDF 页内嵌入图是否保留为 image block。 + + 核心逻辑:扫描件放宽体积阈值;正文密集 PDF 默认只保留「少字页上的大图」; + 手册类则允许正文页保留 ≥12KB 的图,避免机械设计图被滤掉。 + + Args: + data_size: 图片字节数。 + page_text_chars: 当页提取到的正文字符数。 + scan_likely: 是否判定为扫描件。 + text_heavy_pdf: 是否全文偏文本密集。 + figure_rich_handbook: 是否图文手册策略。 + + Returns: + True 表示保留该嵌入图。 + """ if data_size <= 0: return False if scan_likely: return data_size >= _MIN_SCAN_IMAGE_BYTES + if figure_rich_handbook: + return ( + data_size >= _MIN_FIGURE_HANDBOOK_IMAGE_BYTES + and page_text_chars <= _FIGURE_HANDBOOK_PAGE_TEXT_LIMIT + ) if text_heavy_pdf: return page_text_chars <= _TEXT_HEAVY_PAGE_TEXT_LIMIT and data_size >= _MIN_TEXT_HEAVY_IMAGE_BYTES return page_text_chars <= 80 or data_size >= _MIN_DEFAULT_IMAGE_BYTES @@ -181,7 +215,27 @@ def _should_use_page_image_mode( image_count: int, largest_ratio: float, total_ratio: float, + figure_rich_handbook: bool = False, ) -> bool: + """ + 判断当页是否改用「整页渲染图」模式(便于 OCR)。 + + 核心逻辑:扫描件/少字大图页走整页图;手册类在嵌图很少但版面以图为主时也启用。 + + Args: + scan_likely / text_heavy_pdf: PDF 全局特征。 + text_chars / image_count / largest_ratio / total_ratio: 当页特征。 + figure_rich_handbook: 手册策略开关。 + + Returns: + True 表示渲染整页图而非仅保留嵌入图。 + """ + if figure_rich_handbook: + # 手册扫描分片:嵌图提取失败时,用整页图兜底 OCR + if image_count == 0 and (largest_ratio >= 0.35 or total_ratio >= 0.4 or text_chars < 80): + return True + if largest_ratio >= 0.55 or total_ratio >= 0.65: + return True if text_heavy_pdf and text_chars > _TEXT_HEAVY_PAGE_TEXT_LIMIT: return False if scan_likely: @@ -201,9 +255,22 @@ def _should_use_page_image_mode( def _analysis_candidate_pages( - page_payloads: list[dict], scan_likely: bool, text_heavy_pdf: bool + page_payloads: list[dict], + scan_likely: bool, + text_heavy_pdf: bool, + figure_rich_handbook: bool = False, ) -> list[int]: - if scan_likely: + """ + 选出需要做版面/图片框分析的页码列表。 + + Args: + page_payloads: 每页 text/images 摘要。 + scan_likely / text_heavy_pdf / figure_rich_handbook: 文档策略。 + + Returns: + 1-based 页码列表。 + """ + if scan_likely or figure_rich_handbook: return [int(payload["page"]) for payload in page_payloads] if text_heavy_pdf: return [ @@ -305,8 +372,21 @@ def _render_page_png( def run(input_data: dict, context: Context) -> list[Block]: + """ + 加载 PDF 为 paragraph / image blocks。 + + 核心逻辑:提取文本与嵌入图;扫描或手册类可渲染整页图;结果写入 context.extras。 + + Args: + input_data: 须含 file_path。 + context: 流水线上下文(会写入 pages/images/extras)。 + + Returns: + Block 列表。 + """ file_path = Path(input_data["file_path"]) blocks: list[Block] = [] + figure_rich_handbook = is_figure_rich_handbook(file_path.name) try: from pypdf import PdfReader @@ -338,6 +418,7 @@ def run(input_data: dict, context: Context) -> list[Block]: page_text_chars=len(text), scan_likely=False, text_heavy_pdf=False, + figure_rich_handbook=figure_rich_handbook, ): continue ext = (getattr(img, "image_format", "") or "").lower() @@ -366,10 +447,14 @@ def run(input_data: dict, context: Context) -> list[Block]: page_text_chars=len(str(payload.get("text") or "")), scan_likely=scan_likely, text_heavy_pdf=text_heavy_pdf, + figure_rich_handbook=figure_rich_handbook, ) ] candidate_pages = _analysis_candidate_pages( - page_payloads, scan_likely, text_heavy_pdf + page_payloads, + scan_likely, + text_heavy_pdf, + figure_rich_handbook=figure_rich_handbook, ) image_boxes_by_page: dict[int, list[tuple[float, float, float, float]]] = {} pdfium_doc = None @@ -402,6 +487,7 @@ def run(input_data: dict, context: Context) -> list[Block]: image_count=len(page_images) or int(stats["count"]), largest_ratio=float(stats["largest_ratio"]), total_ratio=float(stats["total_ratio"]), + figure_rich_handbook=figure_rich_handbook, ) if text: @@ -476,6 +562,11 @@ def run(input_data: dict, context: Context) -> list[Block]: context.extras["scan_likely"] = True if text_heavy_pdf: context.extras["text_heavy_pdf"] = True + if figure_rich_handbook: + context.extras["figure_rich_handbook"] = True + context.warnings.append( + "figure-rich handbook mode: keep embedded figures and prefer OCR captions" + ) if page_image_mode_pages: context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages context.warnings.append( diff --git a/scripts/split_large_pdfs_for_kb.py b/scripts/split_large_pdfs_for_kb.py new file mode 100644 index 00000000..b7c829a0 --- /dev/null +++ b/scripts/split_large_pdfs_for_kb.py @@ -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())