Skip to content

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

chore: update imports and add PDFDocument utility

jinzhenj15dc36a3efc2
diff --git a/mineru/cli/visualization.py b/mineru/cli/visualization.py
index cbb3ac8f..6625ef98 100644
--- a/mineru/cli/visualization.py
+++ b/mineru/cli/visualization.py
@@ -3,7 +3,7 @@ import json
from dataclasses import dataclass
from pathlib import Path
-from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
+from mineru.utils.pdf_document import PDFDocument
VISUALIZATION_FINISHED = "finished"
@@ -68,11 +68,12 @@ def run_visualization_job(job: VisualizationJob) -> VisualizationResult:
try:
pdf_bytes = origin_pdf_path.read_bytes()
+ doc = PDFDocument(pdf_bytes)
generated_files = [f"{job.document_stem}_layout.pdf"]
- draw_layout_bbox(pdf_info, pdf_bytes, str(job.parse_dir), generated_files[0])
+ doc.draw_layout_bbox(pdf_info, str(job.parse_dir / generated_files[0]))
if job.draw_span:
generated_files.append(f"{job.document_stem}_span.pdf")
- draw_span_bbox(pdf_info, pdf_bytes, str(job.parse_dir), generated_files[1])
+ doc.draw_span_bbox(pdf_info, str(job.parse_dir / generated_files[1]))
except Exception as exc:
return VisualizationResult(
document_stem=job.document_stem,
diff --git a/mineru/client.py b/mineru/client.py
deleted file mode 100644
index c901508c..00000000
--- a/mineru/client.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# Product SDK: communicates with the local mineru server over UDS.
-# See NEXT-SDK.md §6 for the interface specification.
diff --git a/mineru/data/io/http.py b/mineru/data/io/http.py
index 15340f1b..328cb2ac 100644
--- a/mineru/data/io/http.py
+++ b/mineru/data/io/http.py
@@ -2,13 +2,12 @@
import io
-import requests
+import httpx
from .base import IOReader, IOWriter
class HttpReader(IOReader):
-
def read(self, url: str) -> bytes:
"""Read the file.
@@ -18,7 +17,7 @@ class HttpReader(IOReader):
Returns:
bytes: the content of the file
"""
- return requests.get(url).content
+ return httpx.get(url).content
def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
"""Not Implemented."""
@@ -33,6 +32,6 @@ class HttpWriter(IOWriter):
path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
data (bytes): the data want to write
"""
- files = {'file': io.BytesIO(data)}
- response = requests.post(url, files=files)
+ files = {"file": io.BytesIO(data)}
+ response = httpx.post(url, files=files)
assert 300 > response.status_code and response.status_code > 199
diff --git a/mineru/data/io/s3.py b/mineru/data/io/s3.py
index 189787e4..58d82759 100644
--- a/mineru/data/io/s3.py
+++ b/mineru/data/io/s3.py
@@ -22,7 +22,7 @@ class S3Reader(IOReader):
ak: str,
sk: str,
endpoint_url: str,
- addressing_style: str = 'auto',
+ addressing_style: str = "auto",
):
"""s3 reader client.
@@ -34,18 +34,20 @@ class S3Reader(IOReader):
addressing_style (str, optional): Defaults to 'auto'. Other valid options here are 'path' and 'virtual'
refer to https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
"""
+
boto3, Config = _load_s3_client_dependencies()
+
self._bucket = bucket
self._ak = ak
self._sk = sk
self._s3_client = boto3.client(
- service_name='s3',
+ service_name="s3",
aws_access_key_id=ak,
aws_secret_access_key=sk,
endpoint_url=endpoint_url,
config=Config(
- s3={'addressing_style': addressing_style},
- retries={'max_attempts': 5, 'mode': 'standard'},
+ s3={"addressing_style": addressing_style},
+ retries={"max_attempts": 5, "mode": "standard"},
),
)
@@ -72,15 +74,11 @@ class S3Reader(IOReader):
bytes: the content of file
"""
if limit > -1:
- range_header = f'bytes={offset}-{offset+limit-1}'
- res = self._s3_client.get_object(
- Bucket=self._bucket, Key=key, Range=range_header
- )
+ range_header = f"bytes={offset}-{offset + limit - 1}"
+ res = self._s3_client.get_object(Bucket=self._bucket, Key=key, Range=range_header)
else:
- res = self._s3_client.get_object(
- Bucket=self._bucket, Key=key, Range=f'bytes={offset}-'
- )
- return res['Body'].read()
+ res = self._s3_client.get_object(Bucket=self._bucket, Key=key, Range=f"bytes={offset}-")
+ return res["Body"].read()
class S3Writer(IOWriter):
@@ -90,7 +88,7 @@ class S3Writer(IOWriter):
ak: str,
sk: str,
endpoint_url: str,
- addressing_style: str = 'auto',
+ addressing_style: str = "auto",
):
"""s3 reader client.
@@ -102,18 +100,20 @@ class S3Writer(IOWriter):
addressing_style (str, optional): Defaults to 'auto'. Other valid options here are 'path' and 'virtual'
refer to https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
"""
+
boto3, Config = _load_s3_client_dependencies()
+
self._bucket = bucket
self._ak = ak
self._sk = sk
self._s3_client = boto3.client(
- service_name='s3',
+ service_name="s3",
aws_access_key_id=ak,
aws_secret_access_key=sk,
endpoint_url=endpoint_url,
config=Config(
- s3={'addressing_style': addressing_style},
- retries={'max_attempts': 5, 'mode': 'standard'},
+ s3={"addressing_style": addressing_style},
+ retries={"max_attempts": 5, "mode": "standard"},
),
)
diff --git a/mineru/data/utils/schemas.py b/mineru/data/utils/schemas.py
index 00634735..0802892c 100644
--- a/mineru/data/utils/schemas.py
+++ b/mineru/data/utils/schemas.py
@@ -11,10 +11,3 @@ class S3Config(BaseModel):
secret_key: str = Field(description='s3 secret key', min_length=1)
endpoint_url: str = Field(description='s3 endpoint url', min_length=1)
addressing_style: str = Field(description='s3 addressing style', default='auto', min_length=1)
-
-
-class PageInfo(BaseModel):
- """The width and height of page
- """
- w: float = Field(description='the width of page')
- h: float = Field(description='the height of page')
diff --git a/mineru/types.py b/mineru/types.py
deleted file mode 100644
index 5df7affa..00000000
--- a/mineru/types.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# Shared Pydantic models for request/response contracts
-# between client and server.
diff --git a/mineru/utils/draw_bbox.py b/mineru/utils/draw_bbox.py
index 3131ccec..b5063706 100644
--- a/mineru/utils/draw_bbox.py
+++ b/mineru/utils/draw_bbox.py
@@ -422,5 +422,6 @@ if __name__ == "__main__":
with open(json_path, "r", encoding="utf-8") as f:
pdf_ann = json.load(f)
pdf_info = pdf_ann["pdf_info"]
- # 调用可视化函数,输出到examples目录
- draw_layout_bbox(pdf_info, pdf_bytes, "examples", "output_with_layout.pdf")
+ from mineru.utils.pdf_document import PDFDocument
+ doc = PDFDocument(pdf_bytes)
+ doc.draw_layout_bbox(pdf_info, "examples/output_with_layout.pdf")
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
new file mode 100644
index 00000000..7fd4c5f2
--- /dev/null
+++ b/mineru/utils/pdf_document.py
@@ -0,0 +1,210 @@
+# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING
+
+from PIL import Image
+
+from .pdfium_guard import close_pdfium_document, get_pdfium_document_page_count, open_pdfium_document, pdfium_guard
+
+if TYPE_CHECKING:
+ from mineru.parser.types import PageInfo
+
+
+class PDFDocument:
+ """A PDF file loaded in memory, with lazy pypdfium2 access.
+
+ All pypdfium2 operations are serialised under a module-level lock for
+ thread safety. Call ``close()`` when done, or use as a context manager.
+ """
+
+ def __init__(self, pdf_bytes: bytes) -> None:
+ self._pdf_bytes = pdf_bytes
+ self._pdf_doc = None # type: object | None
+
+ # ------------------------------------------------------------------ #
+ # Factory
+ # ------------------------------------------------------------------ #
+
+ @staticmethod
+ def from_image(image_bytes: bytes) -> "PDFDocument":
+ from .pdf_image_tools import images_bytes_to_pdf_bytes
+
+ return PDFDocument(images_bytes_to_pdf_bytes(image_bytes))
+
+ # ------------------------------------------------------------------ #
+ # Lifecycle
+ # ------------------------------------------------------------------ #
+
+ def close(self) -> None:
+ if self._pdf_doc is not None:
+ close_pdfium_document(self._pdf_doc)
+ self._pdf_doc = None
+
+ def __enter__(self) -> "PDFDocument":
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ self.close()
+
+ def __del__(self) -> None:
+ self.close()
+
+ # ------------------------------------------------------------------ #
+ # Properties
+ # ------------------------------------------------------------------ #
+
+ @property
+ def page_count(self) -> int:
+ return get_pdfium_document_page_count(self._ensure_open())
+
+ @property
+ def bytes(self) -> bytes:
+ return self._pdf_bytes
+
+ # ------------------------------------------------------------------ #
+ # Metadata
+ # ------------------------------------------------------------------ #
+
+ def page_size(self, page_idx: int) -> tuple[float, float]:
+ page = self._get_page(page_idx)
+ with pdfium_guard():
+ rect = page.get_bbox()
+ return (abs(rect[2] - rect[0]), abs(rect[1] - rect[3]))
+
+ # ------------------------------------------------------------------ #
+ # Rendering
+ # ------------------------------------------------------------------ #
+
+ def render_page(self, page_idx: int, *, scale: int = 2) -> Image.Image:
+ page = self._get_page(page_idx)
+ with pdfium_guard():
+ bitmap = page.render(scale=scale)
+ try:
+ return bitmap.to_pil()
+ finally:
+ bitmap.close()
+
+ def render_pages(
+ self, start: int = 0, end: int | None = None, *, scale: int = 2
+ ) -> list[Image.Image]:
+ end = end if end is not None else self.page_count - 1
+ return [self.render_page(i, scale=scale) for i in range(start, end + 1)]
+
+ async def render_page_async(self, page_idx: int, *, scale: int = 2) -> Image.Image:
+ import asyncio
+
+ return await asyncio.to_thread(self.render_page, page_idx, scale=scale)
+
+ async def render_pages_async(
+ self, start: int = 0, end: int | None = None, *, scale: int = 2
+ ) -> list[Image.Image]:
+ import asyncio
+
+ end = end if end is not None else self.page_count - 1
+ tasks = [self.render_page_async(i, scale=scale) for i in range(start, end + 1)]
+ return await asyncio.gather(*tasks)
+
+ def crop_image(
+ self,
+ bbox: tuple[float, float, float, float],
+ page_idx: int,
+ *,
+ scale: int = 2,
+ ) -> bytes:
+ from .pdf_image_tools import get_crop_img, image_to_bytes
+
+ pil_img = self.render_page(page_idx, scale=scale)
+ crop = get_crop_img(bbox, pil_img, scale=scale)
+ return image_to_bytes(crop, image_format="JPEG")
+
+ # ------------------------------------------------------------------ #
+ # Text
+ # ------------------------------------------------------------------ #
+
+ def get_page_chars(self, page_idx: int) -> dict:
+ from .pdf_text_tool import get_page_chars as _get_page_chars
+
+ page = self._get_page(page_idx)
+ return _get_page_chars(page)
+
+ def get_page_lines(self, page_idx: int) -> list[dict]:
+ from .pdf_text_tool import get_lines_from_chars
+
+ chars_dict = self.get_page_chars(page_idx)
+ return get_lines_from_chars(chars_dict["chars"])
+
+ # ------------------------------------------------------------------ #
+ # Classification
+ # ------------------------------------------------------------------ #
+
+ def classify(self) -> str:
+ from .pdf_classify import classify as _classify
+
+ return _classify(self._pdf_bytes)
+
+ def get_text_quality(self) -> dict:
+ from .pdf_classify import get_text_quality_signal_pdfium
+
+ doc = self._ensure_open()
+ page_indices = list(range(self.page_count))
+ return get_text_quality_signal_pdfium(doc, page_indices)
+
+ # ------------------------------------------------------------------ #
+ # Page extraction
+ # ------------------------------------------------------------------ #
+
+ def extract_page_range(self, start: int, end: int) -> "PDFDocument":
+ from .pdfium_guard import rewrite_pdf_bytes_with_pdfium
+
+ new_bytes = rewrite_pdf_bytes_with_pdfium(
+ self._pdf_bytes,
+ start_page_id=start,
+ end_page_id=end,
+ )
+ return PDFDocument(new_bytes)
+
+ def sample_pages(self, max_pages: int = 3) -> "PDFDocument":
+ from .pdf_classify import extract_pages as _extract_pages
+
+ new_bytes = _extract_pages(self._pdf_bytes)
+ if max_pages > 0 and new_bytes:
+ new_doc = PDFDocument(new_bytes)
+ count = new_doc.page_count
+ if count > max_pages:
+ return new_doc.extract_page_range(0, max_pages - 1)
+ return new_doc
+ return PDFDocument(b"")
+
+ # ------------------------------------------------------------------ #
+ # Visualization
+ # ------------------------------------------------------------------ #
+
+ def draw_layout_bbox(self, pages: list[PageInfo], output_path: str) -> None:
+ from .draw_bbox import draw_layout_bbox
+
+ out_dir = os.path.dirname(output_path) or "."
+ filename = os.path.basename(output_path)
+ draw_layout_bbox(pages, self._pdf_bytes, out_dir, filename)
+
+ def draw_span_bbox(self, pages: list[PageInfo], output_path: str) -> None:
+ from .draw_bbox import draw_span_bbox
+
+ out_dir = os.path.dirname(output_path) or "."
+ filename = os.path.basename(output_path)
+ draw_span_bbox(pages, self._pdf_bytes, out_dir, filename)
+
+ # ------------------------------------------------------------------ #
+ # Internal
+ # ------------------------------------------------------------------ #
+
+ def _ensure_open(self):
+ if self._pdf_doc is None:
+ import pypdfium2 as pdfium
+
+ self._pdf_doc = open_pdfium_document(pdfium.PdfDocument, self._pdf_bytes)
+ return self._pdf_doc
+
+ def _get_page(self, page_idx: int):
+ return self._ensure_open()[page_idx]