Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: use PDFDocument, PDFPage in most code

jinzhenj2d2632bb4e1f
diff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.py
index 9840a914..2652e423 100644
--- a/mineru/backend/flash/pdf_extractor.py
+++ b/mineru/backend/flash/pdf_extractor.py
@@ -1,48 +1,19 @@
-"""Flash tier PDF extractor — CPU-only text extraction via pypdfium2."""
+"""Flash tier PDF extractor — CPU-only text extraction."""
from __future__ import annotations
-import pypdfium2
-
-from ...utils.pdfium_guard import close_pdfium_child, close_pdfium_document, open_pdfium_document, pdfium_guard
+from ...utils.pdf_document import PDFDocument
def extract_pages_text(filepath: str, start_page: int = 0, end_page: int | None = None) -> list[str]:
"""Extract plain text from each PDF page, preserving empty pages."""
- pdf = open_pdfium_document(pypdfium2.PdfDocument, filepath)
- try:
- with pdfium_guard():
- total = len(pdf)
- end = total if end_page is None else min(end_page, total)
-
- pages: list[str] = []
- for i in range(start_page, end):
- page = None
- text_page = None
- try:
- with pdfium_guard():
- page = pdf[i]
- text_page = page.get_textpage()
- pages.append(text_page.get_text_range() or "")
- finally:
- close_pdfium_child(text_page)
- close_pdfium_child(page)
- return pages
- finally:
- close_pdfium_document(pdf)
-
-
-def extract_text(filepath: str, start_page: int = 0, end_page: int | None = None) -> str:
- """Extract plain text from a PDF file using pypdfium2.
-
- Args:
- filepath: Path to the PDF file.
- start_page: 0-based start page (inclusive).
- end_page: 0-based end page (exclusive). None means all pages.
-
- Returns:
- Extracted text as a string, one page per `\\n\\n`.
- """
+ pages: list[str] = []
+ with PDFDocument(filepath) as pdf_doc:
+ page_count = pdf_doc.page_count
+ end = page_count if end_page is None else min(end_page, page_count)
- return "\n\n".join(text for text in extract_pages_text(filepath, start_page, end_page) if text)
+ # TODO: jzj here has issue
+ for page_idx in range(start_page, end):
+ pages.append(pdf_doc.get_page_text(page_idx))
+ return pages
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 5fb9ff36..21b0afd3 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -9,7 +9,6 @@ from typing import Any, Literal
import cv2
import numpy as np
-import pypdfium2 as pdfium
from loguru import logger
from mineru_vl_utils import MinerUClient
from mineru_vl_utils.structs import BlockType
@@ -29,9 +28,8 @@ from ...utils.ocr_utils import (
sorted_boxes,
update_det_boxes,
)
-from ...utils.pdf_classify import classify
-from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_doc
-from ...utils.pdfium_guard import close_pdfium_document, get_pdfium_document_page_count, open_pdfium_document
+from ...utils.pdf_document import PDFDocument
+from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_bytes_range
from ..pipeline.model_init import (
HybridModelSingleton,
MineruHybridModel,
@@ -69,14 +67,11 @@ def _is_hybrid_ocr_det_candidate(block: dict[str, Any]) -> bool:
return (block.get("type") or block.get("label")) in NOT_EXTRACT_TYPES
-def ocr_classify(
- pdf_bytes: bytes,
- parse_method: str = "auto",
-) -> bool:
+def ocr_classify(pdf_doc: PDFDocument, parse_method: str = "auto") -> bool:
# 确定OCR设置
_ocr_enable = False
if parse_method == "auto":
- if classify(pdf_bytes) == "ocr":
+ if pdf_doc.classify() == "ocr":
_ocr_enable = True
elif parse_method == "ocr":
_ocr_enable = True
@@ -752,16 +747,17 @@ def doc_analyze(
predictor = _maybe_enable_serial_execution(predictor, backend)
device = get_device()
- _ocr_enable = ocr_classify(pdf_bytes, parse_method=parse_method)
+
+ pdf_doc = PDFDocument(pdf_bytes)
+ _ocr_enable = ocr_classify(pdf_doc, parse_method=parse_method)
_vlm_ocr_enable = _should_enable_vlm_ocr(_ocr_enable, language, inline_formula_enable)
- pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
middle_json: list[PageInfo] = []
model_list: list[list[dict[str, Any]]] = []
doc_closed = False
hybrid_pipeline_model = None
try:
- page_count = get_pdfium_document_page_count(pdf_doc)
+ page_count = pdf_doc.page_count
configured_window_size = get_processing_window_size(default=64)
effective_window_size = min(page_count, configured_window_size) if page_count else 0
total_windows = (page_count + effective_window_size - 1) // effective_window_size if effective_window_size else 0
@@ -778,12 +774,11 @@ def doc_analyze(
try:
for window_index, window_start in enumerate(range(0, page_count, effective_window_size or 1)):
window_end = min(page_count - 1, window_start + effective_window_size - 1)
- images_list = load_images_from_pdf_doc(
- pdf_doc,
+ images_list = load_images_from_pdf_bytes_range(
+ pdf_bytes=pdf_bytes,
start_page_id=window_start,
end_page_id=window_end,
image_type=ImageType.PIL,
- pdf_bytes=pdf_bytes,
)
try:
images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
@@ -868,13 +863,13 @@ def doc_analyze(
_ocr_enable,
_vlm_ocr_enable,
)
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
doc_closed = True
clean_memory(device)
return middle_json, model_list, _vlm_ocr_enable
finally:
if not doc_closed:
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
async def aio_doc_analyze(
@@ -903,16 +898,17 @@ async def aio_doc_analyze(
predictor = _maybe_enable_serial_execution(predictor, backend)
device = get_device()
- _ocr_enable = ocr_classify(pdf_bytes, parse_method=parse_method)
+
+ pdf_doc = PDFDocument(pdf_bytes)
+ _ocr_enable = ocr_classify(pdf_doc, parse_method=parse_method)
_vlm_ocr_enable = _should_enable_vlm_ocr(_ocr_enable, language, inline_formula_enable)
- pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
middle_json: list[PageInfo] = []
model_list = []
doc_closed = False
hybrid_pipeline_model = None
try:
- page_count = get_pdfium_document_page_count(pdf_doc)
+ page_count = pdf_doc.page_count
configured_window_size = get_processing_window_size(default=64)
effective_window_size = min(page_count, configured_window_size) if page_count else 0
total_windows = (page_count + effective_window_size - 1) // effective_window_size if effective_window_size else 0
@@ -1022,10 +1018,10 @@ async def aio_doc_analyze(
_ocr_enable,
_vlm_ocr_enable,
)
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
doc_closed = True
clean_memory(device)
return middle_json, model_list, _vlm_ocr_enable
finally:
if not doc_closed:
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index f1ce452c..c3330321 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -10,6 +10,7 @@ from PIL import Image
from ...types import EMPTY_BBOX, NOT_EXTRACT_TYPES, BBox, Block, BlockType, ContentType, IntBBox, Line, Span
from ...utils.guess_suffix_or_lang import guess_language_by_text
+from ...utils.pdf_document import PDFPage
from ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
from ..utils.content_block_draft import VlmContentBlockDraft
from ..utils.span_block_fix import fix_text_block
@@ -57,7 +58,7 @@ class MagicModel:
def __init__(
self,
page_model_list: list[dict[str, Any]],
- page: object,
+ pdf_page: PDFPage,
scale: float,
page_pil_img: Image.Image,
width: int,
@@ -103,7 +104,7 @@ class MagicModel:
# Bad code
virtual_block = (0, 0, width, height, None, None, None, "text")
page_text_inline_formula_spans = txt_spans_extract(
- page,
+ pdf_page,
page_text_inline_formula_spans,
page_pil_img,
scale,
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index 504e099c..62f5525b 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -8,7 +8,7 @@ from typing import Any
from ...types import Block, BlockType, PageInfo
from ...utils.config_reader import get_table_enable
from ...utils.hash_utils import bytes_md5
-from ...utils.pdfium_guard import pdfium_guard
+from ...utils.pdf_document import PDFPage
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ..pipeline.model_init import MineruHybridModel
from ..utils.middle_json_utils import apply_post_ocr
@@ -41,7 +41,7 @@ def _resolve_title_line_avg_height(title_block: Block) -> int:
def blocks_to_page_info(
page_model_list: list[dict[str, Any]],
image_dict: dict[str, Any],
- page: Any,
+ pdf_page: PDFPage,
page_index: int,
_ocr_enable: bool,
_vlm_ocr_enable: bool,
@@ -51,12 +51,11 @@ def blocks_to_page_info(
scale = image_dict["scale"]
page_pil_img = image_dict["img_pil"]
page_img_md5 = bytes_md5(page_pil_img.tobytes())
- with pdfium_guard():
- width, height = map(int, page.get_size())
+ width, height = map(int, pdf_page.size)
magic_model = MagicModel(
page_model_list,
- page,
+ pdf_page,
scale,
page_pil_img,
width,
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
index 8c873207..4041611b 100644
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ b/mineru/backend/pipeline/model_output_to_middle_json.py
@@ -4,7 +4,7 @@ from typing import Any
from ...types import Block, BlockType, ContentType, PageInfo, Span
from ...utils.hash_utils import bytes_md5
from ...utils.page_index import resolve_output_page_idx
-from ...utils.pdfium_guard import pdfium_guard
+from ...utils.pdf_document import PDFDocument, PDFPage
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ..utils.char_utils import full_to_half
from ..utils.middle_json_utils import append_pages, apply_post_ocr
@@ -18,17 +18,16 @@ from .pipeline_magic_model import MagicModel
def blocks_to_page_info(
page_model_info: dict[str, Any],
image_dict: dict[str, Any],
- page: Any,
+ pdf_page: PDFPage,
page_index: int,
ocr_enable: bool = False,
) -> PageInfo:
scale = image_dict["scale"]
page_pil_img = image_dict["img_pil"]
page_img_md5 = bytes_md5(page_pil_img.tobytes())
- with pdfium_guard():
- page_w, page_h = map(int, page.get_size())
+ page_w, page_h = map(int, pdf_page.size)
- magic_model = MagicModel(page_model_info, page, scale, page_pil_img, page_w, page_h, ocr_enable)
+ magic_model = MagicModel(page_model_info, pdf_page, scale, page_pil_img, page_w, page_h, ocr_enable)
"""从magic_model对象中获取后面会用到的区块信息"""
preproc_blocks = magic_model.get_preproc_blocks()
@@ -60,7 +59,7 @@ def append_batch_results_to_middle_json(
middle_json: list[PageInfo],
batch_results: list[list[dict[str, Any]]],
images_list: list[dict[str, Any]],
- pdf_doc: Any,
+ pdf_doc: PDFDocument,
page_start_index: int = 0,
ocr_enable: bool = False,
model_list: list[dict[str, Any]] | None = None,
diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py
index ebdb74ae..a2c44fc5 100644
--- a/mineru/backend/pipeline/pipeline_analyze.py
+++ b/mineru/backend/pipeline/pipeline_analyze.py
@@ -6,7 +6,6 @@ import time
from collections.abc import Callable
from typing import Any
-import pypdfium2 as pdfium
from loguru import logger
from PIL import Image
from tqdm import tqdm
@@ -14,9 +13,8 @@ from tqdm import tqdm
from ...utils.config_reader import get_device, get_processing_window_size
from ...utils.enum_class import ImageType
from ...utils.model_utils import clean_memory, get_vram
-from ...utils.pdf_classify import classify
-from ...utils.pdf_image_tools import load_images_from_pdf_doc
-from ...utils.pdfium_guard import close_pdfium_document, get_pdfium_document_page_count, open_pdfium_document
+from ...utils.pdf_document import PDFDocument
+from ...utils.pdf_image_tools import load_images_from_pdf_bytes_range
from ..utils.runtime_utils import exclude_progress_bar_idle_time
from .model_init import PIPELINE_MODEL_INIT_LOCK, MineruPipelineModel
from .model_output_to_middle_json import (
@@ -83,9 +81,9 @@ def custom_model_init(
return custom_model
-def _get_ocr_enable(pdf_bytes: bytes, parse_method: str) -> bool:
+def _get_ocr_enable(pdf_doc: PDFDocument, parse_method: str) -> bool:
if parse_method == "auto":
- return classify(pdf_bytes) == "ocr"
+ return pdf_doc.classify() == "ocr"
if parse_method == "ocr":
return True
return False
@@ -123,7 +121,7 @@ def _finalize_processing_window_context(
context["middle_json"],
context["ocr_enable"],
)
- close_pdfium_document(context["pdf_doc"])
+ context["pdf_doc"].close()
context["closed"] = True
@@ -160,10 +158,10 @@ def doc_analyze_streaming(
try:
total_pages = 0
for doc_index, (pdf_bytes, lang) in enumerate(zip(pdf_bytes_list, lang_list)):
- _ocr_enable = _get_ocr_enable(pdf_bytes, parse_method)
- pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
+ pdf_doc = PDFDocument(pdf_bytes)
+ _ocr_enable = _get_ocr_enable(pdf_doc, parse_method)
try:
- page_count = get_pdfium_document_page_count(pdf_doc)
+ page_count = pdf_doc.page_count
context = {
"doc_index": doc_index,
"pdf_bytes": pdf_bytes,
@@ -178,7 +176,7 @@ def doc_analyze_streaming(
"closed": False,
}
except Exception:
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
raise
total_pages += page_count
doc_contexts.append(context)
@@ -224,12 +222,11 @@ def doc_analyze_streaming(
continue
take_count = min(batch_capacity, context["page_count"] - page_start)
page_end = page_start + take_count - 1
- images_list = load_images_from_pdf_doc(
- context["pdf_doc"],
+ images_list = load_images_from_pdf_bytes_range(
+ pdf_bytes=context["pdf_bytes"],
start_page_id=page_start,
end_page_id=page_end,
image_type=ImageType.PIL,
- pdf_bytes=context["pdf_bytes"],
)
images_with_extra_info = [
(image_dict["img_pil"], context["ocr_enable"], context["lang"]) for image_dict in images_list
@@ -310,7 +307,7 @@ def doc_analyze_streaming(
finally:
for context in doc_contexts:
if not context["closed"]:
- close_pdfium_document(context["pdf_doc"])
+ context["pdf_doc"].close()
context["closed"] = True
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index f77cfd04..c41cb129 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -1,13 +1,14 @@
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
-from dataclasses import dataclass
from copy import deepcopy
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from ...render.merge import _merge_para_text
from ...types import EMPTY_BBOX, BBox, Block, BlockType, ContentType, Line, Span
from ...utils.guess_suffix_or_lang import guess_language_by_text
+from ...utils.pdf_document import PDFPage
from ..utils.boxbase import calculate_overlap_area_2_minbox_area_ratio, calculate_overlap_area_in_bbox1_area_ratio
from ..utils.span_block_fix import (
is_vertical_text_block_by_spans,
@@ -138,7 +139,7 @@ class MagicModel:
def __init__(
self,
page_model_info: dict[str, Any],
- page: object = None,
+ pdf_page: PDFPage,
scale: float = 1,
page_pil_img: PILImage | None = None,
page_w: int = 0,
@@ -161,7 +162,7 @@ class MagicModel:
# Bad code
virtual_block = (0, 0, page_w, page_h, None, None, None, "text")
self.page_ocr_res = txt_spans_extract(
- page,
+ pdf_page,
self.page_ocr_res,
page_pil_img,
scale,
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index c7309f0e..3a25d16d 100644
--- a/mineru/backend/utils/middle_json_utils.py
+++ b/mineru/backend/utils/middle_json_utils.py
@@ -13,7 +13,7 @@ from typing import Any, Callable, Iterator, TypeVar, Union
from ...types import Block, PageInfo, Span
from ...utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_needed
from ...utils.page_index import resolve_output_page_idx
-from ...utils.pdfium_guard import close_pdfium_child, pdfium_guard
+from ...utils.pdf_document import PDFDocument, PDFPage
from ..pipeline.model_init import run_ocr_rec_inference
T = TypeVar("T")
@@ -23,12 +23,12 @@ def append_pages(
middle_json: list[PageInfo],
model_list: list[T],
images_list: list[dict[str, Any]],
- pdf_doc: Any,
+ pdf_doc: PDFDocument,
*,
page_cvt_fn: Union[
- Callable[[T, dict[str, Any], Any, int], PageInfo],
- Callable[[T, dict[str, Any], Any, int, bool], PageInfo],
- Callable[[T, dict[str, Any], Any, int, bool, bool], PageInfo],
+ Callable[[T, dict[str, Any], PDFPage, int], PageInfo],
+ Callable[[T, dict[str, Any], PDFPage, int, bool], PageInfo],
+ Callable[[T, dict[str, Any], PDFPage, int, bool, bool], PageInfo],
],
page_start_index: int = 0,
page_index_map: list[int] | None = None,
@@ -41,27 +41,23 @@ def append_pages(
is ``page_cvt_fn``, which converts one page's model output into a
page_info dict.
"""
-
for offset, (page_data, image_dict) in enumerate(zip(model_list, images_list)):
physical_page_idx = page_start_index + offset
output_page_idx = resolve_output_page_idx(physical_page_idx, page_index_map)
- page = None
- try:
- with pdfium_guard():
- page = pdf_doc[physical_page_idx]
- page_info = page_cvt_fn(copy.deepcopy(page_data), image_dict, page, output_page_idx, **kwargs)
- if page_info is None:
- with pdfium_guard():
- page_w, page_h = map(int, page.get_size())
- page_info = PageInfo(
- preproc_blocks=[],
- page_idx=output_page_idx,
- page_size=(page_w, page_h),
- discarded_blocks=[],
- _backend=None,
- )
- finally:
- close_pdfium_child(page)
+
+ pdf_page = pdf_doc[physical_page_idx]
+ page_info = page_cvt_fn(copy.deepcopy(page_data), image_dict, pdf_page, output_page_idx, **kwargs)
+
+ if page_info is None:
+ page_w, page_h = map(int, pdf_page.size)
+ page_info = PageInfo(
+ preproc_blocks=[],
+ page_idx=output_page_idx,
+ page_size=(page_w, page_h),
+ discarded_blocks=[],
+ _backend=None,
+ )
+
middle_json.append(page_info)
if progress_bar is not None:
progress_bar.update(1)
diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.py
index b250eba1..6fefce9c 100644
--- a/mineru/backend/utils/span_pre_proc.py
+++ b/mineru/backend/utils/span_pre_proc.py
@@ -10,12 +10,12 @@ from typing import Any, Callable
import cv2
import numpy as np
from loguru import logger
+from pdftext.schema import Char
from ...types import BBox, BlockType, ContentType, Span
from ...utils.image_utils import calculate_contrast
+from ...utils.pdf_document import PDFPage, get_lines_from_chars
from ...utils.pdf_image_tools import get_crop_img
-from ...utils.pdf_text_tool import get_lines_from_chars, get_page_chars
-from ...utils.pdfium_guard import close_pdfium_child, pdfium_guard
from .boxbase import calculate_overlap_area_in_bbox1_area_ratio
MAX_NATIVE_TEXT_CHARS_PER_PAGE = 65535
@@ -38,7 +38,7 @@ def __replace_unicode(text: str) -> str:
def txt_spans_extract(
- pdf_page: Any,
+ pdf_page: PDFPage,
spans: list[Span],
pil_img: Any,
scale: float,
@@ -46,90 +46,75 @@ def txt_spans_extract(
all_discarded_blocks: list[tuple[Any, ...]],
) -> list[Span]:
page_char_count = None
- textpage = None
try:
- try:
- with pdfium_guard():
- textpage = pdf_page.get_textpage()
- page_char_count = textpage.count_chars()
- except Exception as exc:
- logger.debug(f"Failed to get page char count before txt extraction: {exc}")
-
- if page_char_count is not None and page_char_count > MAX_NATIVE_TEXT_CHARS_PER_PAGE:
- logger.info(f"Fallback to post-OCR in txt_spans_extract due to high char count: count_chars={page_char_count}")
- need_ocr_spans = [span for span in spans if span.type == ContentType.TEXT]
- return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
-
- page_chars = get_page_chars(
- pdf_page,
- textpage=textpage,
- page_char_count=page_char_count,
- )
- page_all_chars = [char for char in page_chars["chars"] if _is_supported_rotation(char["rotation"])]
-
- # 计算所有span的高度的中位数
- span_height_list = []
- for span in spans:
- if span.type in [ContentType.TEXT]:
- span_height = span.bbox[3] - span.bbox[1]
- span._extra["height"] = span_height
- span._extra["width"] = span.bbox[2] - span.bbox[0]
- span_height_list.append(span_height)
- if len(span_height_list) == 0:
- return spans
- else:
- median_span_height = statistics.median(span_height_list)
-
- useful_spans = []
- unuseful_spans = []
- # 纵向span的两个特征:1. 高度超过多个line 2. 高宽比超过某个值
- vertical_spans = []
- for span in spans:
- if span.type in [ContentType.TEXT]:
- for block in all_bboxes + all_discarded_blocks:
- if block[7] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.INTERLINE_EQUATION]:
- continue
- if calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block[0:4]) > 0.5:
- if (
- span._extra["height"] > median_span_height * 2.3
- and span._extra["height"] > span._extra["width"] * 2.3
- ):
- vertical_spans.append(span)
- elif block in all_bboxes:
- useful_spans.append(span)
- else:
- unuseful_spans.append(span)
- break
-
- """垂直的span框直接用line进行填充"""
- if len(vertical_spans) > 0:
- page_all_lines = [
- line for line in get_lines_from_chars(page_chars["chars"]) if _is_supported_rotation(line["rotation"])
- ]
- for pdfium_line in page_all_lines:
- for span in vertical_spans:
- if calculate_overlap_area_in_bbox1_area_ratio(pdfium_line["bbox"].bbox, span.bbox) > 0.5:
- for pdfium_span in pdfium_line["spans"]:
- span.content += pdfium_span["text"]
- break
+ page_char_count = pdf_page.get_char_count()
+ except Exception as exc:
+ logger.debug(f"Failed to get page char count before txt extraction: {exc}")
+ if page_char_count is not None and page_char_count > MAX_NATIVE_TEXT_CHARS_PER_PAGE:
+ logger.info(f"Fallback to post-OCR in txt_spans_extract due to high char count: count_chars={page_char_count}")
+ need_ocr_spans = [span for span in spans if span.type == ContentType.TEXT]
+ return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
+
+ page_chars = pdf_page.get_chars()
+ page_all_chars = [char for char in page_chars if _is_supported_rotation(char["rotation"])]
+
+ # 计算所有span的高度的中位数
+ span_height_list = []
+ for span in spans:
+ if span.type in [ContentType.TEXT]:
+ span_height = span.bbox[3] - span.bbox[1]
+ span._extra["height"] = span_height
+ span._extra["width"] = span.bbox[2] - span.bbox[0]
+ span_height_list.append(span_height)
+ if len(span_height_list) == 0:
+ return spans
+ else:
+ median_span_height = statistics.median(span_height_list)
+
+ useful_spans = []
+ unuseful_spans = []
+ # 纵向span的两个特征:1. 高度超过多个line 2. 高宽比超过某个值
+ vertical_spans = []
+ for span in spans:
+ if span.type in [ContentType.TEXT]:
+ for block in all_bboxes + all_discarded_blocks:
+ if block[7] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.INTERLINE_EQUATION]:
+ continue
+ if calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block[0:4]) > 0.5:
+ if span._extra["height"] > median_span_height * 2.3 and span._extra["height"] > span._extra["width"] * 2.3:
+ vertical_spans.append(span)
+ elif block in all_bboxes:
+ useful_spans.append(span)
+ else:
+ unuseful_spans.append(span)
+ break
+
+ """垂直的span框直接用line进行填充"""
+ if len(vertical_spans) > 0:
+ pdf_lines = [line for line in get_lines_from_chars(page_chars) if _is_supported_rotation(line["rotation"])]
+ for pdf_line in pdf_lines:
for span in vertical_spans:
- if len(span.content) == 0:
- spans.remove(span)
+ if calculate_overlap_area_in_bbox1_area_ratio(pdf_line["bbox"].bbox, span.bbox) > 0.5:
+ for pdf_span in pdf_line["spans"]:
+ span.content += pdf_span["text"]
+ break
- """水平的span框先用char填充,再用ocr填充空的span框"""
- new_spans = []
+ for span in vertical_spans:
+ if len(span.content) == 0:
+ spans.remove(span)
- for span in useful_spans + unuseful_spans:
- if span.type in [ContentType.TEXT]:
- span._extra["chars"] = []
- new_spans.append(span)
+ """水平的span框先用char填充,再用ocr填充空的span框"""
+ new_spans = []
- need_ocr_spans = fill_char_in_spans(new_spans, page_all_chars, median_span_height)
+ for span in useful_spans + unuseful_spans:
+ if span.type in [ContentType.TEXT]:
+ span._extra["chars"] = []
+ new_spans.append(span)
- return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
- finally:
- close_pdfium_child(textpage)
+ need_ocr_spans = fill_char_in_spans(new_spans, page_all_chars, median_span_height)
+
+ return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
def _is_supported_rotation(rotation: float) -> bool:
@@ -237,7 +222,7 @@ class SpanBlockMatcher:
def fill_char_in_spans(
spans: list[Span],
- all_chars: list[dict[str, Any]],
+ all_chars: list[Char],
median_span_height: float,
) -> list[Span]:
# 简单从上到下排一下序
diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.py
index 2fc5e567..0639186c 100644
--- a/mineru/backend/vlm/model_output_to_middle_json.py
+++ b/mineru/backend/vlm/model_output_to_middle_json.py
@@ -9,7 +9,7 @@ from mineru_vl_utils.structs import ExtractResult
from ...types import PageInfo
from ...utils.config_reader import get_table_enable
from ...utils.hash_utils import bytes_md5
-from ...utils.pdfium_guard import pdfium_guard
+from ...utils.pdf_document import PDFPage
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ..utils.para_block_utils import (
build_para_blocks_from_preproc,
@@ -24,7 +24,7 @@ from .vlm_magic_model import MagicModel
def blocks_to_page_info(
page_blocks: ExtractResult,
image_dict: dict[str, Any],
- page: Any,
+ pdf_page: PDFPage,
page_index: int,
) -> PageInfo:
"""将blocks转换为页面信息"""
@@ -32,8 +32,7 @@ def blocks_to_page_info(
scale = image_dict["scale"]
page_pil_img = image_dict["img_pil"]
page_img_md5 = bytes_md5(page_pil_img.tobytes())
- with pdfium_guard():
- width, height = map(int, page.get_size())
+ width, height = map(int, pdf_page.size)
magic_model = MagicModel(page_blocks, width, height)
image_blocks = magic_model.get_image_blocks()
diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.py
index c2b2477b..4f79150f 100644
--- a/mineru/backend/vlm/vlm_analyze.py
+++ b/mineru/backend/vlm/vlm_analyze.py
@@ -11,7 +11,6 @@ import time
from contextlib import asynccontextmanager, contextmanager
from typing import Any, AsyncIterator, Generator, Iterator, Literal
-import pypdfium2 as pdfium
from loguru import logger
from mineru_vl_utils import MinerUClient
from mineru_vl_utils.structs import ExtractResult
@@ -23,8 +22,8 @@ from ...utils.check_sys_env import is_mac_os_version_supported
from ...utils.config_reader import get_device, get_processing_window_size
from ...utils.enum_class import ImageType
from ...utils.models_download_utils import auto_download_and_get_model_root_path
-from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_doc
-from ...utils.pdfium_guard import close_pdfium_document, get_pdfium_document_page_count, open_pdfium_document
+from ...utils.pdf_document import PDFDocument
+from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_bytes_range
from ..utils.middle_json_utils import append_pages
from ..utils.runtime_utils import exclude_progress_bar_idle_time
from .model_output_to_middle_json import blocks_to_page_info, finalize_middle_json
@@ -461,12 +460,12 @@ def doc_analyze(
predictor = ModelSingleton().get_model(backend, model_path, server_url, **kwargs)
predictor = _maybe_enable_serial_execution(predictor, backend)
- pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
+ pdf_doc = PDFDocument(pdf_bytes)
middle_json: list[PageInfo] = []
results: list[ExtractResult] = []
doc_closed = False
try:
- page_count = get_pdfium_document_page_count(pdf_doc)
+ page_count = pdf_doc.page_count
configured_window_size = get_processing_window_size(default=64)
effective_window_size = min(page_count, configured_window_size) if page_count else 0
total_windows = (page_count + effective_window_size - 1) // effective_window_size if effective_window_size else 0
@@ -481,12 +480,11 @@ def doc_analyze(
try:
for window_index, window_start in enumerate(range(0, page_count, effective_window_size or 1)):
window_end = min(page_count - 1, window_start + effective_window_size - 1)
- images_list = load_images_from_pdf_doc(
- pdf_doc,
+ images_list = load_images_from_pdf_bytes_range(
+ pdf_bytes=pdf_bytes,
start_page_id=window_start,
end_page_id=window_end,
image_type=ImageType.PIL,
- pdf_bytes=pdf_bytes,
)
try:
images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
@@ -532,12 +530,12 @@ def doc_analyze(
)
if not client_side_output_generation:
finalize_middle_json(middle_json)
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
doc_closed = True
return middle_json, results
finally:
if not doc_closed:
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
async def aio_doc_analyze(
@@ -562,12 +560,12 @@ async def aio_doc_analyze(
predictor = await _get_model_async(backend, model_path, server_url, **kwargs)
predictor = _maybe_enable_serial_execution(predictor, backend)
- pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
+ pdf_doc = PDFDocument(pdf_bytes)
middle_json: list[PageInfo] = []
results: list[ExtractResult] = []
doc_closed = False
try:
- page_count = get_pdfium_document_page_count(pdf_doc)
+ page_count = pdf_doc.page_count
configured_window_size = get_processing_window_size(default=64)
effective_window_size = min(page_count, configured_window_size) if page_count else 0
total_windows = (page_count + effective_window_size - 1) // effective_window_size if effective_window_size else 0
@@ -632,9 +630,9 @@ async def aio_doc_analyze(
)
if not client_side_output_generation:
await asyncio.to_thread(finalize_middle_json, middle_json)
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
doc_closed = True
return middle_json, results
finally:
if not doc_closed:
- close_pdfium_document(pdf_doc)
+ pdf_doc.close()
diff --git a/mineru/cli_old/client.py b/mineru/cli_old/client.py
index cf66d0c7..87a2302a 100644
--- a/mineru/cli_old/client.py
+++ b/mineru/cli_old/client.py
@@ -11,25 +11,14 @@ from typing import Awaitable, Callable, Optional, TextIO
import click
import httpx
-import pypdfium2 as pdfium
from loguru import logger
+from mineru.cli_old import api_client as _api_client
from mineru.cli_old.api_protocol import (
DEFAULT_MAX_CONCURRENT_REQUESTS,
DEFAULT_PROCESSING_WINDOW_SIZE,
)
-from mineru.utils.config_reader import (
- get_max_concurrent_requests as read_max_concurrent_requests,
-)
-from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
-from mineru.utils.pdf_page_id import get_end_page_id
-from mineru.utils.pdfium_guard import (
- close_pdfium_document,
- get_pdfium_document_page_count,
- open_pdfium_document,
-)
-
-from mineru.version import __version__
+from mineru.cli_old.client_side_output import regenerate_client_side_outputs
from mineru.cli_old.common import (
HybridDependencyError,
ensure_backend_dependencies,
@@ -38,17 +27,23 @@ from mineru.cli_old.common import (
pdf_suffixes,
uniquify_task_stems,
)
-from mineru.cli_old import api_client as _api_client
-from mineru.cli_old.client_side_output import regenerate_client_side_outputs
from mineru.cli_old.output_paths import resolve_parse_dir
from mineru.cli_old.visualization import (
VisualizationJob,
run_visualization_job,
)
+from mineru.utils.config_reader import (
+ get_max_concurrent_requests as read_max_concurrent_requests,
+)
+from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
+from mineru.utils.pdf_document import PDFDocument
+from mineru.utils.pdf_page_id import get_end_page_id
+from mineru.version import __version__
os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
+
@dataclass(frozen=True)
class InputDocument:
path: Path
@@ -167,9 +162,7 @@ class LiveTaskStatusRenderer:
return
if isinstance(status_update, _api_client.TaskStatusSnapshot):
status = status_update.status
- queued_ahead = (
- status_update.queued_ahead if status == "pending" else None
- )
+ queued_ahead = status_update.queued_ahead if status == "pending" else None
else:
status = status_update
queued_ahead = None
@@ -219,10 +212,7 @@ class LiveTaskStatusRenderer:
self._task_states.values(),
key=lambda state: (state.task_index, state.task_id),
)
- return [
- self._build_render_line_locked(state)
- for state in states
- ]
+ return [self._build_render_line_locked(state) for state in states]
@staticmethod
def _build_render_line_locked(state: LiveTaskStatusState) -> str:
@@ -264,6 +254,7 @@ logger.add(_stderr_sink, level=log_level)
def build_http_timeout() -> httpx.Timeout:
return _api_client.build_http_timeout()
+
def find_free_port() -> int:
return _api_client.find_free_port()
@@ -393,9 +384,7 @@ def log_visualization_future_result(
return
if result.status != "finished":
- logger.warning(
- f"Skipping visualization for {result.document_stem}: {result.message}"
- )
+ logger.warning(f"Skipping visualization for {result.document_stem}: {result.message}")
def queue_visualization_jobs(
@@ -436,10 +425,7 @@ async def wait_for_visualization_jobs(
try:
if visualization_context.futures:
await asyncio.gather(
- *(
- asyncio.wrap_future(future)
- for future in visualization_context.futures
- ),
+ *(asyncio.wrap_future(future) for future in visualization_context.futures),
return_exceptions=True,
)
finally:
@@ -478,21 +464,16 @@ def probe_pdf_effective_pages(
start_page_id: int,
end_page_id: Optional[int],
) -> int:
- pdf_doc = open_pdfium_document(pdfium.PdfDocument, str(path))
- try:
- page_count = get_pdfium_document_page_count(pdf_doc)
- finally:
- close_pdfium_document(pdf_doc)
+ with PDFDocument(str(path)) as pdf_doc:
+ page_count = pdf_doc.page_count
if page_count <= 0:
raise click.ClickException(f"PDF has no pages: {path}")
effective_end_page_id = get_end_page_id(end_page_id, page_count)
if start_page_id > effective_end_page_id:
- raise click.ClickException(
- f"Requested page range is empty for PDF {path}: "
- f"start={start_page_id}, end={end_page_id}"
- )
+ raise click.ClickException(f"Requested page range is empty for PDF {path}: start={start_page_id}, end={end_page_id}")
+
return effective_end_page_id - start_page_id + 1
@@ -535,18 +516,14 @@ def collect_input_documents(
if not collected:
raise click.ClickException(f"No supported documents found under {input_path}")
- normalized_stems, renamed_stems = uniquify_task_stems(
- [document.stem for document in collected]
- )
+ normalized_stems, renamed_stems = uniquify_task_stems([document.stem for document in collected])
if renamed_stems:
rename_details = ", ".join(
f"{document.path.name} -> {effective_stem}"
for document, effective_stem in zip(collected, normalized_stems)
if document.stem != effective_stem
)
- logger.warning(
- f"Normalized duplicate document stems within this run: {rename_details}"
- )
+ logger.warning(f"Normalized duplicate document stems within this run: {rename_details}")
return [
InputDocument(
path=document.path,
@@ -582,11 +559,7 @@ def plan_pipeline_tasks(
)
continue
- candidates = [
- task
- for task in bins
- if task.total_pages + document.effective_pages <= processing_window_size
- ]
+ candidates = [task for task in bins if task.total_pages + document.effective_pages <= processing_window_size]
if candidates:
selected = min(candidates, key=lambda task: (task.total_pages, task.index))
selected.documents.append(document)
@@ -850,9 +823,7 @@ async def run_planned_task(
parse_method,
)
except Exception as exc:
- logger.warning(
- f"Skipping visualization for {format_task_log_label(planned_task)}: {exc}"
- )
+ logger.warning(f"Skipping visualization for {format_task_log_label(planned_task)}: {exc}")
else:
queue_visualization_jobs(
visualization_context,
@@ -905,21 +876,15 @@ async def run_orchestrated_cli(
base_url = local_server.start()
logger.info(f"Started local mineru-api at {base_url}")
server_health = await wait_for_local_api_ready(http_client, local_server)
- effective_max_concurrent_requests = (
- server_health.max_concurrent_requests
- )
+ effective_max_concurrent_requests = server_health.max_concurrent_requests
else:
server_health = await fetch_server_health(
http_client,
normalize_base_url(api_url),
)
- effective_max_concurrent_requests = (
- resolve_effective_max_concurrent_requests(
- read_max_concurrent_requests(
- default=DEFAULT_MAX_CONCURRENT_REQUESTS
- ),
- server_health.max_concurrent_requests,
- )
+ effective_max_concurrent_requests = resolve_effective_max_concurrent_requests(
+ read_max_concurrent_requests(default=DEFAULT_MAX_CONCURRENT_REQUESTS),
+ server_health.max_concurrent_requests,
)
live_renderer = create_live_task_status_renderer(api_url)
@@ -970,9 +935,7 @@ async def run_orchestrated_cli(
f"- task#{failure.task_index} ({', '.join(failure.document_stems)}): {failure.message}"
for failure in sorted(failures, key=lambda item: item.task_index)
)
- raise click.ClickException(
- f"{len(failures)} task(s) failed while processing documents:\n{details}"
- )
+ raise click.ClickException(f"{len(failures)} task(s) failed while processing documents:\n{details}")
finally:
try:
if local_server is not None:
@@ -1135,10 +1098,7 @@ async def run_orchestrated_cli(
"client_side_output_generation",
type=bool,
default=False,
- help=(
- "Generate markdown and content lists locally from server-returned "
- "middle json, images, and original files."
- ),
+ help=("Generate markdown and content lists locally from server-returned middle json, images, and original files."),
)
def main(
ctx: click.Context,
diff --git a/mineru/doclib/core/file_io.py b/mineru/doclib/core/file_io.py
index 35d7040a..c65bcac9 100644
--- a/mineru/doclib/core/file_io.py
+++ b/mineru/doclib/core/file_io.py
@@ -8,9 +8,7 @@ import os
from dataclasses import dataclass
from pathlib import Path
-import pypdfium2
-
-from ...utils.pdfium_guard import close_pdfium_document, open_pdfium_document, pdfium_guard
+from ...utils.pdf_document import PDFDocument
# Optional office doc support
try:
@@ -113,18 +111,16 @@ async def extract_metadata(filepath: str) -> dict:
async def _extract_pdf_meta(filepath: str, result: dict) -> None:
def _extract() -> None:
- pdf = None
+ pdf_doc = None
try:
try:
- pdf = open_pdfium_document(pypdfium2.PdfDocument, filepath)
- with pdfium_guard():
- result["page_count"] = len(pdf)
+ pdf_doc = PDFDocument(filepath)
+ result["page_count"] = pdf_doc.page_count
except Exception as exc:
raise MetadataExtractionError("open_failed", str(exc) or "Failed to open document") from exc
try:
- with pdfium_guard():
- meta = pdf.get_metadata_dict() or {}
+ meta = pdf_doc.metadata
except Exception as exc:
raise MetadataExtractionError("read_metadata_failed", str(exc) or "Failed to read document metadata") from exc
@@ -136,8 +132,8 @@ async def _extract_pdf_meta(filepath: str, result: dict) -> None:
except Exception as exc:
raise MetadataExtractionError("read_metadata_failed", str(exc) or "Failed to read document metadata") from exc
finally:
- if pdf is not None:
- close_pdfium_document(pdf)
+ if pdf_doc is not None:
+ pdf_doc.close()
await asyncio.to_thread(_extract)
diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.py
index cfb85fa0..084bc9e4 100644
--- a/mineru/parser/pdf.py
+++ b/mineru/parser/pdf.py
@@ -196,8 +196,7 @@ class PdfBaseParser(DocumentParser):
pages_by_index = {page.page_idx: page for page in pages}
ordered_page_indices = sorted(set(pages_by_index) | set(broken_page_indices))
pages[:] = [
- pages_by_index.get(page_idx, PageInfo(page_idx=page_idx, _backend=backend))
- for page_idx in ordered_page_indices
+ pages_by_index.get(page_idx, PageInfo(page_idx=page_idx, _backend=backend)) for page_idx in ordered_page_indices
]
def _build_result(
@@ -419,7 +418,7 @@ class PdfHybridParser(PdfBaseParser):
class PdfFlashParser(PdfBaseParser):
- """PDF / image parser using the flash (CPU-only pypdfium2) backend."""
+ """PDF / image parser using the flash backend."""
_backend = "flash"
diff --git a/mineru/utils/pdf_classify.py b/mineru/utils/pdf_classify.py
index de6c5cd6..cb37c1cd 100644
--- a/mineru/utils/pdf_classify.py
+++ b/mineru/utils/pdf_classify.py
@@ -11,12 +11,7 @@ import pypdfium2.raw as pdfium_c
from loguru import logger
from pypdf import PdfReader
-from .pdfium_guard import (
- close_pdfium_child,
- close_pdfium_document,
- open_pdfium_document,
- pdfium_guard,
-)
+from .pdfium_guard import close_pdfium_child, pdfium_guard
MAX_SAMPLE_PAGES = 10
CHARS_THRESHOLD = 50
@@ -47,7 +42,7 @@ def _is_disallowed_control_unicode(unicode_code: int) -> bool:
return (0 <= unicode_code < 32 or 127 <= unicode_code <= 159) and unicode_code not in _ALLOWED_CONTROL_CODES
-def classify(pdf_bytes: bytes) -> str:
+def classify(pdf_doc: pdfium.PdfDocument, pdf_bytes: bytes) -> str:
"""
Fast PDF classification path.
@@ -57,12 +52,9 @@ def classify(pdf_bytes: bytes) -> str:
"txt" if the PDF can be parsed as text, otherwise "ocr".
"""
- pdf = None
-
try:
with pdfium_guard():
- pdf = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
- page_count = len(pdf)
+ page_count = len(pdf_doc)
if page_count == 0:
return "ocr"
@@ -71,7 +63,7 @@ def classify(pdf_bytes: bytes) -> str:
return "ocr"
extreme_page_index, extreme_ratio = get_extreme_aspect_ratio_page_pdfium(
- pdf,
+ pdf_doc,
page_indices,
)
if extreme_page_index is not None:
@@ -81,7 +73,7 @@ def classify(pdf_bytes: bytes) -> str:
)
return "ocr"
- text_samples = _collect_pdfium_text_samples(pdf, page_indices)
+ text_samples = _collect_pdfium_text_samples(pdf_doc, page_indices)
avg_cleaned_chars_per_page = _get_avg_cleaned_chars_per_page_from_samples(text_samples)
if avg_cleaned_chars_per_page < CHARS_THRESHOLD:
return "ocr"
@@ -143,16 +135,13 @@ def classify(pdf_bytes: bytes) -> str:
)
return "ocr"
- if get_high_image_coverage_ratio_pdfium(pdf, page_indices) >= HIGH_IMAGE_COVERAGE_THRESHOLD:
+ if get_high_image_coverage_ratio_pdfium(pdf_doc, page_indices) >= HIGH_IMAGE_COVERAGE_THRESHOLD:
return "ocr"
except Exception as e:
logger.error(f"Failed to classify PDF: {e}")
return "ocr"
- finally:
- close_pdfium_document(pdf)
-
return "txt"
@@ -188,7 +177,7 @@ def get_sample_page_indices(page_count: int, max_pages: int = MAX_SAMPLE_PAGES)
def get_extreme_aspect_ratio_page_pdfium(
- pdf_doc: Any,
+ pdf_doc: pdfium.PdfDocument,
page_indices: list[int],
max_page_aspect_ratio: float = MAX_PAGE_ASPECT_RATIO,
) -> tuple[Any, Any]:
@@ -258,7 +247,7 @@ def _collect_pdfium_text_sample_from_page(page_index: int, page: Any) -> dict[st
close_pdfium_child(text_page)
-def _collect_pdfium_text_samples(pdf_doc: Any, page_indices: list[int]) -> list[dict[str, Any]]:
+def _collect_pdfium_text_samples(pdf_doc: pdfium.PdfDocument, page_indices: list[int]) -> list[dict[str, Any]]:
"""一次性收集抽样页文本统计,返回纯 Python 数据,避免缓存 PDFium 子对象。"""
text_samples = []
@@ -286,7 +275,7 @@ def _get_avg_cleaned_chars_per_page_from_samples(text_samples: list[dict[str, An
return cleaned_total_chars / len(text_samples)
-def get_avg_cleaned_chars_per_page_pdfium(pdf_doc: Any, page_indices: list[int]) -> float:
+def get_avg_cleaned_chars_per_page_pdfium(pdf_doc: pdfium.PdfDocument, page_indices: list[int]) -> float:
text_samples = _collect_pdfium_text_samples(pdf_doc, page_indices)
return _get_avg_cleaned_chars_per_page_from_samples(text_samples)
@@ -322,7 +311,7 @@ def _get_text_quality_signal_from_samples(text_samples: list[dict[str, Any]]) ->
}
-def get_text_quality_signal_pdfium(pdf_doc: Any, page_indices: list[int]) -> dict[str, Any]:
+def get_text_quality_signal_pdfium(pdf_doc: pdfium.PdfDocument, page_indices: list[int]) -> dict[str, Any]:
text_samples = _collect_pdfium_text_samples(pdf_doc, page_indices)
return _get_text_quality_signal_from_samples(text_samples)
@@ -464,7 +453,7 @@ def _get_u72xx_text_signal_from_samples(text_samples: list[dict[str, Any]]) -> d
}
-def get_u72xx_text_signal_pdfium(pdf_doc: Any, page_indices: list[int]) -> dict[str, Any]:
+def get_u72xx_text_signal_pdfium(pdf_doc: pdfium.PdfDocument, page_indices: list[int]) -> dict[str, Any]:
"""统计抽样页中扣除常用字后的 U+7280-U+72DF 字符占比,用于识别可疑 ToUnicode 映射。"""
text_samples = _collect_pdfium_text_samples(pdf_doc, page_indices)
return _get_u72xx_text_signal_from_samples(text_samples)
@@ -598,7 +587,7 @@ def _resolve_pdf_object(obj: Any) -> Any:
return obj
-def get_high_image_coverage_ratio_pdfium(pdf_doc: Any, page_indices: list[int]) -> float:
+def get_high_image_coverage_ratio_pdfium(pdf_doc: pdfium.PdfDocument, page_indices: list[int]) -> float:
high_image_coverage_pages = 0
with pdfium_guard():
@@ -606,7 +595,7 @@ def get_high_image_coverage_ratio_pdfium(pdf_doc: Any, page_indices: list[int])
page = None
try:
page = pdf_doc[page_index]
- page_bbox = page.get_bbox()
+ page_bbox: tuple[float, float, float, float] = page.get_bbox()
page_area = abs((page_bbox[2] - page_bbox[0]) * (page_bbox[3] - page_bbox[1]))
image_area = 0.0
@@ -629,6 +618,9 @@ def get_high_image_coverage_ratio_pdfium(pdf_doc: Any, page_indices: list[int])
if __name__ == "__main__":
+ from .pdf_document import PDFDocument
+
with open("/Users/myhloli/pdf/luanma2x10.pdf", "rb") as f:
p_bytes = f.read()
- logger.info(f"PDF classify result: {classify(p_bytes)}")
+ pdf_doc = PDFDocument(p_bytes)
+ logger.info(f"PDF classify result: {pdf_doc.classify()}")
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index d6a47854..2b57ad93 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -4,26 +4,23 @@ from __future__ import annotations
import asyncio
import os
from contextlib import contextmanager
-from functools import cached_property
from io import BytesIO
from typing import Iterator, Literal, TypeAlias, cast
import pypdfium2 as pdfium
from pdftext.pdf.chars import deduplicate_chars, get_chars
-from pdftext.pdf.pages import assign_scripts, get_blocks, get_lines, get_spans
-from pdftext.schema import Char, Line, Span
+from pdftext.pdf.pages import assign_scripts, get_lines, get_spans
+from pdftext.schema import Char, Line
from PIL import Image, ImageOps
from ..types import BBox, PageInfo
from .draw_bbox import draw_layout_bbox, draw_span_bbox
from .pdf_classify import classify, get_sample_page_indices
-from .pdf_image_tools import _load_images_from_pdf_bytes_range, get_crop_img
+from .pdf_image_tools import get_crop_img, load_images_from_pdf_bytes_range
from .pdf_reader import image_to_bytes
from .pdfium_guard import _pdfium_lock, safe_rewrite_pdf_bytes_with_pdfium
# from .pdf_image_tools import images_bytes_to_pdf_bytes, pdf_page_to_image
-# from .pdf_text_tool import get_lines_from_chars, get_page_chars
-# from .pdfium_guard import close_pdfium_document, get_pdfium_document_page_count, open_pdfium_document
POINTS_PER_INCH: int = 72
DEFAULT_RENDER_DPI: int = 200
@@ -49,6 +46,22 @@ class PDFPageImage:
self.scale = scale
+class PDFPage:
+ def __init__(self, pdf_doc: "PDFDocument", idx: int) -> None:
+ self.pdf_doc = pdf_doc
+ self._idx = idx
+
+ @property
+ def size(self) -> tuple[float, float]:
+ return self.pdf_doc.page_size(self._idx)
+
+ def get_char_count(self) -> int:
+ return self.pdf_doc.page_char_count(self._idx)
+
+ def get_chars(self) -> list[Char]:
+ return self.pdf_doc.get_page_chars(self._idx)
+
+
class PDFDocument:
"""A PDF file loaded in memory, with lazy pypdfium2 access.
@@ -66,11 +79,17 @@ class PDFDocument:
def __init__(
self,
- pdf_bytes: bytes,
+ pdf_bytes_or_path: bytes | str,
render_scale: float = DEFAULT_RENDER_SCALE,
render_max_edge: int = DEFAULT_RENDER_MAX_EDGE,
) -> None:
- self._pdf_bytes = pdf_bytes
+ if isinstance(pdf_bytes_or_path, bytes):
+ self._pdf_bytes: bytes = pdf_bytes_or_path
+ else:
+ assert isinstance(pdf_bytes_or_path, str)
+ with open(pdf_bytes_or_path, "rb") as f:
+ self._pdf_bytes = f.read()
+
self._pdf_doc_opened: pdfium.PdfDocument | None = None
self._page_count: int | None = None
self.render_scale = render_scale
@@ -110,6 +129,9 @@ class PDFDocument:
def __len__(self) -> int:
return self.page_count
+ def __getitem__(self, idx: int) -> PDFPage:
+ return PDFPage(self, idx)
+
@property
def page_count(self) -> int:
with _pdfium_lock:
@@ -151,7 +173,7 @@ class PDFDocument:
end = self.page_count - 1
if scale is None:
scale = self.render_scale
- results = _load_images_from_pdf_bytes_range(
+ results = load_images_from_pdf_bytes_range(
pdf_bytes=self.bytes,
dpi=max(1, int(round(scale * POINTS_PER_INCH))),
start_page_id=start,
@@ -213,20 +235,29 @@ class PDFDocument:
chars = self.get_page_chars(page_idx)
return get_lines_from_chars(chars)
+ def get_page_text(self, page_idx: int) -> str:
+ with self._open_page(page_idx) as page:
+ textpage = None
+ try:
+ textpage = page.get_textpage()
+ text = textpage.get_text_range()
+ finally:
+ _try_close(textpage)
+ return text or ""
+
# ------------------------------------------------------------------ #
# Classification
# ------------------------------------------------------------------ #
def classify(self) -> Literal["ocr", "txt"]:
- # TODO: pass _pdf_doc in future.
- pdf_class = classify(self._pdf_bytes)
+ pdf_class = classify(self._pdf_doc, self.bytes)
return cast(Literal["ocr", "txt"], pdf_class)
# ------------------------------------------------------------------ #
# Page extraction
# ------------------------------------------------------------------ #
- # TODO
+ # TODO: no caller
def extract_page_range(self, start: int, end: int) -> "PDFDocument":
new_bytes = safe_rewrite_pdf_bytes_with_pdfium(
self._pdf_bytes,
@@ -235,7 +266,7 @@ class PDFDocument:
)
return PDFDocument(new_bytes)
- # TODO
+ # TODO: no caller
def sample_pages(self, max_pages: int = 3) -> "PDFDocument":
"""按 PDF 分类抽样规则提取代表性页面,返回新的 PDFDocument。"""
if max_pages <= 0:
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index 6e24e61d..2520a39d 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -23,13 +23,7 @@ from .check_sys_env import is_windows_environment
from .enum_class import ImageType
from .os_env_config import get_load_images_threads, get_load_images_timeout
from .pdf_reader import image_to_b64str, page_to_image
-from .pdfium_guard import (
- close_pdfium_child,
- close_pdfium_document,
- get_pdfium_document_page_count,
- open_pdfium_document,
- pdfium_guard,
-)
+from .pdfium_guard import close_pdfium_child, pdfium_guard
DEFAULT_PDF_IMAGE_DPI = 200
# DEFAULT_PDF_IMAGE_DPI = 144
@@ -255,7 +249,7 @@ def shutdown_pdf_render_executor() -> None:
atexit.register(shutdown_pdf_render_executor)
-def _load_images_from_pdf_bytes_range(
+def load_images_from_pdf_bytes_range(
pdf_bytes: bytes,
dpi: int = DEFAULT_PDF_IMAGE_DPI,
start_page_id: int = 0,
@@ -346,7 +340,7 @@ async def aio_load_images_from_pdf_bytes_range(
threads: int | None = None,
) -> list[dict[str, Any]]:
return await asyncio.to_thread(
- _load_images_from_pdf_bytes_range,
+ load_images_from_pdf_bytes_range,
pdf_bytes,
dpi=dpi,
start_page_id=start_page_id,
@@ -415,7 +409,7 @@ def load_images_from_pdf_core(
pdf_doc = None
try:
with pdfium_guard():
- pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
+ pdf_doc = pdfium.PdfDocument(pdf_bytes)
pdf_page_num = len(pdf_doc)
end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else pdf_page_num - 1
if end_page_id > pdf_page_num - 1:
@@ -431,47 +425,9 @@ def load_images_from_pdf_core(
finally:
close_pdfium_child(page)
finally:
- close_pdfium_document(pdf_doc)
-
- return images_list
-
-
-def load_images_from_pdf_doc(
- pdf_doc: pdfium.PdfDocument,
- dpi: int = DEFAULT_PDF_IMAGE_DPI,
- start_page_id: int = 0,
- end_page_id: int | None = None,
- image_type: Literal["pil_img", "base64_img"] = ImageType.PIL,
- pdf_bytes: bytes | None = None,
- timeout: int | None = None,
- threads: int | None = None,
-) -> list[dict[str, Any]]:
- pdf_page_num = get_pdfium_document_page_count(pdf_doc)
- normalized_end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else pdf_page_num - 1
- if normalized_end_page_id > pdf_page_num - 1:
- normalized_end_page_id = pdf_page_num - 1
-
- if pdf_bytes is not None:
- return _load_images_from_pdf_bytes_range(
- pdf_bytes,
- dpi=dpi,
- start_page_id=start_page_id,
- end_page_id=normalized_end_page_id,
- image_type=image_type,
- timeout=timeout,
- threads=threads,
- )
-
- images_list = []
- with pdfium_guard():
- for index in range(start_page_id, normalized_end_page_id + 1):
- page = None
- try:
- page = pdf_doc[index]
- image_dict = pdf_page_to_image(page, dpi=dpi, image_type=image_type)
- images_list.append(image_dict)
- finally:
- close_pdfium_child(page)
+ if pdf_doc is not None:
+ with pdfium_guard():
+ pdf_doc.close()
return images_list
diff --git a/mineru/utils/pdf_text_tool.py b/mineru/utils/pdf_text_tool.py
deleted file mode 100644
index aec91ef5..00000000
--- a/mineru/utils/pdf_text_tool.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import math
-from typing import Any
-
-import pypdfium2 as pdfium
-from pdftext.pdf.chars import deduplicate_chars, get_chars
-from pdftext.pdf.pages import assign_scripts, get_blocks, get_lines, get_spans
-
-from .pdfium_guard import close_pdfium_child, pdfium_guard
-
-
-def get_page(
- page: pdfium.PdfPage,
- quote_loosebox: bool = True,
- superscript_height_threshold: float = 0.7,
- line_distance_threshold: float = 0.1,
-) -> dict[str, Any]:
- page_chars = get_page_chars(page, quote_loosebox=quote_loosebox)
- lines = get_lines_from_chars(
- page_chars["chars"],
- superscript_height_threshold=superscript_height_threshold,
- line_distance_threshold=line_distance_threshold,
- )
- blocks = get_blocks(lines)
-
- return {
- "bbox": page_chars["bbox"],
- "width": page_chars["width"],
- "height": page_chars["height"],
- "rotation": page_chars["rotation"],
- "blocks": blocks,
- }
-
-
-def get_page_chars(
- page: pdfium.PdfPage,
- textpage: Any = None,
- quote_loosebox: bool = True,
- page_char_count: int | None = None,
-) -> dict[str, Any]:
- """轻量读取页面字符坐标,供只需要 char 级信息的路径复用。"""
- owns_textpage = textpage is None
- try:
- with pdfium_guard():
- if textpage is None:
- textpage = page.get_textpage()
- page_bbox = page.get_bbox()
- page_width = math.ceil(abs(page_bbox[2] - page_bbox[0]))
- page_height = math.ceil(abs(page_bbox[1] - page_bbox[3]))
-
- page_rotation = 0
- try:
- page_rotation = page.get_rotation()
- except Exception:
- pass
-
- if page_char_count is None:
- page_char_count = textpage.count_chars()
-
- chars = deduplicate_chars(get_chars(textpage, page_bbox, page_rotation, quote_loosebox))
- finally:
- if owns_textpage:
- close_pdfium_child(textpage)
-
- return {
- "bbox": page_bbox,
- "width": page_width,
- "height": page_height,
- "rotation": page_rotation,
- "char_count": page_char_count,
- "chars": chars,
- }
-
-
-def get_lines_from_chars(
- chars: list[dict[str, Any]],
- superscript_height_threshold: float = 0.7,
- line_distance_threshold: float = 0.1,
-) -> list[dict[str, Any]]:
- """从已提取的字符构建 pdftext lines,避免重复读取 PDFium textpage。"""
- spans = get_spans(
- chars,
- superscript_height_threshold=superscript_height_threshold,
- line_distance_threshold=line_distance_threshold,
- )
- lines = get_lines(spans)
- assign_scripts(
- lines,
- height_threshold=superscript_height_threshold,
- line_distance_threshold=line_distance_threshold,
- )
- return lines
diff --git a/mineru/utils/pdfium_guard.py b/mineru/utils/pdfium_guard.py
index a58827a1..e5291927 100644
--- a/mineru/utils/pdfium_guard.py
+++ b/mineru/utils/pdfium_guard.py
@@ -7,7 +7,6 @@ from typing import Any, Callable, Iterator, Sequence, TypeVar
from loguru import logger
-
_pdfium_lock = threading.RLock()
T = TypeVar("T")
@@ -29,20 +28,6 @@ def pdfium_guard() -> Iterator[None]:
yield
-def open_pdfium_document(
- opener: Callable[..., T],
- *args: Any,
- **kwargs: Any,
-) -> T:
- with pdfium_guard():
- return opener(*args, **kwargs)
-
-
-def get_pdfium_document_page_count(pdf_doc: Any) -> int:
- with pdfium_guard():
- return len(pdf_doc)
-
-
def close_pdfium_document(pdf_doc: Any) -> None:
if pdf_doc is None:
return
@@ -91,11 +76,7 @@ def get_loadable_pdfium_page_indices(
return [], []
normalized_start_page_id = max(0, start_page_id)
- normalized_end_page_id = (
- end_page_id
- if end_page_id is not None and end_page_id >= 0
- else total_page_count - 1
- )
+ normalized_end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else total_page_count - 1
if normalized_end_page_id > total_page_count - 1:
normalized_end_page_id = total_page_count - 1
if normalized_start_page_id > normalized_end_page_id:
@@ -134,11 +115,7 @@ def _normalize_rewrite_page_indices(
return sorted({int(page_index) for page_index in page_indices if 0 <= int(page_index) < total_page_count})
normalized_start_page_id = max(0, start_page_id)
- normalized_end_page_id = (
- end_page_id
- if end_page_id is not None and end_page_id >= 0
- else total_page_count - 1
- )
+ normalized_end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else total_page_count - 1
if normalized_end_page_id > total_page_count - 1:
normalized_end_page_id = total_page_count - 1
if normalized_start_page_id > normalized_end_page_id:
@@ -251,15 +228,11 @@ def safe_rewrite_pdf_bytes_with_pdfium_result(
)
logger.warning("PDFium rewrite returned empty bytes, trying to skip broken pages.")
except Exception as fallback_error:
- logger.warning(
- f"Error in converting PDF bytes with pdfium: {fallback_error}, trying to skip broken pages."
- )
+ logger.warning(f"Error in converting PDF bytes with pdfium: {fallback_error}, trying to skip broken pages.")
try:
if page_indices is not None:
- requested_page_indices = sorted(
- {int(page_index) for page_index in page_indices if int(page_index) >= 0}
- )
+ requested_page_indices = sorted({int(page_index) for page_index in page_indices if int(page_index) >= 0})
if not requested_page_indices:
logger.warning("PDFium safe rewrite received no valid requested pages, using original PDF bytes.")
return PdfiumRewriteResult(pdf_bytes=src_pdf_bytes, retained_page_indices=None, used_original=True)
@@ -278,15 +251,9 @@ def safe_rewrite_pdf_bytes_with_pdfium_result(
if requested_page_indices is not None:
requested_page_index_set = set(requested_page_indices)
loadable_page_indices = [
- page_index
- for page_index in loadable_page_indices
- if page_index in requested_page_index_set
- ]
- broken_page_indices = [
- page_index
- for page_index in broken_page_indices
- if page_index in requested_page_index_set
+ page_index for page_index in loadable_page_indices if page_index in requested_page_index_set
]
+ broken_page_indices = [page_index for page_index in broken_page_indices if page_index in requested_page_index_set]
if broken_page_indices:
skipped_pages = [page_index + 1 for page_index in broken_page_indices]