Skip to content

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

feat: remove deprecated functions and clean up unused code in various modules

myhloli895aa9815f71
diff --git a/mineru/utils/backend_options.py b/mineru/utils/backend_options.py
index 7381c392..fff74cdc 100644
--- a/mineru/utils/backend_options.py
+++ b/mineru/utils/backend_options.py
@@ -32,7 +32,6 @@ HYBRID_EFFORT_BY_TIER: Final[dict[str, str]] = {
"standard": LAYOUT_HYBRID_EFFORT,
"advanced": MAX_HYBRID_EFFORT,
}
-TIER_BY_HYBRID_EFFORT: Final[dict[str, str]] = {effort: tier for tier, effort in HYBRID_EFFORT_BY_TIER.items()}
BACKEND_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(PUBLIC_BACKEND_CHOICES)}
HYBRID_EFFORT_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(HYBRID_EFFORT_CHOICES)}
@@ -94,12 +93,6 @@ def effort_for_tier(tier: str | None) -> str:
raise ValueError(f"Unsupported tier '{tier}'. Supported hybrid tiers: {supported_tiers}")
-def tier_for_effort(effort: str | None) -> str:
- """将 Hybrid effort 映射回公开 tier,避免把内部 effort 当作 tier 校验。"""
- normalized = validate_effort(effort)
- return TIER_BY_HYBRID_EFFORT[normalized]
-
-
def resolve_backend_and_effort(backend: str | None, effort: str | None = None) -> tuple[str, str]:
"""同时解析 backend 与 effort,旧 pipeline/VLM backend 分别统一转为 Hybrid medium/xhigh。"""
raw_backend = (backend or "").strip()
diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.py
index 531942b3..46f6de9f 100644
--- a/mineru/utils/config_reader.py
+++ b/mineru/utils/config_reader.py
@@ -1,33 +1,8 @@
# Copyright (c) Opendatalab. All rights reserved.
-import json
import os
-from typing import Any
from loguru import logger
-# 定义配置文件名常量,保留给旧日志文案使用;实际读取路径通过函数动态解析环境变量。
-CONFIG_FILE_NAME = os.getenv("MINERU_TOOLS_CONFIG_JSON", "mineru.json")
-
-
-def get_tools_config_file_path() -> str:
- """获取 MinerU 工具配置文件路径,支持环境变量指定绝对或相对路径。"""
- config_file_name = os.getenv("MINERU_TOOLS_CONFIG_JSON", "mineru.json")
- if os.path.isabs(config_file_name):
- return config_file_name
- return os.path.join(os.path.expanduser("~"), config_file_name)
-
-
-def read_config() -> dict[str, Any] | None:
- config_file = get_tools_config_file_path()
-
- if not os.path.exists(config_file):
- # logger.warning(f'{config_file} not found, using default configuration')
- return None
- else:
- with open(config_file, "r", encoding="utf-8") as f:
- config = json.load(f)
- return config
-
def get_device() -> str:
device_mode = os.getenv("MINERU_DEVICE_MODE", None)
@@ -94,12 +69,6 @@ def get_model_stack() -> str:
return "light" if device == "cpu" else "full"
-def get_ocr_det_mask_inline_formula_enable(enable: bool) -> bool:
- enable_env = os.getenv("MINERU_OCR_DET_MASK_INLINE_FORMULA_ENABLE")
- enable = enable if enable_env is None else enable_env.lower() == "true"
- return enable
-
-
def get_processing_window_size(default: int = 64) -> int:
value = os.getenv("MINERU_PROCESSING_WINDOW_SIZE")
if value is None:
@@ -125,25 +94,3 @@ def get_max_concurrent_requests(default: int = 3) -> int:
if max_concurrent_requests <= 0:
raise ValueError(f"Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: {value}. Expected a positive integer.")
return max_concurrent_requests
-
-
-def get_latex_delimiter_config() -> dict[str, Any] | None:
- config = read_config()
- if config is None:
- return None
- latex_delimiter_config = config.get("latex-delimiter-config", None)
- if latex_delimiter_config is None:
- # logger.warning(f"'latex-delimiter-config' not found in {CONFIG_FILE_NAME}, use 'None' as default")
- return None
- else:
- return latex_delimiter_config
-
-
-def get_local_models_dir() -> dict[str, str] | None:
- config = read_config()
- if config is None:
- return None
- models_dir = config.get("models-dir")
- if models_dir is None:
- logger.warning(f"'models-dir' not found in {CONFIG_FILE_NAME}, use None as default")
- return models_dir
diff --git a/mineru/utils/hash_utils.py b/mineru/utils/hash_utils.py
index 1b4b953e..2393e842 100644
--- a/mineru/utils/hash_utils.py
+++ b/mineru/utils/hash_utils.py
@@ -1,20 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
import hashlib
-import json
-
-
-def bytes_md5(file_bytes: bytes) -> str:
- hasher = hashlib.md5()
- hasher.update(file_bytes)
- return hasher.hexdigest().upper()
-
-
-def str_md5(input_string: str) -> str:
- hasher = hashlib.md5()
- # 在Python3中,需要将字符串转化为字节对象才能被哈希函数处理
- input_bytes = input_string.encode("utf-8")
- hasher.update(input_bytes)
- return hasher.hexdigest()
def str_sha256(input_string: str) -> str:
@@ -23,8 +8,3 @@ def str_sha256(input_string: str) -> str:
input_bytes = input_string.encode("utf-8")
hasher.update(input_bytes)
return hasher.hexdigest()
-
-
-def dict_md5(d: dict[str, object]) -> str:
- json_str = json.dumps(d, sort_keys=True, ensure_ascii=False)
- return hashlib.md5(json_str.encode("utf-8")).hexdigest()
diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.py
index 0df6827d..7dc738ae 100644
--- a/mineru/utils/image_payload.py
+++ b/mineru/utils/image_payload.py
@@ -10,7 +10,6 @@ import xml.etree.ElementTree as ElementTree
from .hash_utils import str_sha256
INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;\"']+);base64,([^\"']+)", re.DOTALL)
-INLINE_IMAGE_SRC_RE = re.compile(r"src=(?P<quote>[\"'])(?P re.DOTALL)
def normalize_image_extension(fmt: str) -> str:
@@ -19,25 +18,6 @@ def normalize_image_extension(fmt: str) -> str:
return "jpg" if normalized in {"jpeg", "jpg"} else normalized
-def image_bytes_to_data_uri(img_bytes: bytes, image_format: str = "JPEG") -> str:
- """把图片字节编码成 data URI,作为 middle_json 中的临时图片载荷。"""
- fmt = image_format.lower()
- mime_fmt = "jpeg" if fmt in {"jpg", "jpeg"} else fmt
- payload = base64.b64encode(img_bytes).decode("ascii")
- return f"data:image/{mime_fmt};base64,{payload}"
-
-
-def parse_image_data_uri(data_uri: str) -> tuple[bytes, str] | None:
- """解析 data URI,返回图片字节和规范化扩展名;非法输入返回 None。"""
- match = re.fullmatch(r"data:image/([^;]+);base64,(.+)", data_uri, re.DOTALL)
- if match is None:
- return None
- try:
- return base64.b64decode(match.group(2)), normalize_image_extension(match.group(1))
- except Exception:
- return None
-
-
def parse_image_data_uri_strict(data_uri: str) -> tuple[bytes, str]:
"""严格解析图片 data URI,并同时校验 MIME 与文件签名是否一致。"""
match = re.fullmatch(r"data:image/([^;]+);base64,([A-Za-z0-9+/]*={0,2})", data_uri)
@@ -82,15 +62,6 @@ def parse_image_data_uri_strict(data_uri: str) -> tuple[bytes, str]:
return payload, extension
-def image_path_from_data_uri(data_uri: str) -> str | None:
- """根据 data URI 内容生成稳定图片路径,供没有显式 image_path 的 span 使用。"""
- parsed = parse_image_data_uri(data_uri)
- if parsed is None:
- return None
- _, ext = parsed
- return f"{str_sha256(data_uri)}.{ext}"
-
-
def image_path_from_key(path_key: str, image_format: str = "JPEG") -> str:
"""复用旧裁图路径哈希规则,根据逻辑路径生成稳定图片文件名。"""
ext = normalize_image_extension(image_format)
@@ -100,23 +71,8 @@ def image_path_from_key(path_key: str, image_format: str = "JPEG") -> str:
class ImagePayloadCache:
"""保存运行时图片载荷,public middle_json 只通过 image_path 引用图片。"""
- def __init__(
- self,
- images: dict[str, bytes] | None = None,
- data_uris: dict[str, str] | None = None,
- ) -> None:
+ def __init__(self, images: dict[str, bytes] | None = None) -> None:
self._images: dict[str, bytes] = dict(images or {})
- self._data_uris: dict[str, str] = dict(data_uris or {})
-
- def register_data_uri(self, data_uri: str, image_path: str | None = None) -> str:
- """登记 data URI 图片,返回稳定的相对 image_path;非法载荷返回空串。"""
- parsed = parse_image_data_uri(data_uri)
- img_path = image_path or image_path_from_data_uri(data_uri)
- if parsed is None or not img_path:
- return ""
- self._images[img_path] = parsed[0]
- self._data_uris[img_path] = data_uri
- return img_path
def register_bytes(
self,
@@ -136,28 +92,8 @@ class ImagePayloadCache:
payload_key = base64.b64encode(img_bytes).decode("ascii")
img_path = f"{str_sha256(payload_key)}.{ext}"
self._images[img_path] = img_bytes
- self._data_uris[img_path] = image_bytes_to_data_uri(img_bytes, image_format)
return img_path
- def replace_html_data_uri_sources(self, markup: str) -> str:
- """把 HTML 内联 data URI 图片替换为 image_path,并同步写入顶层图片缓存。"""
- if not markup or "data:image/" not in markup:
- return markup
-
- def _replace_src(match: re.Match[str]) -> str:
- img_path = self.register_data_uri(match.group("data_uri"))
- if not img_path:
- return match.group(0)
- return f'src={match.group("quote")}{img_path}{match.group("quote")}'
-
- replaced = INLINE_IMAGE_SRC_RE.sub(_replace_src, markup)
-
- def _replace_bare_data_uri(match: re.Match[str]) -> str:
- img_path = self.register_data_uri(match.group(0))
- return img_path or match.group(0)
-
- return INLINE_IMAGE_DATA_URI_RE.sub(_replace_bare_data_uri, replaced)
-
def update(self, images: dict[str, bytes]) -> None:
"""合并外部 sidecar 图片字节,供 API client 绑定远端输出。"""
for image_path, image_bytes in images.items():
@@ -167,10 +103,6 @@ class ImagePayloadCache:
"""返回 image_path 到图片字节的副本,避免调用方改写内部缓存。"""
return dict(self._images)
- def data_uris(self) -> dict[str, str]:
- """返回 image_path 到 data URI 的副本,便于调试运行时图片来源。"""
- return dict(self._data_uris)
-
def validate_image_sidecar_path(image_path: str) -> str:
"""校验图片 sidecar 路径只能是安全的相对子路径,并返回规范化 POSIX 路径。"""
@@ -190,25 +122,3 @@ def validate_image_sidecar_path(image_path: str) -> str:
):
raise ValueError(f"Unsafe image sidecar path: {image_path}")
return posix_path.as_posix()
-
-
-def collect_image_data_uri_bytes(markup: str, images: dict[str, bytes]) -> None:
- """只收集文本或 HTML 中的 data URI 图片字节,不修改原始内容。"""
- if not markup or "data:image/" not in markup:
- return
- for match in INLINE_IMAGE_DATA_URI_RE.finditer(markup):
- data_uri = match.group(0)
- parsed = parse_image_data_uri(data_uri)
- img_path = image_path_from_data_uri(data_uri)
- if parsed is None or img_path is None:
- continue
- images[img_path] = parsed[0]
-
-
-def replace_inline_data_uri_sources(markup: str, images: dict[str, bytes]) -> str:
- """把 HTML src 中的 data URI 图片替换为本地路径,并同步收集图片字节。"""
- cache = ImagePayloadCache(images)
- replaced = cache.replace_html_data_uri_sources(markup)
- images.clear()
- images.update(cache.images())
- return replaced
diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.py
index 90ec5cc6..4373c290 100644
--- a/mineru/utils/model_utils.py
+++ b/mineru/utils/model_utils.py
@@ -2,7 +2,6 @@
import gc
import math
import os
-import time
from typing import Any
import numpy as np
@@ -18,27 +17,6 @@ try:
except ImportError:
_TORCH_AVAILABLE = False
-TEXT_REGION_LABELS = {
- "abstract",
- "algorithm",
- "aside_text",
- "content",
- "doc_title",
- "figure_title",
- "footer",
- "footer_image",
- "footnote",
- "formula_number",
- "header",
- "header_image",
- "number",
- "paragraph_title",
- "reference_content",
- "text",
- "vertical_text",
- "vision_footnote",
-}
-
def _get_bbox(item: dict[str, Any]) -> BBox:
bbox = item["bbox"]
@@ -52,11 +30,6 @@ def _get_int_bbox(item: dict[str, Any]) -> IntBBox:
return math.floor(xmin), math.floor(ymin), math.ceil(xmax), math.ceil(ymax)
-def _bbox_area(bbox: BBox | IntBBox) -> float:
- xmin, ymin, xmax, ymax = bbox
- return abs((xmax - xmin) * (ymax - ymin))
-
-
def crop_img(
input_res: dict[str, Any],
input_img: Image.Image | np.ndarray,
@@ -92,107 +65,6 @@ def crop_img(
return return_image, return_list
-def get_bbox_and_area(block_with_poly: dict[str, Any]) -> tuple[BBox, float]:
- """Extract coordinates and area from a table."""
- xmin, ymin, xmax, ymax = _get_bbox(block_with_poly)
- area = (xmax - xmin) * (ymax - ymin)
- return (xmin, ymin, xmax, ymax), area
-
-
-def calculate_intersection(box1: BBox, box2: BBox) -> BBox | None:
- """Calculate intersection coordinates between two boxes."""
- intersection_xmin = max(box1[0], box2[0])
- intersection_ymin = max(box1[1], box2[1])
- intersection_xmax = min(box1[2], box2[2])
- intersection_ymax = min(box1[3], box2[3])
-
- # Check if intersection is valid
- if intersection_xmax <= intersection_xmin or intersection_ymax <= intersection_ymin:
- return None
-
- return intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax
-
-
-def is_inside(small_box: BBox, big_box: BBox, small_area: float, overlap_threshold: float = 0.8) -> bool:
- """Check if small_box is inside big_box by at least overlap_threshold."""
- intersection = calculate_intersection(small_box, big_box)
- if not intersection:
- return False
-
- intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection
- intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)
- # Check if overlap exceeds threshold
- return intersection_area >= overlap_threshold * small_area
-
-
-def remove_nested_ocr_text_blocks(
- ocr_res_list: list[dict[str, Any]],
- layout_res: list[dict[str, Any]],
- overlap_threshold: float = 0.8,
- min_area_ratio: float = 1.01,
-) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
- """Remove OCR candidate text blocks that are contained by any larger layout block."""
- if not ocr_res_list or len(layout_res) < 2:
- return ocr_res_list, []
-
- layout_info = [(block, get_bbox_and_area(block)) for block in layout_res]
- blocks_to_remove = []
-
- for text_block in ocr_res_list:
- text_box, text_area = get_bbox_and_area(text_block)
- for parent_block, (parent_box, parent_area) in layout_info:
- if parent_block is text_block:
- continue
- if parent_area <= text_area * min_area_ratio:
- continue
- if is_inside(text_box, parent_box, text_area, overlap_threshold):
- blocks_to_remove.append(text_block)
- break
-
- remove_ids = {id(block) for block in blocks_to_remove}
- filtered_ocr_res_list = [block for block in ocr_res_list if id(block) not in remove_ids]
- return filtered_ocr_res_list, blocks_to_remove
-
-
-def get_res_list_from_layout_res(
- layout_res: list[dict[str, Any]], overlap_threshold: float = 0.8
-) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
- """Extract OCR, table and other regions from layout results."""
- ocr_res_list = []
- text_res_list = []
- table_res_list = []
- single_page_mfdetrec_res = []
-
- # Categorize regions
- for i, res in enumerate(layout_res):
- label = res.get("label")
-
- if label in ["display_formula", "inline_formula"]:
- xmin, ymin, xmax, ymax = _get_bbox(res)
- single_page_mfdetrec_res.append(
- {
- "bbox": [xmin, ymin, xmax, ymax],
- }
- )
- elif label == "table":
- table_res_list.append(res)
- elif label in TEXT_REGION_LABELS:
- text_res_list.append(res)
-
- ocr_res_list.extend(text_res_list)
-
- ocr_res_list, nested_text_need_remove = remove_nested_ocr_text_blocks(
- ocr_res_list,
- layout_res,
- overlap_threshold=overlap_threshold,
- )
- nested_remove_ids = {id(res) for res in nested_text_need_remove}
- if nested_remove_ids:
- layout_res[:] = [res for res in layout_res if id(res) not in nested_remove_ids]
-
- return ocr_res_list, table_res_list, single_page_mfdetrec_res
-
-
def clean_memory(device: str = "cuda") -> None:
if not _TORCH_AVAILABLE:
gc.collect()
@@ -221,15 +93,6 @@ def clean_memory(device: str = "cuda") -> None:
gc.collect()
-def clean_vram(device: str, vram_threshold: int = 8) -> None:
- total_memory = get_vram(device)
- if total_memory and total_memory <= vram_threshold:
- gc_start = time.time()
- clean_memory(device)
- gc_time = round(time.time() - gc_start, 2)
- logger.debug(f"gc time: {gc_time}")
-
-
def get_vram(device: str) -> int:
env_vram = os.getenv("MINERU_VIRTUAL_VRAM_SIZE")
diff --git a/mineru/utils/page_index.py b/mineru/utils/page_index.py
deleted file mode 100644
index c25fe984..00000000
--- a/mineru/utils/page_index.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-
-def resolve_output_page_idx(physical_page_idx: int, page_index_map: list[int] | None = None) -> int:
- """根据物理页序解析输出页号,确保轻量解析路径不依赖 pipeline 工具模块。"""
- if page_index_map is None:
- return physical_page_idx
- if physical_page_idx < 0 or physical_page_idx >= len(page_index_map):
- raise ValueError(
- f"page_index_map does not cover physical page index {physical_page_idx}: "
- f"map length={len(page_index_map)}"
- )
- return page_index_map[physical_page_idx]
diff --git a/mineru/utils/pdf_classify.py b/mineru/utils/pdf_classify.py
index 270140de..6bd918ae 100644
--- a/mineru/utils/pdf_classify.py
+++ b/mineru/utils/pdf_classify.py
@@ -372,11 +372,6 @@ 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: 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)
-
-
def _get_text_quality_signal_from_samples(text_samples: list[dict[str, Any]]) -> dict[str, Any]:
"""基于已缓存的抽样页字符计数统计异常字符质量信号。"""
total_chars = 0
@@ -408,11 +403,6 @@ def _get_text_quality_signal_from_samples(text_samples: list[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)
-
-
def _get_unicode_map_error_signal_from_samples(text_samples: list[dict[str, Any]]) -> dict[str, Any]:
"""统计 PDFium 字符级 Unicode 映射失败比例,用于识别无法可靠抽取的乱码文本。"""
total_chars = 0
@@ -698,12 +688,6 @@ def _get_u72xx_text_signal_from_samples(text_samples: list[dict[str, Any]]) -> d
}
-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)
-
-
def _get_sample_cleaned_text(text_sample: Any) -> str:
"""兼容 dict 和测试替身对象,读取抽样页的 cleaned_text 字段。"""
if isinstance(text_sample, dict):
@@ -1122,19 +1106,6 @@ def _get_font_resource_signals_pypdf(
}
-def get_cid_font_signal_pypdf(pdf_bytes: bytes, page_indices: list[int]) -> dict[str, Any]:
- """兼容旧接口:返回抽样页无 ToUnicode 的 Identity CID 字体资源。"""
- return _get_font_resource_signals_pypdf(
- pdf_bytes,
- page_indices,
- )["cid_without_to_unicode"]
-
-
-def detect_cid_font_signal_pypdf(pdf_bytes: bytes, page_indices: list[int]) -> bool:
- """兼容旧接口:只返回是否存在无 ToUnicode 的 Identity CID 字体资源。"""
- return get_cid_font_signal_pypdf(pdf_bytes, page_indices)["triggered"]
-
-
def _resolve_pdf_object(obj: Any) -> Any:
if hasattr(obj, "get_object"):
return obj.get_object()
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 2662b513..409007ac 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -1,7 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
-import asyncio
import ctypes
import hashlib
import logging
@@ -23,10 +22,10 @@ from pdftext.schema import Bbox, Char, Line
from PIL import Image, ImageOps
from ..types import BBox, PageInfo
-from .pdf_classify import classify, get_sample_page_indices
-from .pdf_image_tools import get_crop_img, load_images_from_pdf_bytes_range
+from .pdf_classify import classify
+from .pdf_image_tools import get_crop_img
from .pdf_reader import image_to_bytes
-from .pdfium_guard import _pdfium_lock, safe_rewrite_pdf_bytes_with_pdfium
+from .pdfium_guard import _pdfium_lock
logger = logging.getLogger(__name__)
@@ -354,29 +353,6 @@ class PDFDocument:
with self._open_page(page_idx) as page:
return _page_to_image(page, scale, self.render_max_edge)
- def render_pages(self, start: int = 0, end: int | None = None, *, scale: float | None = None) -> list[PDFPageImage]:
- if end is None:
- end = self.page_count - 1
- if scale is None:
- scale = self.render_scale
- if scale <= 0:
- raise ValueError("scale must be greater than 0")
- results = load_images_from_pdf_bytes_range(
- pdf_bytes=self.bytes,
- dpi=max(1, int(round(scale * POINTS_PER_INCH))),
- start_page_id=start,
- end_page_id=end,
- )
- return [PDFPageImage(pil_image=r["img_pil"], scale=r["scale"]) for r in results]
-
- async def render_page_async(self, page_idx: int, *, scale: float | None = None) -> PDFPageImage:
- 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: float | None = None
- ) -> list[PDFPageImage]:
- return await asyncio.to_thread(self.render_pages, start, end, scale=scale)
-
# TODO: move
def crop_image(self, bbox: BBox, page_idx: int, *, scale: float = 2) -> bytes:
image = self.render_page(page_idx, scale=scale)
@@ -426,16 +402,6 @@ 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 ""
-
# ------------------------------------------------------------------ #
# Drawing geometry
# ------------------------------------------------------------------ #
@@ -531,35 +497,6 @@ class PDFDocument:
pdf_class = classify(self._pdf_doc, self.bytes)
return cast(Literal["ocr", "txt"], pdf_class)
- # ------------------------------------------------------------------ #
- # Page extraction
- # ------------------------------------------------------------------ #
-
- # TODO: no caller
- def extract_page_range(self, start: int, end: int) -> "PDFDocument":
- new_bytes = safe_rewrite_pdf_bytes_with_pdfium(
- self._pdf_bytes,
- start_page_id=start,
- end_page_id=end,
- )
- return PDFDocument(new_bytes)
-
- # TODO: no caller
- def sample_pages(self, max_pages: int = 3) -> "PDFDocument":
- """按 PDF 分类抽样规则提取代表性页面,返回新的 PDFDocument。"""
- if max_pages <= 0:
- return PDFDocument(b"")
-
- page_indices = get_sample_page_indices(self.page_count, max_pages)
- if page_indices:
- new_bytes = safe_rewrite_pdf_bytes_with_pdfium(
- self._pdf_bytes,
- page_indices=page_indices,
- )
- if new_bytes:
- return PDFDocument(new_bytes)
- return PDFDocument(b"")
-
# ------------------------------------------------------------------ #
# Visualization
# ------------------------------------------------------------------ #
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index 372dc98d..ed571612 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -1,7 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
-import asyncio
import atexit
import multiprocessing
import os
@@ -447,27 +446,6 @@ def load_images_from_pdf_bytes_range(
)
-async def aio_load_images_from_pdf_bytes_range(
- pdf_bytes: bytes,
- dpi: int = DEFAULT_PDF_IMAGE_DPI,
- start_page_id: int = 0,
- end_page_id: int = 0,
- image_type: Literal["pil_img", "base64_img"] = ImageType.PIL,
- timeout: int | None = None,
- threads: int | None = None,
-) -> list[dict[str, Any]]:
- return await asyncio.to_thread(
- load_images_from_pdf_bytes_range,
- pdf_bytes,
- dpi=dpi,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- image_type=image_type,
- timeout=timeout,
- threads=threads,
- )
-
-
def _terminate_executor_processes(executor: ProcessPoolExecutor) -> None:
"""强制终止 ProcessPoolExecutor 中的所有子进程"""
# executor.shutdown() 后 _processes 会被置空,重复回收时直接视为无进程。
diff --git a/mineru/utils/pdfium_guard.py b/mineru/utils/pdfium_guard.py
index e5291927..fc35dea8 100644
--- a/mineru/utils/pdfium_guard.py
+++ b/mineru/utils/pdfium_guard.py
@@ -3,7 +3,7 @@ import threading
from contextlib import contextmanager
from dataclasses import dataclass, field
from io import BytesIO
-from typing import Any, Callable, Iterator, Sequence, TypeVar
+from typing import Any, Iterator, Sequence, TypeVar
from loguru import logger
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index f9c260ea..0447172f 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -1,4 +1,3 @@
-import base64
from dataclasses import fields
import json
@@ -12,38 +11,6 @@ from mineru.utils.image_payload import ImagePayloadCache
from mineru.version import __version__
-def _data_uri(payload: bytes, image_type: str = "png") -> str:
- return f"data:image/{image_type};base64,{base64.b64encode(payload).decode('ascii')}"
-
-
-def _table_page_with_cached_inline_image(img_bytes: bytes) -> tuple[PageInfo, ImagePayloadCache, str]:
- """构造已完成图片外置化的表格页,验证 ParseResult 只承载顶层图片缓存。"""
- image_cache = ImagePayloadCache()
- inline_image = _data_uri(img_bytes)
- html = image_cache.replace_html_data_uri_sources(
- f'<table><tr><td><img src="{inline_image}"/></td></tr></table>'
- )
- page = PageInfo(
- page_idx=0,
- blocks=[
- TableBlock(
- type=BlockType.TABLE,
- index=0,
- bbox=(0.0, 0.0, 0.1, 0.1),
- content=[
- TableBodyBlock(
- type=BlockType.TABLE_BODY,
- index=0,
- bbox=(0.0, 0.0, 0.1, 0.1),
- content=html,
- )
- ],
- )
- ],
- )
- return page, image_cache, inline_image
-
-
def test_parse_result_does_not_expose_backend_version_or_file_name() -> None:
field_names = {field.name for field in fields(ParseResult)}
@@ -155,9 +122,32 @@ def test_parse_result_from_json_restores_pages() -> None:
assert restored.middle_json.file_suffix == "pdf"
-def test_parse_result_export_pages_returns_defensive_copy_from_cache() -> None:
- img_bytes = b"defensive-table-image"
- page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
+def test_parse_result_export_pages_returns_defensive_copy() -> None:
+ """验证调用方修改导出页面副本时不会污染 ParseResult 内部状态。"""
+ image_cache = ImagePayloadCache()
+ image_path = image_cache.register_bytes(
+ b"defensive-table-image",
+ "png",
+ image_path="images/table.png",
+ )
+ page = PageInfo(
+ page_idx=0,
+ blocks=[
+ TableBlock(
+ type=BlockType.TABLE,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=[
+ TableBodyBlock(
+ type=BlockType.TABLE_BODY,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=f'<table><tr><td><img src="{image_path}"/></td></tr></table>',
+ )
+ ],
+ )
+ ],
+ )
result = ParseResult(
middle_json=MiddleJson(
pages=[page],
@@ -176,34 +166,6 @@ def test_parse_result_export_pages_returns_defensive_copy_from_cache() -> None:
second_content = second_export[0].blocks[0].content[0].content
exported_json = json.dumps(result.to_dict(), ensure_ascii=False)
- assert "mutated by caller" not in second_content
+ assert image_path in second_content
+ assert result.images() == {image_path: b"defensive-table-image"}
assert "mutated by caller" not in exported_json
- assert inline_image not in second_content
- assert inline_image not in exported_json
- assert next(iter(result.images())) in exported_json
-
-
-def test_parse_result_export_rewrites_inline_table_base64_images() -> None:
- img_bytes = b"table-image"
- page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
-
- result = ParseResult(
- middle_json=MiddleJson(
- pages=[page],
- is_full_document=True,
- file_suffix="pdf",
- effort="medium",
- parse_mode="txt",
- mineru_version=__version__,
- ),
- _image_cache=image_cache,
- )
- images = result.images()
- exported_page = result.export_pages()[0]
- exported_body = exported_page.blocks[0].content[0]
- exported_json = json.dumps(result.to_dict(), ensure_ascii=False)
-
- assert list(images.values()) == [img_bytes]
- assert inline_image not in exported_json
- assert 'src="' in exported_body.content
- assert next(iter(images)) in exported_json
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 87bbf74d..feeb37b3 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -160,7 +160,6 @@ def test_validate_effort_rejects_low_and_maps_legacy_backends() -> None:
HYBRID_EFFORT_CHOICES,
effort_for_tier,
resolve_backend_and_effort,
- tier_for_effort,
validate_effort,
)
@@ -168,9 +167,6 @@ def test_validate_effort_rejects_low_and_maps_legacy_backends() -> None:
assert effort_for_tier("basic") == "medium"
assert effort_for_tier("standard") == "high"
assert effort_for_tier("advanced") == "xhigh"
- assert tier_for_effort("medium") == "basic"
- assert tier_for_effort("high") == "standard"
- assert tier_for_effort("xhigh") == "advanced"
with pytest.raises(ValueError, match="Unsupported effort 'low'"):
validate_effort("low")
with pytest.raises(ValueError, match="Unsupported tier 'ultra'"):
diff --git a/tests/unittest/test_pdf_classify.py b/tests/unittest/test_pdf_classify.py
index c2e58298..5c34d6f0 100644
--- a/tests/unittest/test_pdf_classify.py
+++ b/tests/unittest/test_pdf_classify.py
@@ -175,19 +175,6 @@ def test_mixed_elements_uses_exact_cid_counts_and_classifies_as_txt() -> None:
assert pdf_doc.classify() == "txt"
-def test_public_cid_resource_signal_shape_remains_compatible() -> None:
- """验证兼容接口仍只暴露资源存在性与逐页字体名。"""
- pdf_bytes = MIXED_ELEMENTS_PDF.read_bytes()
- signal = pdf_classify.get_cid_font_signal_pypdf(
- pdf_bytes,
- [0, 1, 2, 3],
- )
-
- assert set(signal) == {"triggered", "page_fonts"}
- assert signal["triggered"] is True
- assert "TimesNewRoman" in signal["page_fonts"][1]
-
-
def test_dominant_bad_cid_font_still_classifies_as_ocr_with_same_name_resource() -> None:
"""验证同名正常字体存在时,大量实际使用的坏 CID 字体仍触发 OCR。"""
pdf_bytes = _write_single_sample_page(
diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.py
index d2438c94..42bdf5b5 100644
--- a/tests/unittest/test_pdf_document.py
+++ b/tests/unittest/test_pdf_document.py
@@ -556,7 +556,6 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
def test_pdf_document_does_not_expose_legacy_compat_hooks() -> None:
assert not hasattr(pdf_document, "pdf_page_to_image")
assert not hasattr(pdf_document, "open_pdfium_document")
- assert not hasattr(pdf_document, "get_text_quality_signal_pdfium")
assert not hasattr(pdf_document.PDFDocument, "get_text_quality")
assert pdf_document.PDFDocument._pdf_doc.fset is None