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

+47 -4
View File
@@ -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")
+28 -1
View File
@@ -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)
+82 -9
View File
@@ -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"
+94 -3
View File
@@ -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(