Files
syops/backend/edkb_system/skills/loader_pdf.py
T

585 lines
19 KiB
Python

"""
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
import io
from pathlib import Path
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
_TEXT_HEAVY_PAGE_TEXT_LIMIT = 40
_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",
"connectionSet",
"dataDescription",
"desc",
"extras",
"form",
"localeSet",
"manifest",
"occur",
"template",
}
def _is_scanned(text_chars: int, pages: int) -> bool:
return text_chars < int(150 * max(pages, 1))
def _is_text_heavy_pdf(text_chars: int, pages: int) -> bool:
return text_chars >= max(800, 180 * max(pages, 1))
def _should_keep_embedded_image(
*,
data_size: int,
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
def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str:
b64 = base64.b64encode(blob).decode("ascii")
return f"data:{content_type};base64,{b64}"
def _local_name(tag: str) -> str:
return str(tag or "").rsplit("}", 1)[-1]
def _normalize_xfa_text(text: str) -> str:
return re.sub(r"[ \t\r\f\v]+", " ", str(text or "")).strip()
def _iter_xfa_roots(reader) -> list[ET.Element]:
try:
xfa_obj = getattr(reader, "xfa", None)
xfa = xfa_obj if isinstance(xfa_obj, dict) else getattr(xfa_obj, "xfa", None)
except Exception:
xfa = None
if not xfa:
return []
roots: list[ET.Element] = []
items = xfa.items() if isinstance(xfa, dict) else xfa
for _name, payload in items:
if isinstance(payload, str):
raw = payload.encode("utf-8", errors="ignore")
else:
raw = bytes(payload or b"")
if not raw.strip():
continue
try:
roots.append(ET.fromstring(raw))
except Exception:
continue
return roots
def _render_xfa_leaf_rows(node: ET.Element, prefix: tuple[str, ...] = ()) -> list[str]:
tag = _local_name(node.tag)
if tag in _XFA_SKIP_TAGS:
return []
children = [child for child in list(node) if isinstance(child.tag, str)]
text = _normalize_xfa_text(" ".join(node.itertext()))
if not children:
return [f"{'/'.join((*prefix, tag))}: {text}"] if text else []
leaf_children = [
child
for child in children
if not [grand for grand in list(child) if isinstance(grand.tag, str)]
and _normalize_xfa_text(" ".join(child.itertext()))
]
if tag in _XFA_ROW_CONTAINER_TAGS and leaf_children:
cells = [
f"{_local_name(child.tag)}={_normalize_xfa_text(' '.join(child.itertext()))}"
for child in leaf_children
]
return [f"{'/'.join((*prefix, tag))}: " + " | ".join(cells)]
rows: list[str] = []
for child in children:
rows.extend(_render_xfa_leaf_rows(child, (*prefix, tag)))
return rows
def _extract_xfa_text(reader) -> str:
rows: list[str] = []
seen: set[str] = set()
for root in _iter_xfa_roots(reader):
for row in _render_xfa_leaf_rows(root):
if row in seen:
continue
seen.add(row)
rows.append(row)
return "\n".join(rows).strip()
def _normalize_box(
bounds: tuple[float, float, float, float],
) -> tuple[float, float, float, float]:
x0, y0, x1, y1 = bounds
left = min(x0, x1)
right = max(x0, x1)
top = min(y0, y1)
bottom = max(y0, y1)
return (left, top, right, bottom)
def _page_image_stats(
page_width: float,
page_height: float,
image_boxes: list[tuple[float, float, float, float]],
) -> dict[str, float]:
if page_width <= 0 or page_height <= 0 or not image_boxes:
return {
"count": float(len(image_boxes)),
"largest_ratio": 0.0,
"total_ratio": 0.0,
}
page_area = max(page_width * page_height, 1.0)
largest_ratio = 0.0
total_ratio = 0.0
for raw in image_boxes:
x0, y0, x1, y1 = _normalize_box(raw)
width = max(x1 - x0, 0.0)
height = max(y1 - y0, 0.0)
ratio = min((width * height) / page_area, 1.0)
largest_ratio = max(largest_ratio, ratio)
total_ratio += ratio
return {
"count": float(len(image_boxes)),
"largest_ratio": largest_ratio,
"total_ratio": min(total_ratio, 1.5),
}
def _should_use_page_image_mode(
*,
scan_likely: bool,
text_heavy_pdf: bool,
text_chars: int,
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:
if image_count == 0:
return True
if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3:
return True
if text_chars <= _DEFAULT_PAGE_TEXT_LIMIT and (
largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45)
):
return True
if text_heavy_pdf:
return text_chars <= _TEXT_HEAVY_PAGE_TEXT_LIMIT and (
largest_ratio >= 0.88 or total_ratio >= 0.95 or image_count >= 8
)
return False
def _analysis_candidate_pages(
page_payloads: list[dict],
scan_likely: bool,
text_heavy_pdf: bool,
figure_rich_handbook: bool = False,
) -> list[int]:
"""
选出需要做版面/图片框分析的页码列表。
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 [
int(payload["page"])
for payload in page_payloads
if len(str(payload.get("text") or "")) <= _TEXT_HEAVY_PAGE_TEXT_LIMIT
]
return [
int(payload["page"])
for payload in page_payloads
if len(str(payload.get("text") or "")) <= _DEFAULT_PAGE_TEXT_LIMIT
]
def _collect_image_boxes_from_doc(
doc, page_numbers: list[int]
) -> dict[int, list[tuple[float, float, float, float]]]:
try:
import pypdfium2.raw as pdfium_c
except Exception:
return {}
out: dict[int, list[tuple[float, float, float, float]]] = {}
for page_number in page_numbers:
try:
page = doc[page_number - 1]
except Exception:
continue
boxes: list[tuple[float, float, float, float]] = []
try:
for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]):
try:
bounds = obj.get_bounds()
except Exception:
bounds = obj.get_pos()
boxes.append(tuple(float(v) for v in bounds))
except Exception:
boxes = []
out[page_number] = boxes
return out
def _collect_image_boxes(
file_path: Path, page_numbers: list[int]
) -> dict[int, list[tuple[float, float, float, float]]]:
try:
import pypdfium2 as pdfium
except Exception:
return {}
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
return _collect_image_boxes_from_doc(doc, page_numbers)
except Exception:
return {}
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
def _render_page_image_from_doc(
doc, page_number: int, scale: float = _PAGE_IMAGE_RENDER_SCALE
) -> object | None:
try:
import numpy as np
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil().convert("RGB")
return np.asarray(pil_image)
except Exception:
return None
def _render_page_png(
file_path: Path, page_number: int, scale: float = _PAGE_IMAGE_RENDER_SCALE
) -> object | None:
try:
import pypdfium2 as pdfium
except Exception:
return None
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
return _render_page_image_from_doc(doc, page_number, scale=scale)
except Exception:
return None
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
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
reader = PdfReader(str(file_path))
context.pages = len(reader.pages)
xfa_text = _extract_xfa_text(reader)
text_chars = 0
page_payloads: list[dict] = []
for page_idx, p in enumerate(reader.pages, start=1):
text = (p.extract_text() or "").strip()
images: list[dict] = []
if text:
text_chars += len(text)
try:
page_width = float(getattr(getattr(p, "mediabox", None), "width", 1000.0) or 1000.0)
page_height = float(getattr(getattr(p, "mediabox", None), "height", 1000.0) or 1000.0)
except Exception:
page_width = 1000.0
page_height = 1000.0
try:
for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1):
data = getattr(img, "data", None)
if not data:
continue
if not _should_keep_embedded_image(
data_size=len(data),
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()
ct = f"image/{ext}" if ext else "image/png"
images.append({"id": img_idx, "data": data, "content_type": ct})
except Exception:
pass
page_payloads.append(
{
"page": page_idx,
"text": text,
"images": images,
"page_width": page_width,
"page_height": page_height,
}
)
scan_likely = _is_scanned(text_chars, context.pages)
text_heavy_pdf = _is_text_heavy_pdf(text_chars, context.pages)
for payload in page_payloads:
payload["images"] = [
item
for item in payload["images"]
if _should_keep_embedded_image(
data_size=len(item.get("data") or b""),
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,
figure_rich_handbook=figure_rich_handbook,
)
image_boxes_by_page: dict[int, list[tuple[float, float, float, float]]] = {}
pdfium_doc = None
if candidate_pages:
try:
import pypdfium2 as pdfium
pdfium_doc = pdfium.PdfDocument(str(file_path))
image_boxes_by_page = _collect_image_boxes_from_doc(
pdfium_doc, candidate_pages
)
except Exception:
image_boxes_by_page = _collect_image_boxes(file_path, candidate_pages)
page_image_mode_pages: list[int] = []
for payload in page_payloads:
page_idx = int(payload["page"])
text = str(payload["text"] or "")
page_images = list(payload["images"])
image_boxes = image_boxes_by_page.get(page_idx, [])
stats = _page_image_stats(
float(payload.get("page_width") or 1000.0),
float(payload.get("page_height") or 1000.0),
image_boxes,
)
use_page_image_mode = _should_use_page_image_mode(
scan_likely=scan_likely,
text_heavy_pdf=text_heavy_pdf,
text_chars=len(text),
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:
blocks.append(
Block(
id=f"pdf-{page_idx}",
page=page_idx,
type="paragraph",
text=text,
bbox=(0.0, 0.0, 1000.0, 1000.0),
)
)
if use_page_image_mode:
rendered = (
_render_page_image_from_doc(pdfium_doc, page_idx)
if pdfium_doc is not None
else _render_page_png(file_path, page_idx)
)
if rendered is not None:
blocks.append(
Block(
id=f"pdf-page-{page_idx}",
page=page_idx,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"page_image": True,
"page_image_source": "pdf",
"image": rendered,
},
)
)
context.images += 1
page_image_mode_pages.append(page_idx)
continue
for item in page_images:
blocks.append(
Block(
id=f"pdf-{page_idx}-img-{item['id']}",
page=page_idx,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"data_uri": _to_data_uri(
item["data"], str(item["content_type"])
)
},
)
)
context.images += 1
if xfa_text:
blocks.append(
Block(
id="pdf-xfa",
page=1,
type="paragraph",
text=xfa_text,
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={"source": "pdf_xfa"},
)
)
context.extras["pdf_xfa_text"] = True
context.warnings.append("pdf xfa datasets extracted")
if scan_likely:
context.warnings.append("pdf likely scanned; OCR recommended")
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(
"pdf page-image mode pages: "
+ ", ".join(str(x) for x in page_image_mode_pages)
)
try:
if pdfium_doc is not None:
pdfium_doc.close()
except Exception:
pass
except Exception as exc:
context.warnings.append(f"PDF parse failed: {exc}")
return blocks