Skip to content

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

feat: enhance document processing by improving file suffix handling and adding progress indicators

myhloli4aab895c8a26
diff --git a/mineru/cli/client.py b/mineru/cli/client.py
index 709aab59..fe315170 100644
--- a/mineru/cli/client.py
+++ b/mineru/cli/client.py
@@ -5,6 +5,7 @@ import sys
import click
from pathlib import Path
from loguru import logger
+from tqdm import tqdm
os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
@@ -183,14 +184,14 @@ def main(
os.makedirs(output_dir, exist_ok=True)
- def parse_doc(path_list: list[Path]):
+ def parse_doc(path_list: list[tuple[Path, str | None]]):
try:
file_name_list = []
pdf_bytes_list = []
lang_list = []
- for path in path_list:
+ for path, known_suffix in tqdm(path_list, total=len(path_list), desc='Reading documents'):
file_name = str(Path(path).stem)
- pdf_bytes = read_fn(path)
+ pdf_bytes = read_fn(path, file_suffix=known_suffix)
file_name_list.append(file_name)
pdf_bytes_list.append(pdf_bytes)
lang_list.append(lang)
@@ -213,12 +214,14 @@ def main(
if os.path.isdir(input_path):
doc_path_list = []
- for doc_path in Path(input_path).glob('*'):
- if guess_suffix_by_path(doc_path) in pdf_suffixes + image_suffixes + office_suffixes:
- doc_path_list.append(doc_path)
+ doc_candidates = list(Path(input_path).glob('*'))
+ for doc_path in tqdm(doc_candidates, total=len(doc_candidates), desc='Collecting documents'):
+ file_suffix = guess_suffix_by_path(doc_path)
+ if file_suffix in pdf_suffixes + image_suffixes + office_suffixes:
+ doc_path_list.append((doc_path, file_suffix))
parse_doc(doc_path_list)
else:
- parse_doc([Path(input_path)])
+ parse_doc([(Path(input_path), None)])
if __name__ == '__main__':
main()
diff --git a/mineru/cli/common.py b/mineru/cli/common.py
index d20d943f..e4e02611 100644
--- a/mineru/cli/common.py
+++ b/mineru/cli/common.py
@@ -41,12 +41,13 @@ os.environ["TOKENIZERS_PARALLELISM"] = "false"
_pdf_rewrite_lock = threading.Lock()
-def read_fn(path):
+def read_fn(path, file_suffix: str | None = None):
if not isinstance(path, Path):
path = Path(path)
with open(str(path), "rb") as input_file:
file_bytes = input_file.read()
- file_suffix = guess_suffix_by_bytes(file_bytes, path)
+ if file_suffix is None:
+ file_suffix = guess_suffix_by_bytes(file_bytes, path)
if file_suffix in image_suffixes:
return images_bytes_to_pdf_bytes(file_bytes)
elif file_suffix in pdf_suffixes + office_suffixes:
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index 468bb6a6..4b702fee 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -8,8 +8,6 @@ import numpy as np
import pypdfium2 as pdfium
from loguru import logger
from PIL import Image, ImageOps
-from reportlab.lib.utils import ImageReader
-from reportlab.pdfgen import canvas
from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.utils.check_sys_env import is_windows_environment
@@ -333,35 +331,27 @@ def get_crop_np_img(bbox: tuple, input_img, scale=2):
def images_bytes_to_pdf_bytes(image_bytes):
+ # 内存缓冲区
pdf_buffer = BytesIO()
- with Image.open(BytesIO(image_bytes)) as source_image:
- image = ImageOps.exif_transpose(source_image)
- if image.mode != "RGB":
- image = image.convert("RGB")
- else:
- image = image.copy()
-
- # Preserve the original raster content when the CLI later renders the
- # wrapper PDF back at DEFAULT_PDF_IMAGE_DPI. PIL's PDF writer introduces
- # enough loss for layout detection to miss text blocks on some image inputs.
- page_width = image.width * 72.0 / DEFAULT_PDF_IMAGE_DPI
- page_height = image.height * 72.0 / DEFAULT_PDF_IMAGE_DPI
-
- pdf_canvas = canvas.Canvas(pdf_buffer, pagesize=(page_width, page_height))
- pdf_canvas.drawImage(
- ImageReader(image),
- 0,
- 0,
- width=page_width,
- height=page_height,
- preserveAspectRatio=False,
- mask="auto",
+ # 载入并转换所有图像为 RGB 模式
+ image = Image.open(BytesIO(image_bytes))
+ # 根据 EXIF 信息自动转正(处理手机拍摄的带 Orientation 标记的图片)
+ image = ImageOps.exif_transpose(image) or image
+ # 只在必要时转换
+ if image.mode != "RGB":
+ image = image.convert("RGB")
+
+ # 第一张图保存为 PDF,其余追加
+ image.save(
+ pdf_buffer,
+ format="PDF",
+ resolution=DEFAULT_PDF_IMAGE_DPI,
+ quality=95,
+ subsampling=0,
)
- pdf_canvas.showPage()
- pdf_canvas.save()
+ # 获取 PDF bytes 并重置指针(可选)
pdf_bytes = pdf_buffer.getvalue()
pdf_buffer.close()
- image.close()
- return pdf_bytes
+ return pdf_bytes
\ No newline at end of file