Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
refactor: add comprehensive type hints to mineru/utils/ (574->0 ANN errors)
jinzhenje9869e37d383
diff --git a/mineru/utils/bbox_utils.py b/mineru/utils/bbox_utils.pyindex 717c6594..5456ea34 100644--- a/mineru/utils/bbox_utils.py+++ b/mineru/utils/bbox_utils.py@@ -4,7 +4,10 @@ import mathimport numpy as np-def normalize_to_int_bbox(box, image_size: tuple[int, int] | None = None) -> list[int] | None:+def normalize_to_int_bbox(+ box: list[float] | tuple[float, ...] | None,+ image_size: tuple[int, int] | None = None,+) -> list[int] | None:if box is None:return Nonediff --git a/mineru/utils/boxbase.py b/mineru/utils/boxbase.pyindex ea96c526..cbb06997 100644--- a/mineru/utils/boxbase.py+++ b/mineru/utils/boxbase.py@@ -1,8 +1,10 @@# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations+import math-def is_in(box1, box2) -> bool:+def is_in(box1: tuple[float, ...], box2: tuple[float, ...]) -> bool:"""box1是否完全在box2里面."""x0_1, y0_1, x1_1, y1_1 = box1x0_2, y0_2, x1_2, y1_2 = box2@@ -15,7 +17,7 @@ def is_in(box1, box2) -> bool:) # box1的下边界不在box2的下边外-def bbox_relative_pos(bbox1, bbox2):+def bbox_relative_pos(bbox1: tuple[float, ...], bbox2: tuple[float, ...]) -> tuple[bool, bool, bool, bool]:"""判断两个矩形框的相对位置关系.Args:@@ -37,7 +39,7 @@ def bbox_relative_pos(bbox1, bbox2):return left, right, bottom, top-def bbox_distance(bbox1, bbox2):+def bbox_distance(bbox1: tuple[float, ...], bbox2: tuple[float, ...]) -> float:"""计算两个矩形框的距离。Args:@@ -48,7 +50,7 @@ def bbox_distance(bbox1, bbox2):float: 矩形框之间的距离。"""- def dist(point1, point2):+ def dist(point1: tuple[float, float], point2: tuple[float, float]) -> float: # noqa: ANN202return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)x1, y1, x1b, y1b = bbox1@@ -75,7 +77,7 @@ def bbox_distance(bbox1, bbox2):return 0.0-def bbox_center_distance(bbox1, bbox2):+def bbox_center_distance(bbox1: tuple[float, ...], bbox2: tuple[float, ...]) -> float:"""计算两个矩形框中心点之间的欧氏距离。Args:@@ -98,7 +100,9 @@ def bbox_center_distance(bbox1, bbox2):return math.sqrt((center1_x - center2_x) ** 2 + (center1_y - center2_y) ** 2)-def get_minbox_if_overlap_by_ratio(bbox1, bbox2, ratio):+def get_minbox_if_overlap_by_ratio(+ bbox1: tuple[float, ...], bbox2: tuple[float, ...], ratio: float+) -> tuple[float, ...] | None:"""通过calculate_overlap_area_2_minbox_area_ratio计算两个bbox重叠的面积占最小面积的box的比例如果比例大于ratio,则返回小的那个bbox, 否则返回None."""x1_min, y1_min, x1_max, y1_max = bbox1@@ -115,7 +119,7 @@ def get_minbox_if_overlap_by_ratio(bbox1, bbox2, ratio):return None-def calculate_overlap_area_2_minbox_area_ratio(bbox1, bbox2):+def calculate_overlap_area_2_minbox_area_ratio(bbox1: tuple[float, ...], bbox2: tuple[float, ...]) -> float:"""计算box1和box2的重叠面积占最小面积的box的比例."""# Determine the coordinates of the intersection rectanglex_left = max(bbox1[0], bbox2[0])@@ -128,15 +132,14 @@ def calculate_overlap_area_2_minbox_area_ratio(bbox1, bbox2):# The area of overlap areaintersection_area = (x_right - x_left) * (y_bottom - y_top)- min_box_area = min([(bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]),- (bbox2[3] - bbox2[1]) * (bbox2[2] - bbox2[0])])+ min_box_area = min([(bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]), (bbox2[3] - bbox2[1]) * (bbox2[2] - bbox2[0])])if min_box_area == 0:return 0else:return intersection_area / min_box_area-def calculate_iou(bbox1, bbox2):+def calculate_iou(bbox1: tuple[float, ...], bbox2: tuple[float, ...]) -> float:"""计算两个边界框的交并比(IOU)。Args:@@ -172,7 +175,7 @@ def calculate_iou(bbox1, bbox2):return iou-def calculate_overlap_area_in_bbox1_area_ratio(bbox1, bbox2):+def calculate_overlap_area_in_bbox1_area_ratio(bbox1: tuple[float, ...], bbox2: tuple[float, ...]) -> float:"""计算box1和box2的重叠面积占bbox1的比例."""# Determine the coordinates of the intersection rectanglex_left = max(bbox1[0], bbox2[0])@@ -192,7 +195,7 @@ def calculate_overlap_area_in_bbox1_area_ratio(bbox1, bbox2):return intersection_area / bbox1_area-def calculate_vertical_projection_overlap_ratio(block1, block2):+def calculate_vertical_projection_overlap_ratio(block1: tuple[float, ...], block2: tuple[float, ...]) -> float:"""Calculate the proportion of the x-axis covered by the vertical projection of two blocks.@@ -224,4 +227,4 @@ def calculate_vertical_projection_overlap_ratio(block1, block2):# Proportion of the x-axis covered by the intersection# logger.info(f"intersection_length: {intersection_length}, block1_length: {block1_length}")- return intersection_length / block1_length\ No newline at end of file+ return intersection_length / block1_lengthdiff --git a/mineru/utils/char_utils.py b/mineru/utils/char_utils.pyindex d0566b32..c048dd8e 100644--- a/mineru/utils/char_utils.py+++ b/mineru/utils/char_utils.py@@ -1,16 +1,13 @@# Copyright (c) Opendatalab. All rights reserved.import re-# PDF 文本抽取时,英文跨行断词可能被编码为多种 hyphen 字符。# 这里只用于判断“行末英文断词符”,不要扩展到 en/em dash 等普通破折号。LINE_END_HYPHEN_CHARS = "-\u00ad\u2010\u2011\u2043"-LINE_END_HYPHEN_RE = re.compile(- rf"[A-Za-z]+[{re.escape(LINE_END_HYPHEN_CHARS)}]\s*$"-)+LINE_END_HYPHEN_RE = re.compile(rf"[A-Za-z]+[{re.escape(LINE_END_HYPHEN_CHARS)}]\s*$")-def is_hyphen_at_line_end(line):+def is_hyphen_at_line_end(line: str) -> bool:"""判断文本行是否以英文单词的跨行断词符结尾。只识别字母后紧跟行末 hyphen 的断词场景,不处理词内连字符或普通破折号。@@ -35,7 +32,7 @@ def full_to_half_exclude_marks(text: str) -> str:result.append(chr(code - 0xFEE0)) # Shift to ASCII rangeelse:result.append(char)- return ''.join(result)+ return "".join(result)def full_to_half(text: str) -> str:@@ -55,4 +52,4 @@ def full_to_half(text: str) -> str:result.append(chr(code - 0xFEE0)) # Shift to ASCII rangeelse:result.append(char)- return ''.join(result)+ return "".join(result)diff --git a/mineru/utils/check_sys_env.py b/mineru/utils/check_sys_env.pyindex 02b56bc8..f98c1be1 100644--- a/mineru/utils/check_sys_env.py+++ b/mineru/utils/check_sys_env.py@@ -32,7 +32,8 @@ def is_mac_os_version_supported(min_version: str = "13.5") -> bool:# print("Mac OS Version:", mac_version)return version.parse(mac_version) >= version.parse(min_version)+if __name__ == "__main__":print("Is Mac Environment:", is_mac_environment())print("Is Apple Silicon CPU:", is_apple_silicon_cpu())- print("Is Mac OS Version Supported (>=13.5):", is_mac_os_version_supported())\ No newline at end of file+ print("Is Mac OS Version Supported (>=13.5):", is_mac_os_version_supported())diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.pyindex a04d882e..a25401f3 100644--- a/mineru/utils/config_reader.py+++ b/mineru/utils/config_reader.py@@ -1,6 +1,8 @@# Copyright (c) Opendatalab. All rights reserved.import jsonimport os+from typing import Any+from loguru import loggertry:@@ -11,54 +13,54 @@ except ImportError:# 定义配置文件名常量-CONFIG_FILE_NAME = os.getenv('MINERU_TOOLS_CONFIG_JSON', 'mineru.json')+CONFIG_FILE_NAME = os.getenv("MINERU_TOOLS_CONFIG_JSON", "mineru.json")-def read_config():+def read_config() -> dict[str, Any] | None:if os.path.isabs(CONFIG_FILE_NAME):config_file = CONFIG_FILE_NAMEelse:- home_dir = os.path.expanduser('~')+ home_dir = os.path.expanduser("~")config_file = os.path.join(home_dir, CONFIG_FILE_NAME)if not os.path.exists(config_file):# logger.warning(f'{config_file} not found, using default configuration')return Noneelse:- with open(config_file, 'r', encoding='utf-8') as f:+ with open(config_file, "r", encoding="utf-8") as f:config = json.load(f)return config-def get_s3_config(bucket_name: str):+def get_s3_config(bucket_name: str) -> tuple[str, str, str]:"""~/magic-pdf.json 读出来."""config = read_config()- bucket_info = config.get('bucket_info')+ bucket_info = config.get("bucket_info")if bucket_name not in bucket_info:- access_key, secret_key, storage_endpoint = bucket_info['[default]']+ access_key, secret_key, storage_endpoint = bucket_info["[default]"]else:access_key, secret_key, storage_endpoint = bucket_info[bucket_name]if access_key is None or secret_key is None or storage_endpoint is None:- raise Exception(f'ak, sk or endpoint not found in {CONFIG_FILE_NAME}')+ raise Exception(f"ak, sk or endpoint not found in {CONFIG_FILE_NAME}")# logger.info(f"get_s3_config: ak={access_key}, sk={secret_key}, endpoint={storage_endpoint}")return access_key, secret_key, storage_endpoint-def get_s3_config_dict(path: str):+def get_s3_config_dict(path: str) -> dict[str, str]:access_key, secret_key, storage_endpoint = get_s3_config(get_bucket_name(path))- return {'ak': access_key, 'sk': secret_key, 'endpoint': storage_endpoint}+ return {"ak": access_key, "sk": secret_key, "endpoint": storage_endpoint}-def get_bucket_name(path):+def get_bucket_name(path: str) -> str:bucket, key = parse_bucket_key(path)return bucket-def parse_bucket_key(s3_full_path: str):+def parse_bucket_key(s3_full_path: str) -> tuple[str, str]:"""输入 s3://bucket/path/to/my/file.txt输出 bucket, path/to/my/file.txt@@ -72,101 +74,98 @@ def parse_bucket_key(s3_full_path: str):return bucket, key-def get_device():- device_mode = os.getenv('MINERU_DEVICE_MODE', None)+def get_device() -> str:+ device_mode = os.getenv("MINERU_DEVICE_MODE", None)if device_mode is not None:return device_mode- else:+ try:if torch.cuda.is_available():return "cuda"- elif torch.backends.mps.is_available():+ except Exception:+ pass+ try:+ if torch.backends.mps.is_available():return "mps"- else:- try:- if torch_npu.npu.is_available():- return "npu"- except Exception as e:- try:- if torch.gcu.is_available():- return "gcu"- except Exception as e:- try:- if torch.musa.is_available():- return "musa"- except Exception as e:- try:- if torch.mlu.is_available():- return "mlu"- except Exception as e:- try:- if torch.sdaa.is_available():- return "sdaa"- except Exception as e:- pass-- return "cpu"---def get_formula_enable(formula_enable):- formula_enable_env = os.getenv('MINERU_FORMULA_ENABLE')- formula_enable = formula_enable if formula_enable_env is None else formula_enable_env.lower() == 'true'+ except Exception:+ pass+ try:+ if torch_npu.npu.is_available():+ return "npu"+ except Exception:+ pass+ try:+ if torch.gcu.is_available():+ return "gcu"+ except Exception:+ pass+ try:+ if torch.musa.is_available():+ return "musa"+ except Exception:+ pass+ try:+ if torch.mlu.is_available():+ return "mlu"+ except Exception:+ pass+ try:+ if torch.sdaa.is_available():+ return "sdaa"+ except Exception:+ pass+ return "cpu"+++def get_formula_enable(formula_enable: bool) -> bool:+ formula_enable_env = os.getenv("MINERU_FORMULA_ENABLE")+ formula_enable = formula_enable if formula_enable_env is None else formula_enable_env.lower() == "true"return formula_enable-def get_table_enable(table_enable):- table_enable_env = os.getenv('MINERU_TABLE_ENABLE')- table_enable = table_enable if table_enable_env is None else table_enable_env.lower() == 'true'+def get_table_enable(table_enable: bool) -> bool:+ table_enable_env = os.getenv("MINERU_TABLE_ENABLE")+ table_enable = table_enable if table_enable_env is None else table_enable_env.lower() == "true"return table_enable-def get_ocr_det_mask_inline_formula_enable(enable):- enable_env = os.getenv('MINERU_OCR_DET_MASK_INLINE_FORMULA_ENABLE')- enable = enable if enable_env is None else enable_env.lower() == 'true'+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 enabledef get_processing_window_size(default: int = 64) -> int:- value = os.getenv('MINERU_PROCESSING_WINDOW_SIZE')+ value = os.getenv("MINERU_PROCESSING_WINDOW_SIZE")if value is None:return defaulttry:window_size = int(value)except ValueError:- logger.warning(- f"Invalid MINERU_PROCESSING_WINDOW_SIZE value: {value}, use default {default}"- )+ logger.warning(f"Invalid MINERU_PROCESSING_WINDOW_SIZE value: {value}, use default {default}")return defaultreturn max(1, window_size)def get_max_concurrent_requests(default: int = 3) -> int:if default <= 0:- raise ValueError(- f"default max_concurrent_requests must be a positive integer, got {default}"- )- value = os.getenv('MINERU_API_MAX_CONCURRENT_REQUESTS')+ raise ValueError(f"default max_concurrent_requests must be a positive integer, got {default}")+ value = os.getenv("MINERU_API_MAX_CONCURRENT_REQUESTS")if value is None:return defaulttry:max_concurrent_requests = int(value)except ValueError as exc:- raise ValueError(- "Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: "- f"{value}. Expected a positive integer."- ) from exc+ raise ValueError(f"Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: {value}. Expected a positive integer.") from excif max_concurrent_requests <= 0:- raise ValueError(- "Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: "- f"{value}. Expected a positive integer."- )+ raise ValueError(f"Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: {value}. Expected a positive integer.")return max_concurrent_requests-def get_latex_delimiter_config():+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)+ 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@@ -174,11 +173,11 @@ def get_latex_delimiter_config():return latex_delimiter_config-def get_llm_aided_config():+def get_llm_aided_config() -> dict[str, Any] | None:config = read_config()if config is None:return None- llm_aided_config = config.get('llm-aided-config', None)+ llm_aided_config = config.get("llm-aided-config", None)if llm_aided_config is None:# logger.warning(f"'llm-aided-config' not found in {CONFIG_FILE_NAME}, use 'None' as default")return None@@ -186,11 +185,11 @@ def get_llm_aided_config():return llm_aided_config-def get_local_models_dir():+def get_local_models_dir() -> dict[str, str] | None:config = read_config()if config is None:return None- models_dir = config.get('models-dir')+ 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_dirdiff --git a/mineru/utils/cut_image.py b/mineru/utils/cut_image.pyindex 57bfa4ac..4f705c2c 100644--- a/mineru/utils/cut_image.py+++ b/mineru/utils/cut_image.py@@ -1,12 +1,21 @@# Copyright (c) Opendatalab. All rights reserved.+from typing import Any+from loguru import loggerfrom .pdf_image_tools import cut_image-def cut_image_and_table(span, page_pil_img, page_img_md5, page_id, image_writer, scale=2):+def cut_image_and_table(+ span: dict[str, Any],+ page_pil_img: Any,+ page_img_md5: str,+ page_id: int,+ image_writer: Any,+ scale: int = 2,+) -> dict[str, Any]:- def return_path(path_type):+ def return_path(path_type: str) -> str: # noqa: ANN202return f"{path_type}/{page_img_md5}"span_type = span["type"]@@ -21,7 +30,7 @@ def cut_image_and_table(span, page_pil_img, page_img_md5, page_id, image_writer,return span-def check_img_bbox(bbox) -> bool:+def check_img_bbox(bbox: list[float]) -> bool:if any([bbox[0] >= bbox[2], bbox[1] >= bbox[3]]):logger.warning(f"image_bboxes: 错误的box, {bbox}")return Falsediff --git a/mineru/utils/draw_bbox.py b/mineru/utils/draw_bbox.pyindex 00247b97..fd7aacba 100644--- a/mineru/utils/draw_bbox.py+++ b/mineru/utils/draw_bbox.py@@ -1,6 +1,9 @@# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations+import jsonfrom io import BytesIO+from typing import Anyfrom loguru import loggerfrom pypdf import PageObject, PdfReader, PdfWriter@@ -28,12 +31,12 @@ DIRECT_LAYOUT_BBOX_BLOCK_TYPES = TEXT_LIKE_BLOCK_TYPES_FOR_BBOX | {SPAN_SOURCE_BLOCK_TYPES = DIRECT_LAYOUT_BBOX_BLOCK_TYPES-def _get_layout_source_blocks(page):+def _get_layout_source_blocks(page: dict[str, Any]) -> list[dict[str, Any]]:"""获取 layout.pdf 的页内原始布局块,避免段落合并后跨页子项串页绘制。"""return page.get("preproc_blocks", [])-def cal_canvas_rect(page, bbox):+def cal_canvas_rect(page: Any, bbox: list[float]) -> list[float]:"""Calculate the rectangle coordinates on the canvas based on the original PDF page and bounding box.@@ -82,7 +85,14 @@ def cal_canvas_rect(page, bbox):return rect-def draw_bbox_without_number(i, bbox_list, page, c, rgb_config, fill_config):+def draw_bbox_without_number(+ i: int,+ bbox_list: list[list[list[float]]],+ page: Any,+ c: Any,+ rgb_config: list[int],+ fill_config: bool,+) -> Any:new_rgb = [float(color) / 255 for color in rgb_config]page_data = bbox_list[i]@@ -98,7 +108,15 @@ def draw_bbox_without_number(i, bbox_list, page, c, rgb_config, fill_config):return c-def draw_bbox_with_number(i, bbox_list, page, c, rgb_config, fill_config, draw_bbox=True):+def draw_bbox_with_number(+ i: int,+ bbox_list: list[list[list[float]]],+ page: Any,+ c: Any,+ rgb_config: list[int],+ fill_config: bool,+ draw_bbox: bool = True,+) -> Any:new_rgb = [float(color) / 255 for color in rgb_config]page_data = bbox_list[i]# 强制转换为 float@@ -142,7 +160,12 @@ def draw_bbox_with_number(i, bbox_list, page, c, rgb_config, fill_config, draw_breturn c-def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):+def draw_layout_bbox(+ pdf_info: list[dict[str, Any]],+ pdf_bytes: bytes,+ out_path: str,+ filename: str,+) -> None:dropped_bbox_list = []tables_body_list, tables_caption_list, tables_footnote_list = [], [], []imgs_body_list, imgs_caption_list, imgs_footnote_list = [], [], []@@ -313,7 +336,12 @@ def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):output_pdf.write(f)-def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):+def draw_span_bbox(+ pdf_info: list[dict[str, Any]],+ pdf_bytes: bytes,+ out_path: str,+ filename: str,+) -> None:text_list = []inline_equation_list = []interline_equation_list = []@@ -321,7 +349,7 @@ def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):table_list = []dropped_list = []- def get_span_info(span):+ def get_span_info(span: dict[str, Any]) -> None: # noqa: ANN202if span["type"] == ContentType.TEXT:page_text_list.append(span["bbox"])elif span["type"] == ContentType.INLINE_EQUATION:diff --git a/mineru/utils/engine_utils.py b/mineru/utils/engine_utils.pyindex 4eaa88f4..286bced4 100644--- a/mineru/utils/engine_utils.py+++ b/mineru/utils/engine_utils.py@@ -1,10 +1,7 @@# Copyright (c) Opendatalab. All rights reserved.-import os-from loguru import logger-from mineru.utils.check_sys_env import is_mac_os_version_supported, is_windows_environment, is_mac_environment, \- is_linux_environment+from .check_sys_env import is_linux_environment, is_mac_environment, is_mac_os_version_supported, is_windows_environmentdef get_vlm_engine(inference_engine: str, is_async: bool = False) -> str:@@ -18,7 +15,7 @@ def get_vlm_engine(inference_engine: str, is_async: bool = False) -> str:Returns:最终选择的引擎名称"""- if inference_engine == 'auto':+ if inference_engine == "auto":# 根据操作系统自动选择引擎if is_windows_environment():inference_engine = _select_windows_engine()@@ -28,7 +25,7 @@ def get_vlm_engine(inference_engine: str, is_async: bool = False) -> str:inference_engine = _select_mac_engine()else:logger.warning("Unknown operating system, falling back to transformers")- inference_engine = 'transformers'+ inference_engine = "transformers"formatted_engine = _format_engine_name(inference_engine)logger.info(f"Using {formatted_engine} as the inference engine for VLM.")@@ -39,38 +36,42 @@ def _select_windows_engine() -> str:"""Windows 平台引擎选择"""try:import lmdeploy- return 'lmdeploy'++ return "lmdeploy"except ImportError:- return 'transformers'+ return "transformers"def _select_linux_engine(is_async: bool) -> str:"""Linux 平台引擎选择"""try:import vllm- return 'vllm-async' if is_async else 'vllm'++ return "vllm-async" if is_async else "vllm"except ImportError:try:import lmdeploy- return 'lmdeploy'++ return "lmdeploy"except ImportError:- return 'transformers'+ return "transformers"def _select_mac_engine() -> str:"""macOS 平台引擎选择"""try:from mlx_vlm import load as mlx_load+if is_mac_os_version_supported():- return 'mlx'+ return "mlx"else:- return 'transformers'+ return "transformers"except ImportError:- return 'transformers'+ return "transformers"def _format_engine_name(engine: str) -> str:"""统一格式化引擎名称"""- if engine != 'transformers':+ if engine != "transformers":return f"{engine}-engine"return enginediff --git a/mineru/utils/guess_suffix_or_lang.py b/mineru/utils/guess_suffix_or_lang.pyindex bd838d5c..2ec027f8 100644--- a/mineru/utils/guess_suffix_or_lang.py+++ b/mineru/utils/guess_suffix_or_lang.py@@ -1,43 +1,27 @@# Copyright (c) Opendatalab. All rights reserved.from io import BytesIOfrom pathlib import Path-from zipfile import BadZipFile, ZipFilefrom xml.etree import ElementTree+from zipfile import BadZipFile, ZipFilefrom loguru import loggerfrom magika import Magika-DEFAULT_LANG = "txt"-PDF_SIG_BYTES = b'%PDF'+PDF_SIG_BYTES = b"%PDF"OOXML_ROOT_RELS = "_rels/.rels"OOXML_CONTENT_TYPES = "[Content_Types].xml"-OOXML_PACKAGE_REL_NS = (- "http://schemas.openxmlformats.org/package/2006/relationships"-)-OOXML_CONTENT_TYPES_NS = (- "http://schemas.openxmlformats.org/package/2006/content-types"-)-OOXML_OFFICE_DOCUMENT_REL = (- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"- "officeDocument"-)+OOXML_PACKAGE_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"+OOXML_CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types"+OOXML_OFFICE_DOCUMENT_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"OOXML_MAIN_CONTENT_TYPES = {- (- "application/vnd.openxmlformats-officedocument.wordprocessingml."- "document.main+xml"- ): "docx",- (- "application/vnd.openxmlformats-officedocument.presentationml."- "presentation.main+xml"- ): "pptx",- (- "application/vnd.openxmlformats-officedocument.spreadsheetml."- "sheet.main+xml"- ): "xlsx",+ ("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"): "docx",+ ("application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"): "pptx",+ ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"): "xlsx",}magika = Magika()+def _normalize_text_for_language_guess(code: str) -> str:if not code:return ""@@ -70,7 +54,7 @@ def _normalize_text_for_language_guess(code: str) -> str:return "".join(normalized)-def guess_language_by_text(code):+def guess_language_by_text(code: str) -> str:normalized_code = _normalize_text_for_language_guess(code)if not normalized_code:return DEFAULT_LANG@@ -171,18 +155,23 @@ def _guess_ooxml_suffix_by_path(file_path: Path) -> str | None:return None-def guess_suffix_by_bytes(file_bytes, file_path=None) -> str:+def guess_suffix_by_bytes(file_bytes: bytes, file_path: str | None = None) -> str:ooxml_suffix = _guess_ooxml_suffix_by_bytes(file_bytes)if ooxml_suffix:return ooxml_suffixsuffix = magika.identify_bytes(file_bytes).prediction.output.label- if file_path and suffix in ["ai", "html"] and Path(file_path).suffix.lower() in [".pdf"] and file_bytes[:4] == PDF_SIG_BYTES:+ if (+ file_path+ and suffix in ["ai", "html"]+ and Path(file_path).suffix.lower() in [".pdf"]+ and file_bytes[:4] == PDF_SIG_BYTES+ ):suffix = "pdf"return suffix-def guess_suffix_by_path(file_path) -> str:+def guess_suffix_by_path(file_path: str | Path) -> str:if not isinstance(file_path, Path):file_path = Path(file_path)@@ -193,7 +182,7 @@ def guess_suffix_by_path(file_path) -> str:suffix = magika.identify_path(file_path).prediction.output.labelif suffix in ["ai", "html"] and file_path.suffix.lower() in [".pdf"]:try:- with open(file_path, 'rb') as f:+ with open(file_path, "rb") as f:if f.read(4) == PDF_SIG_BYTES:suffix = "pdf"except Exception as e:diff --git a/mineru/utils/hash_utils.py b/mineru/utils/hash_utils.pyindex 2b82c78d..1b4b953e 100644--- a/mineru/utils/hash_utils.py+++ b/mineru/utils/hash_utils.py@@ -3,28 +3,28 @@ import hashlibimport json-def bytes_md5(file_bytes):+def bytes_md5(file_bytes: bytes) -> str:hasher = hashlib.md5()hasher.update(file_bytes)return hasher.hexdigest().upper()-def str_md5(input_string):+def str_md5(input_string: str) -> str:hasher = hashlib.md5()# 在Python3中,需要将字符串转化为字节对象才能被哈希函数处理- input_bytes = input_string.encode('utf-8')+ input_bytes = input_string.encode("utf-8")hasher.update(input_bytes)return hasher.hexdigest()-def str_sha256(input_string):+def str_sha256(input_string: str) -> str:hasher = hashlib.sha256()# 在Python3中,需要将字符串转化为字节对象才能被哈希函数处理- input_bytes = input_string.encode('utf-8')+ input_bytes = input_string.encode("utf-8")hasher.update(input_bytes)return hasher.hexdigest()-def dict_md5(d):+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()\ No newline at end of file+ return hashlib.md5(json_str.encode("utf-8")).hexdigest()diff --git a/mineru/utils/language.py b/mineru/utils/language.pyindex d90c00d6..073daa0c 100644--- a/mineru/utils/language.py+++ b/mineru/utils/language.py@@ -6,16 +6,16 @@ if not os.getenv("FTLANG_CACHE"):current_file_path = os.path.abspath(__file__)current_dir = os.path.dirname(current_file_path)root_dir = os.path.dirname(current_dir)- ftlang_cache_dir = os.path.join(root_dir, 'resources', 'fasttext-langdetect')+ ftlang_cache_dir = os.path.join(root_dir, "resources", "fasttext-langdetect")os.environ["FTLANG_CACHE"] = str(ftlang_cache_dir)# print(os.getenv("FTLANG_CACHE"))from fast_langdetect import detect_language-def remove_invalid_surrogates(text):+def remove_invalid_surrogates(text: str) -> str:# 移除无效的 UTF-16 代理对- return ''.join(c for c in text if not (0xD800 <= ord(c) <= 0xDFFF))+ return "".join(c for c in text if not (0xD800 <= ord(c) <= 0xDFFF))def detect_lang(text: str) -> str:@@ -26,24 +26,23 @@ def detect_lang(text: str) -> str:text = text.replace("\n", "")text = remove_invalid_surrogates(text)- # print(text)try:lang_upper = detect_language(text)- except:- html_no_ctrl_chars = ''.join([l for l in text if unicodedata.category(l)[0] not in ['C', ]])+ except Exception:+ html_no_ctrl_chars = "".join([c for c in text if unicodedata.category(c)[0] not in ["C"]])lang_upper = detect_language(html_no_ctrl_chars)try:lang = lang_upper.lower()- except:+ except Exception:lang = ""return lang-if __name__ == '__main__':+if __name__ == "__main__":print(os.getenv("FTLANG_CACHE"))print(detect_lang("This is a test."))print(detect_lang("<html>This is a test</html>"))print(detect_lang("这个是中文测试。"))print(detect_lang("<html>这个是中文测试。</html>"))- print(detect_lang("〖\ud835\udc46\ud835〗这是个包含utf-16的中文测试"))\ No newline at end of file+ print(detect_lang("〖\ud835\udc46\ud835〗这是个包含utf-16的中文测试"))diff --git a/mineru/utils/llm_aided.py b/mineru/utils/llm_aided.pyindex 9340858e..93c6af9d 100644--- a/mineru/utils/llm_aided.py+++ b/mineru/utils/llm_aided.py@@ -1,23 +1,26 @@# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations+from concurrent.futures import ThreadPoolExecutor+from typing import Any, Callableimport json_repairfrom loguru import loggerfrom openai import OpenAI-from mineru.backend.pipeline.pipeline_middle_json_mkcontent import merge_para_with_text-from mineru.utils.enum_class import BlockType-+from ..backend.pipeline.pipeline_middle_json_mkcontent import merge_para_with_text+from .enum_class import BlockTypeTITLE_BLOCK_TYPES = {BlockType.TITLE,BlockType.DOC_TITLE,BlockType.PARAGRAPH_TITLE,}+MAX_TITLE_GROUP_WORKERS = 4-def _get_title_line_avg_height(block):+def _get_title_line_avg_height(block: dict[str, Any]) -> float:line_avg_height = block.get("line_avg_height")if isinstance(line_avg_height, (int, float)) and line_avg_height > 0:return line_avg_height@@ -41,7 +44,9 @@ def _get_title_line_avg_height(block):return 0-def _collect_title_block_refs(page_info_list):+def _collect_title_block_refs(+ page_info_list: list[dict[str, Any]],+) -> tuple[list[tuple[dict[str, Any], dict[str, Any]]], set[Any]]:title_block_refs = []title_types = set()@@ -55,7 +60,7 @@ def _collect_title_block_refs(page_info_list):return title_block_refs, title_types-def _build_title_dict(title_block_refs):+def _build_title_dict(title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]]) -> dict[str, list[Any]]:title_dict = {}for i, (page_info, block) in enumerate(title_block_refs):@@ -68,7 +73,7 @@ def _build_title_dict(title_block_refs):return title_dict-def _build_title_optimize_prompt(title_dict):+def _build_title_optimize_prompt(title_dict: dict[str, list[Any]]) -> str:return f"""输入的内容是一篇文档中所有标题组成的字典,请根据以下指南优化标题的结果,使结果符合正常文档的层次结构:1. 字典中每个value均为一个list,包含以下元素:@@ -111,7 +116,7 @@ Corrected title list:"""-def _build_relative_title_optimize_prompt(title_dict):+def _build_relative_title_optimize_prompt(title_dict: dict[str, list[Any]]) -> str:return f"""输入内容是某一篇文档中除文章标题外的全部章节/段落标题组成的字典。请注意:@@ -157,7 +162,9 @@ Corrected title list:"""-def _request_title_levels(title_aided_config, title_dict, prompt_builder=None):+def _request_title_levels(+ title_aided_config: dict[str, Any], title_dict: dict[str, list[Any]], prompt_builder: Callable[..., str] | None = None+) -> dict[int, int] | None:if len(title_dict) == 0:return {}@@ -182,9 +189,7 @@ def _request_title_levels(title_aided_config, title_dict, prompt_builder=None):"stream": True,}if "enable_thinking" in title_aided_config:- api_params["extra_body"] = {- "enable_thinking": title_aided_config["enable_thinking"]- }+ api_params["extra_body"] = {"enable_thinking": title_aided_config["enable_thinking"]}while retry_count < max_retries:try:@@ -206,9 +211,7 @@ def _request_title_levels(title_aided_config, title_dict, prompt_builder=None):if set(dict_completion.keys()) == expected_keys:return dict_completion- logger.warning(- "The keys in the optimized title result do not match the input titles."- )+ logger.warning("The keys in the optimized title result do not match the input titles.")except Exception as e:logger.exception(e)@@ -218,7 +221,9 @@ def _request_title_levels(title_aided_config, title_dict, prompt_builder=None):return None-def _apply_levels_to_blocks(title_block_refs, levels_by_index):+def _apply_levels_to_blocks(+ title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]], levels_by_index: dict[int, int] | None+) -> None:if levels_by_index is None:return@@ -226,13 +231,13 @@ def _apply_levels_to_blocks(title_block_refs, levels_by_index):block["level"] = int(levels_by_index[i])-def _normalize_title_types(title_block_refs):+def _normalize_title_types(title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]]) -> None:for _, block in title_block_refs:if block.get("type") in [BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE]:block["type"] = BlockType.TITLE-def _get_title_block_identity(block):+def _get_title_block_identity(block: dict[str, Any]) -> tuple[str, int] | tuple[str, tuple[Any, ...], str]:block_index = block.get("index")if block_index is not None:return ("index", block_index)@@ -244,7 +249,7 @@ def _get_title_block_identity(block):)-def _sync_para_titles_to_preproc(page_info_list):+def _sync_para_titles_to_preproc(page_info_list: list[dict[str, Any]]) -> None:for page_info in page_info_list:para_title_map = {}for block in page_info.get("para_blocks", []):@@ -267,13 +272,17 @@ def _sync_para_titles_to_preproc(page_info_list):block["level"] = para_block["level"]-def _run_single_pass_title_leveling(title_block_refs, title_aided_config):+def _run_single_pass_title_leveling(+ title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]], title_aided_config: dict[str, Any]+) -> None:title_dict = _build_title_dict(title_block_refs)levels_by_index = _request_title_levels(title_aided_config, title_dict)_apply_levels_to_blocks(title_block_refs, levels_by_index)-def _split_paragraph_title_groups(title_block_refs):+def _split_paragraph_title_groups(+ title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]],+) -> list[list[tuple[dict[str, Any], dict[str, Any]]]]:groups = []current_group = []@@ -292,17 +301,16 @@ def _split_paragraph_title_groups(title_block_refs):return groups-def _offset_paragraph_title_levels(levels_by_index):+def _offset_paragraph_title_levels(levels_by_index: dict[int, int] | None) -> dict[int, int] | None:if not levels_by_index:return levels_by_index- return {- index: 2 if level == 1 else level- for index, level in levels_by_index.items()- }+ return {index: 2 if level == 1 else level for index, level in levels_by_index.items()}-def _request_paragraph_group_levels(title_block_refs, title_aided_config):+def _request_paragraph_group_levels(+ title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]], title_aided_config: dict[str, Any]+) -> dict[int, int] | None:title_dict = _build_title_dict(title_block_refs)levels_by_index = _request_title_levels(title_aided_config,@@ -312,7 +320,9 @@ def _request_paragraph_group_levels(title_block_refs, title_aided_config):return _offset_paragraph_title_levels(levels_by_index)-def _run_grouped_title_leveling(title_block_refs, title_aided_config):+def _run_grouped_title_leveling(+ title_block_refs: list[tuple[dict[str, Any], dict[str, Any]]], title_aided_config: dict[str, Any]+) -> None:doc_title_refs = []for title_ref in title_block_refs:_, block = title_ref@@ -337,8 +347,7 @@ def _run_grouped_title_leveling(title_block_refs, title_aided_config):group_levels = [future.result() for future in futures]else:group_levels = [- _request_paragraph_group_levels(title_group, title_aided_config)- for title_group in paragraph_title_groups+ _request_paragraph_group_levels(title_group, title_aided_config) for title_group in paragraph_title_groups]for title_group, levels_by_index in zip(paragraph_title_groups, group_levels):@@ -349,7 +358,7 @@ def _run_grouped_title_leveling(title_block_refs, title_aided_config):_normalize_title_types(title_group)-def llm_aided_title(page_info_list, title_aided_config):+def llm_aided_title(page_info_list: list[dict[str, Any]], title_aided_config: dict[str, Any]) -> None:title_block_refs, title_types = _collect_title_block_refs(page_info_list)if len(title_block_refs) == 0:logger.info("No titles detected, skipping LLM-aided title optimization.")diff --git a/mineru/utils/magic_model_utils.py b/mineru/utils/magic_model_utils.pyindex 105dcba8..1cd4728c 100644--- a/mineru/utils/magic_model_utils.py+++ b/mineru/utils/magic_model_utils.py@@ -2,10 +2,12 @@"""包含两个MagicModel类中重复使用的方法和逻辑"""-from typing import List, Dict, Any, Callable++from typing import Any, Callable, Dict, Listfrom loguru import logger-from mineru.utils.boxbase import bbox_distance, bbox_center_distance, is_in++from .boxbase import bbox_center_distance, bbox_distance, is_indef reduct_overlap(bboxes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:@@ -24,19 +26,19 @@ def reduct_overlap(bboxes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:for j in range(N):if i == j:continue- if is_in(bboxes[i]['bbox'], bboxes[j]['bbox']):+ if is_in(bboxes[i]["bbox"], bboxes[j]["bbox"]):keep[i] = Falsereturn [bboxes[i] for i in range(N) if keep[i]]def tie_up_category_by_index(- get_subjects_func: Callable,- get_objects_func: Callable,- extract_subject_func: Callable = None,- extract_object_func: Callable = None,- object_block_type: str = "object",- include_bbox: bool = True,-):+ get_subjects_func: Callable,+ get_objects_func: Callable,+ extract_subject_func: Callable[..., Any] | None = None,+ extract_object_func: Callable[..., Any] | None = None,+ object_block_type: str = "object",+ include_bbox: bool = True,+) -> list[dict[str, Any]]:"""基于index的类别关联方法,用于将主体对象与客体对象进行关联客体优先匹配给index最接近的主体,匹配优先级为:@@ -74,9 +76,9 @@ def tie_up_category_by_index(}# 提取所有客体的index集合,用于计算有效index差值- object_indices = set(obj["index"] for obj in objects)+ object_indices = {obj["index"] for obj in objects}- def calc_effective_index_diff(obj_index: int, sub_index: int) -> int:+ def calc_effective_index_diff(obj_index: int, sub_index: int) -> int: # noqa: ANN202"""计算有效的index差值有效差值 = 绝对差值 - 区间内其他客体的数量@@ -133,20 +135,33 @@ def tie_up_category_by_index(if edge_dist_diff > 2:# 边缘距离差值大于2,匹配边缘距离更小的主体best_subject_idx = min(edge_distances, key=lambda x: x[1])[0]- logger.debug(f"Obj index: {obj_index}, edge_dist_diff > 2, matching to subject with min edge distance, index: {subjects[best_subject_idx]['index']}")+ logger.debug(+ f"Obj index: {obj_index}, edge_dist_diff > 2, matching to subject with min edge distance,"+ f" index: {subjects[best_subject_idx]['index']}"+ )elif object_block_type == "table_caption":# 边缘距离差值<=2且为table_caption,匹配index更大的主体best_subject_idx = max(best_subject_indices, key=lambda idx: subjects[idx]["index"])- logger.debug(f"Obj index: {obj_index}, edge_dist_diff <= 2 and table_caption, matching to later subject with index: {subjects[best_subject_idx]['index']}")+ logger.debug(+ f"Obj index: {obj_index}, edge_dist_diff <= 2 and table_caption,"+ f" matching to later subject with index: {subjects[best_subject_idx]['index']}"+ )elif object_block_type.endswith("footnote"):# 边缘距离差值<=2且为footnote,匹配index更小的主体best_subject_idx = min(best_subject_indices, key=lambda idx: subjects[idx]["index"])- logger.debug(f"Obj index: {obj_index}, edge_dist_diff <= 2 and footnote, matching to earlier subject with index: {subjects[best_subject_idx]['index']}")+ logger.debug(+ f"Obj index: {obj_index}, edge_dist_diff <= 2 and footnote,"+ f" matching to earlier subject with index: {subjects[best_subject_idx]['index']}"+ )else:# 边缘距离差值<=2 且不适用特殊匹配规则,使用中心点距离匹配- center_distances = [(idx, bbox_center_distance(obj["bbox"], subjects[idx]["bbox"])) for idx in best_subject_indices]+ center_distances = [+ (idx, bbox_center_distance(obj["bbox"], subjects[idx]["bbox"])) for idx in best_subject_indices+ ]for idx, center_dist in center_distances:- logger.debug(f"Obj index: {obj_index}, Sub index: {subjects[idx]['index']}, Center distance: {center_dist}")+ logger.debug(+ f"Obj index: {obj_index}, Sub index: {subjects[idx]['index']}, Center distance: {center_dist}"+ )best_subject_idx = min(center_distances, key=lambda x: x[1])[0]else:best_subject_idx = best_subject_indices[0]diff --git a/mineru/utils/model_utils.py b/mineru/utils/model_utils.pyindex 6c1f486a..2f70d93d 100644--- a/mineru/utils/model_utils.py+++ b/mineru/utils/model_utils.py@@ -1,11 +1,13 @@# Copyright (c) Opendatalab. All rights reserved.+import gcimport mathimport osimport time-import gc-from PIL import Image-from loguru import logger+from typing import Any+import numpy as np+from loguru import logger+from PIL import Imagetry:import torch@@ -35,19 +37,24 @@ TEXT_REGION_LABELS = {}-def _get_bbox(item):+def _get_bbox(item: dict[str, Any]) -> tuple[float, float, float, float] | None:bbox = item.get("bbox")if bbox is not None:xmin, ymin, xmax, ymax = bboxreturn float(xmin), float(ymin), float(xmax), float(ymax)-def _get_int_bbox(item):+def _get_int_bbox(item: dict[str, Any]) -> tuple[int, int, int, int]:xmin, ymin, xmax, ymax = _get_bbox(item)return math.floor(xmin), math.floor(ymin), math.ceil(xmax), math.ceil(ymax)-def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):+def crop_img(+ input_res: dict[str, Any],+ input_img: Image.Image | np.ndarray,+ crop_paste_x: int = 0,+ crop_paste_y: int = 0,+) -> tuple[Image.Image | np.ndarray, list[int]]:crop_xmin, crop_ymin, crop_xmax, crop_ymax = _get_int_bbox(input_res)# Calculate new dimensions@@ -55,7 +62,6 @@ def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):crop_new_height = crop_ymax - crop_ymin + crop_paste_y * 2if isinstance(input_img, np.ndarray):-# Create a white background arrayreturn_image = np.ones((crop_new_height, crop_new_width, 3), dtype=np.uint8) * 255@@ -63,29 +69,29 @@ def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):cropped_img = input_img[crop_ymin:crop_ymax, crop_xmin:crop_xmax]# Paste the cropped image onto the white background- return_image[crop_paste_y:crop_paste_y + (crop_ymax - crop_ymin),- crop_paste_x:crop_paste_x + (crop_xmax - crop_xmin)] = cropped_img+ return_image[+ crop_paste_y : crop_paste_y + (crop_ymax - crop_ymin), crop_paste_x : crop_paste_x + (crop_xmax - crop_xmin)+ ] = cropped_imgelse:# Create a white background array- return_image = Image.new('RGB', (crop_new_width, crop_new_height), 'white')+ return_image = Image.new("RGB", (crop_new_width, crop_new_height), "white")# Crop imagecrop_box = (crop_xmin, crop_ymin, crop_xmax, crop_ymax)cropped_img = input_img.crop(crop_box)return_image.paste(cropped_img, (crop_paste_x, crop_paste_y))- return_list = [crop_paste_x, crop_paste_y, crop_xmin, crop_ymin, crop_xmax, crop_ymax, crop_new_width,- crop_new_height]+ return_list = [crop_paste_x, crop_paste_y, crop_xmin, crop_ymin, crop_xmax, crop_ymax, crop_new_width, crop_new_height]return return_image, return_list-def get_coords_and_area(block_with_poly):+def get_coords_and_area(block_with_poly: dict[str, Any]) -> tuple[float, float, float, float, 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, box2):+def calculate_intersection(box1: tuple[float, ...], box2: tuple[float, ...]) -> tuple[float, float, float, float] | None:"""Calculate intersection coordinates between two boxes."""intersection_xmin = max(box1[0], box2[0])intersection_ymin = max(box1[1], box2[1])@@ -99,7 +105,7 @@ def calculate_intersection(box1, box2):return intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax-def is_inside(small_box, big_box, overlap_threshold=0.8):+def is_inside(small_box: tuple[float, ...], big_box: tuple[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[:4], big_box[:4])@@ -114,11 +120,11 @@ def is_inside(small_box, big_box, overlap_threshold=0.8):def remove_nested_ocr_text_blocks(- ocr_res_list,- layout_res,- overlap_threshold=0.8,- min_area_ratio=1.01,-):+ 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, []@@ -139,13 +145,13 @@ def remove_nested_ocr_text_blocks(breakremove_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- ]+ 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, overlap_threshold=0.8):+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 = []@@ -158,9 +164,11 @@ def get_res_list_from_layout_res(layout_res, overlap_threshold=0.8):if label in ["display_formula", "inline_formula"]:xmin, ymin, xmax, ymax = _get_bbox(res)- single_page_mfdetrec_res.append({- "bbox": [xmin, ymin, xmax, ymax],- })+ single_page_mfdetrec_res.append(+ {+ "bbox": [xmin, ymin, xmax, ymax],+ }+ )elif label == "table":table_res_list.append(res)elif label in TEXT_REGION_LABELS:@@ -180,7 +188,7 @@ def get_res_list_from_layout_res(layout_res, overlap_threshold=0.8):return ocr_res_list, table_res_list, single_page_mfdetrec_res-def clean_memory(device='cuda'):+def clean_memory(device: str = "cuda") -> None:if str(device).startswith("cuda"):if torch.cuda.is_available():torch.cuda.empty_cache()@@ -201,11 +209,11 @@ def clean_memory(device='cuda'):torch.mlu.empty_cache()elif str(device).startswith("sdaa"):if torch.sdaa.is_available():- torch.sdaa.empty_cache()+ torch.sdaa.empty_cache()gc.collect()-def clean_vram(device, vram_threshold=8):+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()@@ -214,7 +222,7 @@ def clean_vram(device, vram_threshold=8):logger.debug(f"gc time: {gc_time}")-def get_vram(device) -> int:+def get_vram(device: str) -> int:env_vram = os.getenv("MINERU_VIRTUAL_VRAM_SIZE")# 如果环境变量已配置,尝试解析并返回@@ -224,30 +232,30 @@ def get_vram(device) -> int:if total_memory > 0:return total_memoryelse:- logger.warning(- f"MINERU_VIRTUAL_VRAM_SIZE value '{env_vram}' is not positive, falling back to auto-detection")+ logger.warning(f"MINERU_VIRTUAL_VRAM_SIZE value '{env_vram}' is not positive, falling back to auto-detection")except ValueError:logger.warning(- f"MINERU_VIRTUAL_VRAM_SIZE value '{env_vram}' is not a valid integer, falling back to auto-detection")+ f"MINERU_VIRTUAL_VRAM_SIZE value '{env_vram}' is not a valid integer, falling back to auto-detection"+ )# 环境变量未配置或配置错误,根据device自动获取total_memory = 1if torch.cuda.is_available() and str(device).startswith("cuda"):- total_memory = round(torch.cuda.get_device_properties(device).total_memory / (1024 ** 3)) # 将字节转换为 GB+ total_memory = round(torch.cuda.get_device_properties(device).total_memory / (1024**3)) # 将字节转换为 GBelif str(device).startswith("npu"):if torch_npu.npu.is_available():- total_memory = round(torch_npu.npu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB+ total_memory = round(torch_npu.npu.get_device_properties(device).total_memory / (1024**3)) # 转为 GBelif str(device).startswith("gcu"):if torch.gcu.is_available():- total_memory = round(torch.gcu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB+ total_memory = round(torch.gcu.get_device_properties(device).total_memory / (1024**3)) # 转为 GBelif str(device).startswith("musa"):if torch.musa.is_available():- total_memory = round(torch.musa.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB+ total_memory = round(torch.musa.get_device_properties(device).total_memory / (1024**3)) # 转为 GBelif str(device).startswith("mlu"):if torch.mlu.is_available():- total_memory = round(torch.mlu.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB+ total_memory = round(torch.mlu.get_device_properties(device).total_memory / (1024**3)) # 转为 GBelif str(device).startswith("sdaa"):if torch.sdaa.is_available():- total_memory = round(torch.sdaa.get_device_properties(device).total_memory / (1024 ** 3)) # 转为 GB+ total_memory = round(torch.sdaa.get_device_properties(device).total_memory / (1024**3)) # 转为 GBreturn total_memorydiff --git a/mineru/utils/models_download_utils.py b/mineru/utils/models_download_utils.pyindex 7c9e20d1..417808db 100644--- a/mineru/utils/models_download_utils.py+++ b/mineru/utils/models_download_utils.py@@ -1,12 +1,14 @@# Copyright (c) Opendatalab. All rights reserved.import os+from huggingface_hub import snapshot_download as hf_snapshot_downloadfrom modelscope import snapshot_download as ms_snapshot_download-from mineru.utils.config_reader import get_local_models_dir-from mineru.utils.enum_class import ModelPath+from .config_reader import get_local_models_dir+from .enum_class import ModelPath+-def auto_download_and_get_model_root_path(relative_path: str, repo_mode='pipeline') -> str:+def auto_download_and_get_model_root_path(relative_path: str, repo_mode: str = "pipeline") -> str:"""支持文件或目录的可靠下载。- 如果输入文件: 返回本地文件绝对路径@@ -15,9 +17,9 @@ def auto_download_and_get_model_root_path(relative_path: str, repo_mode='pipelin:param relative_path: 文件或目录相对路径:return: 本地文件绝对路径或相对路径"""- model_source = os.getenv('MINERU_MODEL_SOURCE', "huggingface")+ model_source = os.getenv("MINERU_MODEL_SOURCE", "huggingface")- if model_source == 'local':+ if model_source == "local":local_models_config = get_local_models_dir()root_path = local_models_config.get(repo_mode, None)if not root_path:@@ -26,24 +28,23 @@ def auto_download_and_get_model_root_path(relative_path: str, repo_mode='pipelin# 建立仓库模式到路径的映射repo_mapping = {- 'pipeline': {- 'huggingface': ModelPath.pipeline_root_hf,- 'modelscope': ModelPath.pipeline_root_modelscope,- 'default': ModelPath.pipeline_root_hf+ "pipeline": {+ "huggingface": ModelPath.pipeline_root_hf,+ "modelscope": ModelPath.pipeline_root_modelscope,+ "default": ModelPath.pipeline_root_hf,+ },+ "vlm": {+ "huggingface": ModelPath.vlm_root_hf,+ "modelscope": ModelPath.vlm_root_modelscope,+ "default": ModelPath.vlm_root_hf,},- 'vlm': {- 'huggingface': ModelPath.vlm_root_hf,- 'modelscope': ModelPath.vlm_root_modelscope,- 'default': ModelPath.vlm_root_hf- }}if repo_mode not in repo_mapping:raise ValueError(f"Unsupported repo_mode: {repo_mode}, must be 'pipeline' or 'vlm'")# 如果没有指定model_source或值不是'modelscope',则使用默认值- repo = repo_mapping[repo_mode].get(model_source, repo_mapping[repo_mode]['default'])-+ repo = repo_mapping[repo_mode].get(model_source, repo_mapping[repo_mode]["default"])if model_source == "huggingface":snapshot_download = hf_snapshot_download@@ -54,23 +55,23 @@ def auto_download_and_get_model_root_path(relative_path: str, repo_mode='pipelincache_dir = None- if repo_mode == 'pipeline':- relative_path = relative_path.strip('/')- cache_dir = snapshot_download(repo, allow_patterns=[relative_path, relative_path+"/*"])- elif repo_mode == 'vlm':+ if repo_mode == "pipeline":+ relative_path = relative_path.strip("/")+ cache_dir = snapshot_download(repo, allow_patterns=[relative_path, relative_path + "/*"])+ elif repo_mode == "vlm":# VLM 模式下,根据 relative_path 的不同处理方式if relative_path == "/":cache_dir = snapshot_download(repo)else:- relative_path = relative_path.strip('/')- cache_dir = snapshot_download(repo, allow_patterns=[relative_path, relative_path+"/*"])+ relative_path = relative_path.strip("/")+ cache_dir = snapshot_download(repo, allow_patterns=[relative_path, relative_path + "/*"])if not cache_dir:raise FileNotFoundError(f"Failed to download model: {relative_path} from {repo}")return cache_dir-if __name__ == '__main__':+if __name__ == "__main__":path1 = "models/README.md"root = auto_download_and_get_model_root_path(path1)- print("本地文件绝对路径:", os.path.join(root, path1))\ No newline at end of file+ print("本地文件绝对路径:", os.path.join(root, path1))diff --git a/mineru/utils/ocr_utils.py b/mineru/utils/ocr_utils.pyindex b80081da..a686de44 100644--- a/mineru/utils/ocr_utils.py+++ b/mineru/utils/ocr_utils.py@@ -1,5 +1,9 @@# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations+import copy+from typing import Any+import cv2import numpy as np@@ -10,22 +14,23 @@ class OcrConfidence:min_confidence = 0.5min_width = 3+LINE_WIDTH_TO_HEIGHT_RATIO_THRESHOLD = 4 # 一般情况下,行宽度超过高度4倍时才是一个正常的横向文本块TEXT_REC_ROTATE_RATIO = 1.5-def merge_spans_to_line(spans, threshold=0.6):+def merge_spans_to_line(spans: list[dict[str, Any]], threshold: float = 0.6) -> list[list[dict[str, Any]]]:if len(spans) == 0:return []else:# 按照y0坐标排序- spans.sort(key=lambda span: span['bbox'][1])+ spans.sort(key=lambda span: span["bbox"][1])lines = []current_line = [spans[0]]for span in spans[1:]:# 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行- if _is_overlaps_y_exceeds_threshold(span['bbox'], current_line[-1]['bbox'], threshold):+ if _is_overlaps_y_exceeds_threshold(span["bbox"], current_line[-1]["bbox"], threshold):current_line.append(span)else:# 否则,开始新行@@ -38,9 +43,12 @@ def merge_spans_to_line(spans, threshold=0.6):return lines-def _is_overlaps_y_exceeds_threshold(bbox1,- bbox2,- overlap_ratio_threshold=0.8):++def _is_overlaps_y_exceeds_threshold(+ bbox1: list[float],+ bbox2: list[float],+ overlap_ratio_threshold: float = 0.8,+) -> bool:"""检查两个bbox在y轴上是否有重叠,并且该重叠区域的高度占两个bbox高度更低的那个超过80%"""_, y0_1, _, y1_1 = bbox1_, y0_2, _, y1_2 = bbox2@@ -53,9 +61,11 @@ def _is_overlaps_y_exceeds_threshold(bbox1,return (overlap / min_height) > overlap_ratio_threshold if min_height > 0 else False-def _is_overlaps_x_exceeds_threshold(bbox1,- bbox2,- overlap_ratio_threshold=0.8):+def _is_overlaps_x_exceeds_threshold(+ bbox1: list[float],+ bbox2: list[float],+ overlap_ratio_threshold: float = 0.8,+) -> bool:"""检查两个bbox在x轴上是否有重叠,并且该重叠区域的宽度占两个bbox宽度更低的那个超过指定阈值"""x0_1, _, x1_1, _ = bbox1x0_2, _, x1_2, _ = bbox2@@ -67,11 +77,12 @@ def _is_overlaps_x_exceeds_threshold(bbox1,return (overlap / min_width) > overlap_ratio_threshold if min_width > 0 else False-def img_decode(content: bytes):+def img_decode(content: bytes) -> Any:np_arr = np.frombuffer(content, dtype=np.uint8)return cv2.imdecode(np_arr, cv2.IMREAD_UNCHANGED)-def check_img(img):++def check_img(img: bytes | np.ndarray) -> Any:if isinstance(img, bytes):img = img_decode(img)if isinstance(img, np.ndarray) and len(img.shape) == 2:@@ -79,7 +90,7 @@ def check_img(img):return img-def alpha_to_color(img, alpha_color=(255, 255, 255)):+def alpha_to_color(img: np.ndarray, alpha_color: tuple[int, int, int] = (255, 255, 255)) -> np.ndarray:if len(img.shape) == 3 and img.shape[2] == 4:B, G, R, A = cv2.split(img)alpha = A / 255@@ -92,13 +103,13 @@ def alpha_to_color(img, alpha_color=(255, 255, 255)):return img-def preprocess_image(_image):+def preprocess_image(_image: np.ndarray) -> np.ndarray:alpha_color = (255, 255, 255)_image = alpha_to_color(_image, alpha_color)return _image-def sorted_boxes(dt_boxes):+def sorted_boxes(dt_boxes: list[Any]) -> list[Any]:"""Sort text boxes in order from top to bottom, left to rightargs:@@ -112,8 +123,7 @@ def sorted_boxes(dt_boxes):for i in range(num_boxes - 1):for j in range(i, -1, -1):- if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \- (_boxes[j + 1][0][0] < _boxes[j][0][0]):+ if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and (_boxes[j + 1][0][0] < _boxes[j][0][0]):tmp = _boxes[j]_boxes[j] = _boxes[j + 1]_boxes[j + 1] = tmp@@ -122,21 +132,21 @@ def sorted_boxes(dt_boxes):return _boxes-def bbox_to_points(bbox):- """ 将bbox格式转换为四个顶点的数组 """+def bbox_to_points(bbox: list[float] | tuple[float, ...]) -> np.ndarray:+ """将bbox格式转换为四个顶点的数组"""x0, y0, x1, y1 = bbox- return np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]).astype('float32')+ return np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]).astype("float32")-def points_to_bbox(points):- """ 将四个顶点的数组转换为bbox格式 """+def points_to_bbox(points: np.ndarray) -> list[float]:+ """将四个顶点的数组转换为bbox格式"""x0, y0 = points[0]x1, _ = points[1]_, y1 = points[2]return [x0, y0, x1, y1]-def merge_intervals(intervals):+def merge_intervals(intervals: list[list[float]]) -> list[list[float]]:# Sort the intervals based on the start valueintervals.sort(key=lambda x: x[0])@@ -153,7 +163,7 @@ def merge_intervals(intervals):return merged-def remove_intervals(original, masks):+def remove_intervals(original: list[float], masks: list[list[float]]) -> list[list[float]]:# Merge all mask intervalsmerged_masks = merge_intervals(masks)@@ -184,11 +194,10 @@ def remove_intervals(original, masks):return result-def update_det_boxes(dt_boxes, mfd_res):+def update_det_boxes(dt_boxes: list[Any], mfd_res: list[dict[str, Any]]) -> list[Any]:new_dt_boxes = []angle_boxes_list = []for text_box in dt_boxes:-if calculate_is_angle(text_box):angle_boxes_list.append(text_box)continue@@ -196,7 +205,7 @@ def update_det_boxes(dt_boxes, mfd_res):text_bbox = points_to_bbox(text_box)masks_list = []for mf_box in mfd_res:- mf_bbox = mf_box['bbox']+ mf_bbox = mf_box["bbox"]if _is_overlaps_y_exceeds_threshold(text_bbox, mf_bbox):masks_list.append([mf_bbox[0], mf_bbox[2]])text_x_range = [text_bbox[0], text_bbox[2]]@@ -212,7 +221,7 @@ def update_det_boxes(dt_boxes, mfd_res):return new_dt_boxes-def merge_overlapping_spans(spans):+def merge_overlapping_spans(spans: list[tuple[float, ...]]) -> list[tuple[float, ...]]:"""Merges overlapping spans on the same line.@@ -249,7 +258,7 @@ def merge_overlapping_spans(spans):return merged-def merge_det_boxes(dt_boxes):+def merge_det_boxes(dt_boxes: list[Any]) -> list[Any]:"""Merge detection boxes.@@ -272,7 +281,7 @@ def merge_det_boxes(dt_boxes):angle_boxes_list.append(text_box)continue- text_box_dict = {'bbox': text_bbox}+ text_box_dict = {"bbox": text_bbox}dt_boxes_dict_list.append(text_box_dict)# Merge adjacent text regions into lines@@ -283,7 +292,7 @@ def merge_det_boxes(dt_boxes):for line in lines:line_bbox_list = []for span in line:- line_bbox_list.append(span['bbox'])+ line_bbox_list.append(span["bbox"])# 计算整行的宽度和高度min_x = min(bbox[0] for bbox in line_bbox_list)@@ -295,7 +304,6 @@ def merge_det_boxes(dt_boxes):# 只有当行宽度超过高度4倍时才进行合并if line_width > line_height * LINE_WIDTH_TO_HEIGHT_RATIO_THRESHOLD:-# Merge overlapping text regions within the same linemerged_spans = merge_overlapping_spans(line_bbox_list)@@ -312,7 +320,7 @@ def merge_det_boxes(dt_boxes):return new_dt_boxes-def get_adjusted_mfdetrec_res(single_page_mfdetrec_res, useful_list):+def get_adjusted_mfdetrec_res(single_page_mfdetrec_res: list[dict[str, Any]], useful_list: list[int]) -> list[dict[str, Any]]:paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_list# Adjust the coordinates of the formula areaadjusted_mfdetrec_res = []@@ -327,19 +335,21 @@ def get_adjusted_mfdetrec_res(single_page_mfdetrec_res, useful_list):if any([x1 < 0, y1 < 0]) or any([x0 > new_width, y0 > new_height]):continueelse:- adjusted_mfdetrec_res.append({- "bbox": [x0, y0, x1, y1],- })+ adjusted_mfdetrec_res.append(+ {+ "bbox": [x0, y0, x1, y1],+ }+ )return adjusted_mfdetrec_resdef get_ocr_result_list(- ocr_res,- useful_list,- ocr_enable,- bgr_image,- lang,-):+ ocr_res: list[Any],+ useful_list: list[int],+ ocr_enable: bool,+ bgr_image: np.ndarray,+ lang: str,+) -> list[dict[str, Any]]:paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_listocr_result_list = []ori_im = bgr_image.copy()@@ -358,7 +368,7 @@ def get_ocr_result_list(text, score = "", 1if ocr_enable:- tmp_box = copy.deepcopy(np.array([p1, p2, p3, p4]).astype('float32'))+ tmp_box = copy.deepcopy(np.array([p1, p2, p3, p4]).astype("float32"))img_crop = get_rotate_crop_image_for_text_rec(ori_im, tmp_box)need_ocr_rec = True@@ -408,7 +418,7 @@ def get_ocr_result_list(return ocr_result_list-def calculate_is_angle(poly):+def calculate_is_angle(poly: list[Any]) -> bool:p1, p2, p3, p4 = polyheight = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2if 0.8 * height <= (p3[1] - p1[1]) <= 1.2 * height:@@ -417,15 +427,17 @@ def calculate_is_angle(poly):# logger.info((p3[1] - p1[1])/height)return True-def is_bbox_aligned_rect(points):++def is_bbox_aligned_rect(points: np.ndarray) -> bool:x_coords = points[:, 0]y_coords = points[:, 1]unique_x = np.unique(x_coords)unique_y = np.unique(y_coords)return len(unique_x) == 2 and len(unique_y) == 2-def get_rotate_crop_image(img, points):- '''++def get_rotate_crop_image(img: np.ndarray, points: np.ndarray) -> np.ndarray:+ """img_height, img_width = img.shape[0:2]left = int(np.min(points[:, 0]))right = int(np.max(points[:, 0]))@@ -434,7 +446,7 @@ def get_rotate_crop_image(img, points):img_crop = img[top:bottom, left:right, :].copy()points[:, 0] = points[:, 0] - leftpoints[:, 1] = points[:, 1] - top- '''+ """assert len(points) == 4, "shape of points must be 4*2"if is_bbox_aligned_rect(points):@@ -446,30 +458,22 @@ def get_rotate_crop_image(img, points):if new_img.shape[0] > 0 and new_img.shape[1] > 0:return new_img- img_crop_width = int(- max(- np.linalg.norm(points[0] - points[1]),- np.linalg.norm(points[2] - points[3])))- img_crop_height = int(- max(- np.linalg.norm(points[0] - points[3]),- np.linalg.norm(points[1] - points[2])))- pts_std = np.float32([[0, 0], [img_crop_width, 0],- [img_crop_width, img_crop_height],- [0, img_crop_height]])+ img_crop_width = int(max(np.linalg.norm(points[0] - points[1]), np.linalg.norm(points[2] - points[3])))+ img_crop_height = int(max(np.linalg.norm(points[0] - points[3]), np.linalg.norm(points[1] - points[2])))+ pts_std = np.float32([[0, 0], [img_crop_width, 0], [img_crop_width, img_crop_height], [0, img_crop_height]])M = cv2.getPerspectiveTransform(points, pts_std)dst_img = cv2.warpPerspective(- img,- M, (img_crop_width, img_crop_height),- borderMode=cv2.BORDER_REPLICATE,- flags=cv2.INTER_CUBIC)+ img, M, (img_crop_width, img_crop_height), borderMode=cv2.BORDER_REPLICATE, flags=cv2.INTER_CUBIC+ )dst_img_height, dst_img_width = dst_img.shape[0:2]if dst_img_height * 1.0 / dst_img_width >= TEXT_REC_ROTATE_RATIO:dst_img = np.rot90(dst_img)return dst_img-def rotate_vertical_crop_if_needed(crop_img, rotate_ratio=TEXT_REC_ROTATE_RATIO):+def rotate_vertical_crop_if_needed(+ crop_img: np.ndarray | None, rotate_ratio: float = TEXT_REC_ROTATE_RATIO+) -> np.ndarray | None:if crop_img is None or crop_img.size == 0:return crop_img@@ -482,6 +486,6 @@ def rotate_vertical_crop_if_needed(crop_img, rotate_ratio=TEXT_REC_ROTATE_RATIO)return crop_img-def get_rotate_crop_image_for_text_rec(img, points):+def get_rotate_crop_image_for_text_rec(img: np.ndarray, points: np.ndarray) -> np.ndarray | None:crop_img = get_rotate_crop_image(img, points)return rotate_vertical_crop_if_needed(crop_img)diff --git a/mineru/utils/office_rich_text.py b/mineru/utils/office_rich_text.pyindex 80e52579..05b43579 100644--- a/mineru/utils/office_rich_text.py+++ b/mineru/utils/office_rich_text.py@@ -2,7 +2,6 @@from dataclasses import dataclassfrom typing import Any, Optional-VISIBLE_SPACE_STYLES = {"underline", "emphasis", "strikethrough"}@@ -77,10 +76,7 @@ def has_non_visible_text_style(format_obj: Any) -> bool:"""判断格式是否只包含空白文本不可见的字形样式。"""if format_obj is None:return False- return bool(- getattr(format_obj, "bold", False)- or getattr(format_obj, "italic", False)- )+ return bool(getattr(format_obj, "bold", False) or getattr(format_obj, "italic", False))def normalize_format_for_text(@@ -88,7 +84,7 @@ def normalize_format_for_text(text: str,*,preserve_blank_non_visible_style: bool = False,-):+) -> Any:"""按文本内容规范 run 格式,避免空白 run 误把不可见样式带到输出。"""if format_obj is None:return None@@ -198,17 +194,9 @@ def _format_hyperlink_segments(group: list[OfficeRichTextSegment]) -> str:return ""hyperlink = group[0].hyperlinkif not is_valid_hyperlink_target(hyperlink):- return "".join(- format_text_tag(segment.text, _style_str(segment.style))- for segment in group- if segment.text- )+ return "".join(format_text_tag(segment.text, _style_str(segment.style)) for segment in group if segment.text)- text_tags = [- format_text_tag(segment.text, _style_str(segment.style), force_tag=True)- for segment in group- if segment.text- ]+ text_tags = [format_text_tag(segment.text, _style_str(segment.style), force_tag=True) for segment in group if segment.text]return f"<hyperlink>{''.join(text_tags)}<url>{hyperlink}</url></hyperlink>"@@ -325,9 +313,8 @@ def build_rich_text_from_segments(index += 1while index < len(normalized_segments):next_segment = normalized_segments[index]- if (- not is_valid_hyperlink_target(next_segment.hyperlink)- or str(next_segment.hyperlink) != str(segment.hyperlink)+ if not is_valid_hyperlink_target(next_segment.hyperlink) or str(next_segment.hyperlink) != str(+ segment.hyperlink):breakgroup.append(next_segment)@@ -364,11 +351,7 @@ def build_text_mappings_from_elements(index += 1while index < len(paragraph_elements):next_text, next_format, next_hyperlink = paragraph_elements[index]- if (- not next_text- or not is_valid_hyperlink_target(next_hyperlink)- or str(next_hyperlink) != str(hyperlink)- ):+ if not next_text or not is_valid_hyperlink_target(next_hyperlink) or str(next_hyperlink) != str(hyperlink):breakgroup.append((next_text, next_format, next_hyperlink))index += 1diff --git a/mineru/utils/os_env_config.py b/mineru/utils/os_env_config.pyindex cdd41fba..90f3dc23 100644--- a/mineru/utils/os_env_config.py+++ b/mineru/utils/os_env_config.py@@ -8,12 +8,12 @@ def get_op_num_threads(env_name: str) -> int:def get_load_images_timeout() -> int:- env_value = os.getenv('MINERU_PDF_RENDER_TIMEOUT', None)+ env_value = os.getenv("MINERU_PDF_RENDER_TIMEOUT", None)return get_value_from_string(env_value, 300)def get_load_images_threads() -> int:- env_value = os.getenv('MINERU_PDF_RENDER_THREADS', None)+ env_value = os.getenv("MINERU_PDF_RENDER_THREADS", None)return get_value_from_string(env_value, 3)@@ -28,9 +28,9 @@ def get_value_from_string(env_value: str, default_value: int) -> int:return default_value-if __name__ == '__main__':- print(get_value_from_string('1', -1))- print(get_value_from_string('0', -1))- print(get_value_from_string('-1', -1))- print(get_value_from_string('abc', -1))- print(get_load_images_timeout())\ No newline at end of file+if __name__ == "__main__":+ print(get_value_from_string("1", -1))+ print(get_value_from_string("0", -1))+ print(get_value_from_string("-1", -1))+ print(get_value_from_string("abc", -1))+ print(get_load_images_timeout())diff --git a/mineru/utils/pdf_classify.py b/mineru/utils/pdf_classify.pyindex 9abd758a..de6c5cd6 100644--- a/mineru/utils/pdf_classify.py+++ b/mineru/utils/pdf_classify.py@@ -1,13 +1,17 @@# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations+import refrom ctypes import byref, c_int, create_string_bufferfrom io import BytesIO+from typing import Anyimport pypdfium2 as pdfiumimport pypdfium2.raw as pdfium_cfrom loguru import loggerfrom pypdf import PdfReader-from mineru.utils.pdfium_guard import (++from .pdfium_guard import (close_pdfium_child,close_pdfium_document,open_pdfium_document,@@ -27,9 +31,7 @@ SUSPICIOUS_CJK_72XX_START = 0x7280SUSPICIOUS_CJK_72XX_END = 0x72DFSUSPICIOUS_CJK_72XX_COUNT_THRESHOLD = 30SUSPICIOUS_CJK_72XX_CJK_RATIO_THRESHOLD = 0.026-SUSPICIOUS_CJK_72XX_WHITELIST = set(- "犀犁犄犊犒犟犬犯状犷犹狂狄狈狐狗狙狞"-)+SUSPICIOUS_CJK_72XX_WHITELIST = set("犀犁犄犊犒犟犬犯状犷犹狂狄狈狐狗狙狞")ASCII_PUNCT_CHARS = set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")ASCII_PUNCT_RUN_MIN_LENGTH = 4SUSPICIOUS_ASCII_PUNCT_MIN_TEXT_CHARS = 100@@ -42,16 +44,10 @@ _PRIVATE_USE_AREA_END = 0xF8FFdef _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- )+ return (0 <= unicode_code < 32 or 127 <= unicode_code <= 159) and unicode_code not in _ALLOWED_CONTROL_CODES-def classify(pdf_bytes):+def classify(pdf_bytes: bytes) -> str:"""Fast PDF classification path.@@ -86,19 +82,12 @@ def classify(pdf_bytes):return "ocr"text_samples = _collect_pdfium_text_samples(pdf, page_indices)- avg_cleaned_chars_per_page = _get_avg_cleaned_chars_per_page_from_samples(- text_samples- )+ 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"- unicode_map_error_signal = _get_unicode_map_error_signal_from_samples(- text_samples- )- if (- unicode_map_error_signal["unicode_map_error_ratio"]- >= UNICODE_MAP_ERROR_RATIO_THRESHOLD- ):+ unicode_map_error_signal = _get_unicode_map_error_signal_from_samples(text_samples)+ if unicode_map_error_signal["unicode_map_error_ratio"] >= UNICODE_MAP_ERROR_RATIO_THRESHOLD:logger.debug("Classify PDF as OCR due to PDFium Unicode map errors: "f"errors={unicode_map_error_signal['unicode_map_error_count']}, "@@ -127,18 +116,13 @@ def classify(pdf_bytes):total_chars = text_quality_signal["total_chars"]abnormal_ratio = text_quality_signal["abnormal_ratio"]- if (- total_chars >= TEXT_QUALITY_MIN_CHARS- and abnormal_ratio >= TEXT_QUALITY_BAD_THRESHOLD- ):+ if total_chars >= TEXT_QUALITY_MIN_CHARS and abnormal_ratio >= TEXT_QUALITY_BAD_THRESHOLD:return "ocr"u72xx_signal = _get_u72xx_text_signal_from_samples(text_samples)if (- u72xx_signal["u72xx_count"]- >= SUSPICIOUS_CJK_72XX_COUNT_THRESHOLD- and u72xx_signal["u72xx_cjk_ratio"]- >= SUSPICIOUS_CJK_72XX_CJK_RATIO_THRESHOLD+ u72xx_signal["u72xx_count"] >= SUSPICIOUS_CJK_72XX_COUNT_THRESHOLD+ and u72xx_signal["u72xx_cjk_ratio"] >= SUSPICIOUS_CJK_72XX_CJK_RATIO_THRESHOLD):logger.debug("Classify PDF as OCR due to suspicious U+7280-U+72DF text: "@@ -147,9 +131,7 @@ def classify(pdf_bytes):)return "ocr"- ascii_punct_signal = _get_sampled_ascii_punct_signal_from_samples(- text_samples- )+ ascii_punct_signal = _get_sampled_ascii_punct_signal_from_samples(text_samples)if ascii_punct_signal["triggered"]:logger.debug("Classify PDF as OCR due to suspicious sampled-page ASCII punctuation "@@ -161,10 +143,7 @@ def classify(pdf_bytes):)return "ocr"- if (- get_high_image_coverage_ratio_pdfium(pdf, page_indices)- >= HIGH_IMAGE_COVERAGE_THRESHOLD- ):+ if get_high_image_coverage_ratio_pdfium(pdf, page_indices) >= HIGH_IMAGE_COVERAGE_THRESHOLD:return "ocr"except Exception as e:@@ -177,7 +156,7 @@ def classify(pdf_bytes):return "txt"-def get_sample_page_indices(page_count: int, max_pages: int = MAX_SAMPLE_PAGES):+def get_sample_page_indices(page_count: int, max_pages: int = MAX_SAMPLE_PAGES) -> list[int]:if page_count <= 0 or max_pages <= 0:return []@@ -209,10 +188,10 @@ def get_sample_page_indices(page_count: int, max_pages: int = MAX_SAMPLE_PAGES):def get_extreme_aspect_ratio_page_pdfium(- pdf_doc,- page_indices,+ pdf_doc: Any,+ page_indices: list[int],max_page_aspect_ratio: float = MAX_PAGE_ASPECT_RATIO,-):+) -> tuple[Any, Any]:with pdfium_guard():for page_index in page_indices:page = None@@ -231,7 +210,7 @@ def get_extreme_aspect_ratio_page_pdfium(return None, None-def _collect_pdfium_text_sample_from_page(page_index, page):+def _collect_pdfium_text_sample_from_page(page_index: int, page: Any) -> dict[str, Any]:"""从单页 PDFium 对象提取纯 Python 文本统计,并在调用方释放子对象。"""text_page = Nonetry:@@ -259,9 +238,7 @@ def _collect_pdfium_text_sample_from_page(page_index, page):if pdfium_c.FPDFText_HasUnicodeMapError(text_page, char_index):unicode_map_error_count += 1- font_name = _normalize_pdf_font_name(- _get_pdfium_char_font_name(text_page, char_index)- )+ font_name = _normalize_pdf_font_name(_get_pdfium_char_font_name(text_page, char_index))if font_name:font_name_counts[font_name] = font_name_counts.get(font_name, 0) + 1@@ -281,7 +258,7 @@ def _collect_pdfium_text_sample_from_page(page_index, page):close_pdfium_child(text_page)-def _collect_pdfium_text_samples(pdf_doc, page_indices):+def _collect_pdfium_text_samples(pdf_doc: Any, page_indices: list[int]) -> list[dict[str, Any]]:"""一次性收集抽样页文本统计,返回纯 Python 数据,避免缓存 PDFium 子对象。"""text_samples = []@@ -290,16 +267,14 @@ def _collect_pdfium_text_samples(pdf_doc, page_indices):page = Nonetry:page = pdf_doc[page_index]- text_samples.append(- _collect_pdfium_text_sample_from_page(page_index, page)- )+ text_samples.append(_collect_pdfium_text_sample_from_page(page_index, page))finally:close_pdfium_child(page)return text_samples-def _get_avg_cleaned_chars_per_page_from_samples(text_samples):+def _get_avg_cleaned_chars_per_page_from_samples(text_samples: list[dict[str, Any]]) -> float:"""基于已缓存的抽样页文本计算平均有效字符数。"""cleaned_total_chars = 0@@ -311,12 +286,12 @@ def _get_avg_cleaned_chars_per_page_from_samples(text_samples):return cleaned_total_chars / len(text_samples)-def get_avg_cleaned_chars_per_page_pdfium(pdf_doc, page_indices):+def get_avg_cleaned_chars_per_page_pdfium(pdf_doc: Any, 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):+def _get_text_quality_signal_from_samples(text_samples: list[dict[str, Any]]) -> dict[str, Any]:"""基于已缓存的抽样页字符计数统计异常字符质量信号。"""total_chars = 0null_char_count = 0@@ -331,12 +306,7 @@ def _get_text_quality_signal_from_samples(text_samples):control_char_count += text_sample["control_char_count"]private_use_char_count += text_sample["private_use_char_count"]- abnormal_chars = (- null_char_count- + replacement_char_count- + control_char_count- + private_use_char_count- )+ abnormal_chars = null_char_count + replacement_char_count + control_char_count + private_use_char_countabnormal_ratio = 0.0if total_chars > 0:@@ -352,12 +322,12 @@ def _get_text_quality_signal_from_samples(text_samples):}-def get_text_quality_signal_pdfium(pdf_doc, page_indices):+def get_text_quality_signal_pdfium(pdf_doc: Any, 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):+def _get_unicode_map_error_signal_from_samples(text_samples: list[dict[str, Any]]) -> dict[str, Any]:"""统计 PDFium 字符级 Unicode 映射失败比例,用于识别无法可靠抽取的乱码文本。"""total_chars = 0unicode_map_error_count = 0@@ -377,14 +347,14 @@ def _get_unicode_map_error_signal_from_samples(text_samples):}-def _normalize_pdf_font_name(font_name) -> str:+def _normalize_pdf_font_name(font_name: Any) -> str:"""规范化 PDF 字体名,统一 pypdf 的 NameObject 和 PDFium 返回值格式。"""if font_name is None:return ""return str(font_name).strip().lstrip("/")-def _get_pdfium_char_font_name(text_page, char_index: int) -> str:+def _get_pdfium_char_font_name(text_page: Any, char_index: int) -> str:"""读取 PDFium 字符级字体名,用于统计可疑 CID 字体的实际使用比例。"""flags = c_int()buffer_length = pdfium_c.FPDFText_GetFontInfo(@@ -411,7 +381,9 @@ def _get_pdfium_char_font_name(text_page, char_index: int) -> str:return font_name_buffer.value.decode("utf-8", errors="ignore")-def _get_cid_font_usage_signal_from_samples(text_samples, cid_font_signal):+def _get_cid_font_usage_signal_from_samples(+ text_samples: list[dict[str, Any]], cid_font_signal: dict[str, Any]+) -> dict[str, Any]:"""基于 PDFium 字符级字体名统计可疑 CID 字体在抽样页中的真实使用比例。"""best_signal = {"triggered": False,@@ -427,10 +399,7 @@ def _get_cid_font_usage_signal_from_samples(text_samples, cid_font_signal):page_fonts = cid_font_signal.get("page_fonts") or {}for text_sample in text_samples:page_index = text_sample.get("page_index")- cid_font_names = {- _normalize_pdf_font_name(font_name)- for font_name in page_fonts.get(page_index, set())- }+ cid_font_names = {_normalize_pdf_font_name(font_name) for font_name in page_fonts.get(page_index, set())}cid_font_names.discard("")if not cid_font_names:continue@@ -441,9 +410,7 @@ def _get_cid_font_usage_signal_from_samples(text_samples, cid_font_signal):font_name_counts = text_sample.get("font_name_counts") or {}matched_font_names = cid_font_names.intersection(font_name_counts)- cid_font_char_count = sum(- font_name_counts[font_name] for font_name in matched_font_names- )+ cid_font_char_count = sum(font_name_counts[font_name] for font_name in matched_font_names)cid_font_usage_ratio = cid_font_char_count / total_charssignal = {@@ -454,10 +421,7 @@ def _get_cid_font_usage_signal_from_samples(text_samples, cid_font_signal):"total_chars": total_chars,"cid_font_usage_ratio": cid_font_usage_ratio,}- if (- cid_font_char_count >= CID_FONT_USAGE_COUNT_THRESHOLD- and cid_font_usage_ratio >= CID_FONT_USAGE_RATIO_THRESHOLD- ):+ if cid_font_char_count >= CID_FONT_USAGE_COUNT_THRESHOLD and cid_font_usage_ratio >= CID_FONT_USAGE_RATIO_THRESHOLD:signal["triggered"] = Truereturn signal@@ -473,7 +437,7 @@ def _get_cid_font_usage_signal_from_samples(text_samples, cid_font_signal):return best_signal-def _get_u72xx_text_signal_from_samples(text_samples):+def _get_u72xx_text_signal_from_samples(text_samples: list[dict[str, Any]]) -> dict[str, Any]:"""基于已缓存的抽样页文本统计扣除常用字后的 U+7280-U+72DF 字符占比。"""cjk_chars = 0u72xx_count = 0@@ -484,9 +448,7 @@ def _get_u72xx_text_signal_from_samples(text_samples):if 0x4E00 <= unicode_code <= 0x9FFF:cjk_chars += 1if (- SUSPICIOUS_CJK_72XX_START- <= unicode_code- <= SUSPICIOUS_CJK_72XX_END+ SUSPICIOUS_CJK_72XX_START <= unicode_code <= SUSPICIOUS_CJK_72XX_ENDand char not in SUSPICIOUS_CJK_72XX_WHITELIST):u72xx_count += 1@@ -502,7 +464,7 @@ def _get_u72xx_text_signal_from_samples(text_samples):}-def get_u72xx_text_signal_pdfium(pdf_doc, page_indices):+def get_u72xx_text_signal_pdfium(pdf_doc: Any, 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)@@ -528,7 +490,7 @@ def _count_ascii_punct_run_chars(text: str) -> int:return run_chars-def _get_sampled_ascii_punct_signal_from_samples(text_samples):+def _get_sampled_ascii_punct_signal_from_samples(text_samples: list[dict[str, Any]]) -> dict[str, Any]:"""检查所有抽样页的 ASCII 标点密集度,用于识别无 ToUnicode 的乱码文本。"""best_signal = {"triggered": False,@@ -544,9 +506,7 @@ def _get_sampled_ascii_punct_signal_from_samples(text_samples):page_index = text_sample.get("page_index")cleaned_text = text_sample["cleaned_text"]cleaned_text_chars = len(cleaned_text)- ascii_punct_count = sum(- 1 for char in cleaned_text if char in ASCII_PUNCT_CHARS- )+ ascii_punct_count = sum(1 for char in cleaned_text if char in ASCII_PUNCT_CHARS)ascii_punct_run_chars = _count_ascii_punct_run_chars(cleaned_text)ascii_punct_ratio = 0.0@@ -587,7 +547,7 @@ def _get_sampled_ascii_punct_signal_from_samples(text_samples):return best_signal-def get_cid_font_signal_pypdf(pdf_bytes, page_indices):+def get_cid_font_signal_pypdf(pdf_bytes: bytes, page_indices: list[int]) -> dict[str, Any]:"""收集抽样页中无 ToUnicode 的 Identity CID 字体资源,供后续按实际字符使用量判定。"""reader = PdfReader(BytesIO(pdf_bytes))page_fonts = {}@@ -619,9 +579,7 @@ def get_cid_font_signal_pypdf(pdf_bytes, page_indices):and not has_to_unicode):font_name = font.get("/BaseFont") or font_key- page_fonts.setdefault(page_index, set()).add(- _normalize_pdf_font_name(font_name)- )+ page_fonts.setdefault(page_index, set()).add(_normalize_pdf_font_name(font_name))return {"triggered": bool(page_fonts),@@ -629,18 +587,18 @@ def get_cid_font_signal_pypdf(pdf_bytes, page_indices):}-def detect_cid_font_signal_pypdf(pdf_bytes, page_indices):+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):+def _resolve_pdf_object(obj: Any) -> Any:if hasattr(obj, "get_object"):return obj.get_object()return obj-def get_high_image_coverage_ratio_pdfium(pdf_doc, page_indices):+def get_high_image_coverage_ratio_pdfium(pdf_doc: Any, page_indices: list[int]) -> float:high_image_coverage_pages = 0with pdfium_guard():@@ -649,23 +607,17 @@ def get_high_image_coverage_ratio_pdfium(pdf_doc, page_indices):try:page = pdf_doc[page_index]page_bbox = page.get_bbox()- page_area = abs(- (page_bbox[2] - page_bbox[0]) * (page_bbox[3] - page_bbox[1])- )+ page_area = abs((page_bbox[2] - page_bbox[0]) * (page_bbox[3] - page_bbox[1]))image_area = 0.0- for page_object in page.get_objects(- filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE], max_depth=3- ):+ for page_object in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE], max_depth=3):try:left, bottom, right, top = page_object.get_pos()image_area += max(0.0, right - left) * max(0.0, top - bottom)finally:close_pdfium_child(page_object)- coverage_ratio = (- min(image_area / page_area, 1.0) if page_area > 0 else 0.0- )+ coverage_ratio = min(image_area / page_area, 1.0) if page_area > 0 else 0.0if coverage_ratio >= HIGH_IMAGE_COVERAGE_THRESHOLD:high_image_coverage_pages += 1finally:diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.pyindex 31df7e8a..486e3395 100644--- a/mineru/utils/pdf_document.py+++ b/mineru/utils/pdf_document.py@@ -1,15 +1,25 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations+import asyncioimport os-from typing import TYPE_CHECKING+import pypdfium2 as pdfiumfrom 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.types import PageInfo+from ..types import PageInfo+from .draw_bbox import draw_layout_bbox, draw_span_bbox+from .pdf_classify import classify, get_text_quality_signal_pdfium+from .pdf_classify import extract_pages as _extract_pages+from .pdf_image_tools import get_crop_img, image_to_bytes, images_bytes_to_pdf_bytes+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,+ pdfium_guard,+ rewrite_pdf_bytes_with_pdfium,+)class PDFDocument:@@ -29,8 +39,6 @@ class PDFDocument:@staticmethoddef 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))# ------------------------------------------------------------------ #@@ -86,22 +94,14 @@ class PDFDocument:finally:bitmap.close()- def render_pages(- self, start: int = 0, end: int | None = None, *, scale: int = 2- ) -> list[Image.Image]:+ 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 - 1return [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-+ async def render_pages_async(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 - 1tasks = [self.render_page_async(i, scale=scale) for i in range(start, end + 1)]return await asyncio.gather(*tasks)@@ -113,8 +113,6 @@ class PDFDocument:*,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")@@ -124,14 +122,10 @@ class PDFDocument:# ------------------------------------------------------------------ #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)+ 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"])@@ -140,13 +134,9 @@ class PDFDocument:# ------------------------------------------------------------------ #def classify(self) -> str:- from .pdf_classify import classify as _classify-- return _classify(self._pdf_bytes)+ 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)@@ -156,8 +146,6 @@ class PDFDocument:# ------------------------------------------------------------------ #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,@@ -166,8 +154,6 @@ class PDFDocument: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)@@ -182,15 +168,11 @@ class PDFDocument:# ------------------------------------------------------------------ #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)@@ -199,12 +181,10 @@ class PDFDocument:# Internal# ------------------------------------------------------------------ #- def _ensure_open(self):+ def _ensure_open(self) -> pdfium.PdfDocument: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):+ def _get_page(self, page_idx: int) -> pdfium.PdfPage:return self._ensure_open()[page_idx]diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.pyindex 8ffa934a..0fc26004 100644--- a/mineru/utils/pdf_image_tools.py+++ b/mineru/utils/pdf_image_tools.py@@ -1,4 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations+import asyncioimport atexitimport multiprocessing@@ -8,21 +10,22 @@ import timefrom concurrent.futures import ALL_COMPLETED, ProcessPoolExecutor, waitfrom concurrent.futures.process import BrokenProcessPoolfrom io import BytesIO+from typing import Any, Callableimport numpy as npimport pypdfium2 as pdfiumfrom loguru import loggerfrom PIL import Image, ImageOps-from mineru.data.data_reader_writer import FileBasedDataWriter-from mineru.utils.bbox_utils import normalize_to_int_bbox-from mineru.utils.check_sys_env import is_windows_environment-from mineru.utils.enum_class import ImageType-from mineru.utils.hash_utils import str_sha256-from mineru.utils.os_env_config import get_load_images_threads, get_load_images_timeout-from mineru.utils.pdf_page_id import get_end_page_id-from mineru.utils.pdf_reader import image_to_b64str, image_to_bytes, page_to_image-from mineru.utils.pdfium_guard import (+from ..data.data_reader_writer import FileBasedDataWriter+from .bbox_utils import normalize_to_int_bbox+from .check_sys_env import is_windows_environment+from .enum_class import ImageType+from .hash_utils import str_sha256+from .os_env_config import get_load_images_threads, get_load_images_timeout+from .pdf_page_id import get_end_page_id+from .pdf_reader import image_to_b64str, image_to_bytes, page_to_image+from .pdfium_guard import (close_pdfium_child,close_pdfium_document,get_pdfium_document_page_count,@@ -47,9 +50,9 @@ _pdf_render_spawn_submit_count = 0def pdf_page_to_image(page: pdfium.PdfPage,- dpi=DEFAULT_PDF_IMAGE_DPI,- image_type=ImageType.PIL,-) -> dict:+ dpi: int = DEFAULT_PDF_IMAGE_DPI,+ image_type: ImageType = ImageType.PIL,+) -> dict[str, Any]:"""Convert pdfium.PdfDocument to image, Then convert the image to base64.Args:@@ -75,12 +78,14 @@ def pdf_page_to_image(return image_dict-def _load_images_from_pdf_worker(pdf_bytes, dpi, start_page_id, end_page_id, image_type):+def _load_images_from_pdf_worker(+ pdf_bytes: bytes, dpi: int, start_page_id: int, end_page_id: int, image_type: ImageType+) -> list[dict[str, Any]]:"""用于进程池的包装函数"""return load_images_from_pdf_core(pdf_bytes, dpi, start_page_id, end_page_id, image_type)-def _close_image_dicts(images_list) -> None:+def _close_image_dicts(images_list: list[dict[str, Any]] | None) -> None:"""关闭 image dict 中的 PIL 图片,供异常清理路径释放已生成的图像资源。"""for image_dict in images_list or []:pil_img = image_dict.get("img_pil")@@ -92,7 +97,7 @@ def _close_image_dicts(images_list) -> None:pass-def _calculate_render_process_count(total_pages: int, threads: int, cpu_count=None) -> int:+def _calculate_render_process_count(total_pages: int, threads: int, cpu_count: int | None = None) -> int:requested_threads = max(1, threads)available_cpus = max(1, cpu_count if cpu_count is not None else (os.cpu_count() or 1))page_limited_threads = max(1, total_pages // MIN_PAGES_PER_RENDER_PROCESS)@@ -127,14 +132,14 @@ def _get_render_process_plan(start_page_id: int,end_page_id: int,threads: int,- cpu_count=None,+ cpu_count: int | None = None,) -> tuple[int, list[tuple[int, int]]]:total_pages = end_page_id - start_page_id + 1actual_threads = _calculate_render_process_count(total_pages, threads, cpu_count)return actual_threads, _build_render_page_ranges(start_page_id, end_page_id, actual_threads)-def _get_pdf_render_pool_capacity(cpu_count=None) -> int:+def _get_pdf_render_pool_capacity(cpu_count: int | None = None) -> int:available_cpus = max(1, cpu_count if cpu_count is not None else (os.cpu_count() or 1))configured_threads = max(1, get_load_images_threads())return min(@@ -172,10 +177,10 @@ def _is_pdf_render_pool_still_spawning_workers(executor: ProcessPoolExecutor) ->def _submit_pdf_render_task(executor: ProcessPoolExecutor,- fn,- *args,- **kwargs,-):+ fn: Callable[..., Any],+ *args: Any, # noqa: ANN401+ **kwargs: Any, # noqa: ANN401+) -> Any: # noqa: ANN401"""提交 PDF 渲染任务;冷启动补 worker 时串行 submit 并错开 100ms。"""global _pdf_render_spawn_submit_executor_id, _pdf_render_spawn_submit_count@@ -252,13 +257,13 @@ atexit.register(shutdown_pdf_render_executor)def _load_images_from_pdf_bytes_range(pdf_bytes: bytes,- dpi=DEFAULT_PDF_IMAGE_DPI,- start_page_id=0,- end_page_id=0,- image_type=ImageType.PIL,- timeout=None,- threads=None,-):+ dpi: int = DEFAULT_PDF_IMAGE_DPI,+ start_page_id: int = 0,+ end_page_id: int = 0,+ image_type: ImageType = ImageType.PIL,+ timeout: int | None = None,+ threads: int | None = None,+) -> list[dict[str, Any]]:if end_page_id < start_page_id:return []@@ -333,13 +338,13 @@ def _load_images_from_pdf_bytes_range(async def aio_load_images_from_pdf_bytes_range(pdf_bytes: bytes,- dpi=DEFAULT_PDF_IMAGE_DPI,- start_page_id=0,- end_page_id=0,- image_type=ImageType.PIL,- timeout=None,- threads=None,-):+ dpi: int = DEFAULT_PDF_IMAGE_DPI,+ start_page_id: int = 0,+ end_page_id: int = 0,+ image_type: ImageType = 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,@@ -352,7 +357,7 @@ async def aio_load_images_from_pdf_bytes_range()-def _terminate_executor_processes(executor):+def _terminate_executor_processes(executor: ProcessPoolExecutor) -> None:"""强制终止 ProcessPoolExecutor 中的所有子进程"""# executor.shutdown() 后 _processes 会被置空,重复回收时直接视为无进程。process_map = getattr(executor, "_processes", None) or {}@@ -401,11 +406,11 @@ def _terminate_executor_processes(executor):def load_images_from_pdf_core(pdf_bytes: bytes,- dpi=DEFAULT_PDF_IMAGE_DPI,- start_page_id=0,- end_page_id=None,- image_type=ImageType.PIL, # PIL or BASE64-):+ dpi: int = DEFAULT_PDF_IMAGE_DPI,+ start_page_id: int = 0,+ end_page_id: int | None = None,+ image_type: ImageType = ImageType.PIL, # PIL or BASE64+) -> list[dict[str, Any]]:images_list = []pdf_doc = Nonetry:@@ -431,14 +436,14 @@ def load_images_from_pdf_core(def load_images_from_pdf_doc(pdf_doc: pdfium.PdfDocument,- dpi=DEFAULT_PDF_IMAGE_DPI,- start_page_id=0,- end_page_id=None,- image_type=ImageType.PIL,+ dpi: int = DEFAULT_PDF_IMAGE_DPI,+ start_page_id: int = 0,+ end_page_id: int | None = None,+ image_type: ImageType = ImageType.PIL,pdf_bytes: bytes | None = None,- timeout=None,- threads=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 = get_end_page_id(end_page_id, pdf_page_num)@@ -468,13 +473,13 @@ def load_images_from_pdf_doc(def cut_image(- bbox: tuple,+ bbox: tuple[float, float, float, float],page_num: int,- page_pil_img,- return_path,+ page_pil_img: Image.Image,+ return_path: str | None,image_writer: FileBasedDataWriter,- scale=2,-):+ scale: int = 2,+) -> str:"""从第page_num页的page中,根据bbox进行裁剪出一张jpg图片,返回图片路径 save_path:需要同时支持s3和本地,图片存放在save_path下,文件名是:{page_num}_{bbox[0]}_{bbox[1]}_{bbox[2]}_{bbox[3]}.jpg , bbox内数字取整。"""@@ -497,14 +502,16 @@ def cut_image(return img_hash256_path-def get_crop_img(bbox: tuple[float, float, float, float], pil_img: Image.Image, scale: float = 2.0):+def get_crop_img(bbox: tuple[float, float, float, float], pil_img: Image.Image, scale: float = 2.0) -> Image.Image:scale_bbox = normalize_to_int_bbox([float(v) * scale for v in bbox])if scale_bbox is None:return pil_img.crop((0, 0, 0, 0))return pil_img.crop(tuple(scale_bbox))-def get_crop_np_img(bbox: tuple, input_img, scale: float = 2.0):+def get_crop_np_img(+ bbox: tuple[float, float, float, float], input_img: Image.Image | np.ndarray, scale: float = 2.0+) -> np.ndarray:if isinstance(input_img, Image.Image):np_img = np.asarray(input_img)elif isinstance(input_img, np.ndarray):@@ -523,7 +530,7 @@ def get_crop_np_img(bbox: tuple, input_img, scale: float = 2.0):return np_img[scale_bbox[1] : scale_bbox[3], scale_bbox[0] : scale_bbox[2]]-def images_bytes_to_pdf_bytes(image_bytes):+def images_bytes_to_pdf_bytes(image_bytes: bytes) -> bytes:# 内存缓冲区pdf_buffer = BytesIO()diff --git a/mineru/utils/pdf_page_id.py b/mineru/utils/pdf_page_id.pyindex 5471297f..cca3e142 100644--- a/mineru/utils/pdf_page_id.py+++ b/mineru/utils/pdf_page_id.py@@ -2,7 +2,7 @@from loguru import logger-def get_end_page_id(end_page_id, pdf_page_num):+def get_end_page_id(end_page_id: int | None, pdf_page_num: int) -> int:end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else pdf_page_num - 1if end_page_id > pdf_page_num - 1:logger.debug("end_page_id is out of range, use images length")diff --git a/mineru/utils/pdf_text_tool.py b/mineru/utils/pdf_text_tool.pyindex 7cb495fd..f08bcf37 100644--- a/mineru/utils/pdf_text_tool.py+++ b/mineru/utils/pdf_text_tool.py@@ -1,12 +1,12 @@# Copyright (c) Opendatalab. All rights reserved.import math-from typing import List+from typing import Any, Listimport pypdfium2 as pdfiumfrom pdftext.pdf.chars import deduplicate_chars, get_charsfrom pdftext.pdf.pages import assign_scripts, get_blocks, get_lines, get_spans-from mineru.utils.pdfium_guard import close_pdfium_child, pdfium_guard+from .pdfium_guard import close_pdfium_child, pdfium_guarddef get_page(@@ -14,7 +14,7 @@ def get_page(quote_loosebox: bool = True,superscript_height_threshold: float = 0.7,line_distance_threshold: float = 0.1,-) -> dict:+) -> dict[str, Any]:page_chars = get_page_chars(page, quote_loosebox=quote_loosebox)lines = get_lines_from_chars(page_chars["chars"],@@ -34,10 +34,10 @@ def get_page(def get_page_chars(page: pdfium.PdfPage,- textpage=None,+ textpage: Any = None,quote_loosebox: bool = True,page_char_count: int | None = None,-) -> dict:+) -> dict[str, Any]:"""轻量读取页面字符坐标,供只需要 char 级信息的路径复用。"""owns_textpage = textpage is Nonetry:@@ -57,9 +57,7 @@ def get_page_chars(if page_char_count is None:page_char_count = textpage.count_chars()- chars = deduplicate_chars(- get_chars(textpage, page_bbox, page_rotation, quote_loosebox)- )+ chars = deduplicate_chars(get_chars(textpage, page_bbox, page_rotation, quote_loosebox))finally:if owns_textpage:close_pdfium_child(textpage)@@ -75,10 +73,10 @@ def get_page_chars(def get_lines_from_chars(- 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,diff --git a/mineru/utils/pdfium_guard.py b/mineru/utils/pdfium_guard.pyindex b3f83ea1..07d7f607 100644--- a/mineru/utils/pdfium_guard.py+++ b/mineru/utils/pdfium_guard.py@@ -28,19 +28,19 @@ def open_pdfium_document(return opener(*args, **kwargs)-def get_pdfium_document_page_count(pdf_doc) -> int:+def get_pdfium_document_page_count(pdf_doc: Any) -> int:with pdfium_guard():return len(pdf_doc)-def close_pdfium_document(pdf_doc) -> None:+def close_pdfium_document(pdf_doc: Any) -> None:if pdf_doc is None:returnwith pdfium_guard():pdf_doc.close()-def close_pdfium_child(pdfium_obj) -> None:+def close_pdfium_child(pdfium_obj: Any) -> None:"""显式关闭 PDFium 子对象,避免依赖 weakref/finalizer 延迟释放 native 资源。"""if pdfium_obj is None:returndiff --git a/mineru/utils/span_block_fix.py b/mineru/utils/span_block_fix.pyindex c57211e0..4e1f9a2d 100644--- a/mineru/utils/span_block_fix.py+++ b/mineru/utils/span_block_fix.py@@ -1,17 +1,19 @@# Copyright (c) Opendatalab. All rights reserved.-from mineru.utils.enum_class import ContentType-from mineru.utils.ocr_utils import _is_overlaps_y_exceeds_threshold, _is_overlaps_x_exceeds_threshold+from typing import Any++from .enum_class import ContentType+from .ocr_utils import _is_overlaps_x_exceeds_threshold, _is_overlaps_y_exceeds_thresholdVERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2VERTICAL_SPAN_IN_BLOCK_THRESHOLD = 0.8-def is_vertical_text_block_by_spans(spans):+def is_vertical_text_block_by_spans(spans: list[dict[str, Any]]) -> bool:"""根据块内文本 span 的高宽比判断文本块是否更像竖排文本。"""valid_span_count = 0vertical_span_count = 0for span in spans:- bbox = span.get('bbox')+ bbox = span.get("bbox")if not bbox or len(bbox) < 4:continue@@ -30,51 +32,47 @@ def is_vertical_text_block_by_spans(spans):return vertical_span_count / valid_span_count > VERTICAL_SPAN_IN_BLOCK_THRESHOLD-def fix_text_block(block):+def fix_text_block(block: dict[str, Any]) -> dict[str, Any]:# 文本block中的公式span都应该转换成行内type- for span in block['spans']:- if span['type'] == ContentType.INTERLINE_EQUATION:- span['type'] = ContentType.INLINE_EQUATION+ for span in block["spans"]:+ if span["type"] == ContentType.INTERLINE_EQUATION:+ span["type"] = ContentType.INLINE_EQUATION- if is_vertical_text_block_by_spans(block['spans']):+ if is_vertical_text_block_by_spans(block["spans"]):# 如果是纵向文本块,则按纵向lines处理- block_lines = merge_spans_to_vertical_line(block['spans'])+ block_lines = merge_spans_to_vertical_line(block["spans"])sort_block_lines = vertical_line_sort_spans_from_top_to_bottom(block_lines)else:- block_lines = merge_spans_to_line(block['spans'])+ block_lines = merge_spans_to_line(block["spans"])sort_block_lines = line_sort_spans_by_left_to_right(block_lines)- block['lines'] = sort_block_lines- del block['spans']+ block["lines"] = sort_block_lines+ del block["spans"]return block-def merge_spans_to_line(spans, threshold=0.6):+def merge_spans_to_line(spans: list[dict[str, Any]], threshold: float = 0.6) -> list[list[dict[str, Any]]]:if len(spans) == 0:return []else:# 按照y0坐标排序- spans.sort(key=lambda span: span['bbox'][1])+ spans.sort(key=lambda span: span["bbox"][1])lines = []current_line = [spans[0]]for span in spans[1:]:# 如果当前的span类型为"interline_equation" 或者 当前行中已经有"interline_equation"# image和table类型,同上- if span['type'] in [- ContentType.INTERLINE_EQUATION, ContentType.IMAGE,- ContentType.TABLE- ] or any(s['type'] in [- ContentType.INTERLINE_EQUATION, ContentType.IMAGE,- ContentType.TABLE- ] for s in current_line):+ if span["type"] in [ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE] or any(+ s["type"] in [ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE] for s in current_line+ ):# 则开始新行lines.append(current_line)current_line = [span]continue# 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行- if _is_overlaps_y_exceeds_threshold(span['bbox'], current_line[-1]['bbox'], threshold):+ if _is_overlaps_y_exceeds_threshold(span["bbox"], current_line[-1]["bbox"], threshold):current_line.append(span)else:# 否则,开始新行@@ -88,32 +86,28 @@ def merge_spans_to_line(spans, threshold=0.6):return lines-def merge_spans_to_vertical_line(spans, threshold=0.6):+def merge_spans_to_vertical_line(spans: list[dict[str, Any]], threshold: float = 0.6) -> list[list[dict[str, Any]]]:"""将纵向文本的spans合并成纵向lines(从右向左阅读)"""if len(spans) == 0:return []else:# 按照x2坐标从大到小排序(从右向左)- spans.sort(key=lambda span: span['bbox'][2], reverse=True)+ spans.sort(key=lambda span: span["bbox"][2], reverse=True)vertical_lines = []current_line = [spans[0]]for span in spans[1:]:# 特殊类型元素单独成列- if span['type'] in [- ContentType.INTERLINE_EQUATION, ContentType.IMAGE,- ContentType.TABLE- ] or any(s['type'] in [- ContentType.INTERLINE_EQUATION, ContentType.IMAGE,- ContentType.TABLE- ] for s in current_line):+ if span["type"] in [ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE] or any(+ s["type"] in [ContentType.INTERLINE_EQUATION, ContentType.IMAGE, ContentType.TABLE] for s in current_line+ ):vertical_lines.append(current_line)current_line = [span]continue# 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行- if _is_overlaps_x_exceeds_threshold(span['bbox'], current_line[-1]['bbox'], threshold):+ if _is_overlaps_x_exceeds_threshold(span["bbox"], current_line[-1]["bbox"], threshold):current_line.append(span)else:vertical_lines.append(current_line)@@ -127,41 +121,45 @@ def merge_spans_to_vertical_line(spans, threshold=0.6):# 将每一个line中的span从左到右排序-def line_sort_spans_by_left_to_right(lines):+def line_sort_spans_by_left_to_right(lines: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:line_objects = []for line in lines:# 按照x0坐标排序- line.sort(key=lambda span: span['bbox'][0])+ line.sort(key=lambda span: span["bbox"][0])line_bbox = [- min(span['bbox'][0] for span in line), # x0- min(span['bbox'][1] for span in line), # y0- max(span['bbox'][2] for span in line), # x1- max(span['bbox'][3] for span in line), # y1+ min(span["bbox"][0] for span in line), # x0+ min(span["bbox"][1] for span in line), # y0+ max(span["bbox"][2] for span in line), # x1+ max(span["bbox"][3] for span in line), # y1]- line_objects.append({- 'bbox': line_bbox,- 'spans': line,- })+ line_objects.append(+ {+ "bbox": line_bbox,+ "spans": line,+ }+ )return line_objects-def vertical_line_sort_spans_from_top_to_bottom(vertical_lines):+def vertical_line_sort_spans_from_top_to_bottom(vertical_lines: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:line_objects = []for line in vertical_lines:# 按照y0坐标排序(从上到下)- line.sort(key=lambda span: span['bbox'][1])+ line.sort(key=lambda span: span["bbox"][1])# 计算整个列的边界框line_bbox = [- min(span['bbox'][0] for span in line), # x0- min(span['bbox'][1] for span in line), # y0- max(span['bbox'][2] for span in line), # x1- max(span['bbox'][3] for span in line), # y1+ min(span["bbox"][0] for span in line), # x0+ min(span["bbox"][1] for span in line), # y0+ max(span["bbox"][2] for span in line), # x1+ max(span["bbox"][3] for span in line), # y1]# 组装结果- line_objects.append({- 'bbox': line_bbox,- 'spans': line,- })+ line_objects.append(+ {+ "bbox": line_bbox,+ "spans": line,+ }+ )return line_objectsdiff --git a/mineru/utils/span_pre_proc.py b/mineru/utils/span_pre_proc.pyindex 7648d815..8e5b1b52 100644--- a/mineru/utils/span_pre_proc.py+++ b/mineru/utils/span_pre_proc.py@@ -1,37 +1,49 @@# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations+import collectionsimport mathimport reimport statistics+from typing import Any, Callableimport cv2import numpy as npfrom loguru import logger-from mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio-from mineru.utils.enum_class import BlockType, ContentType-from mineru.utils.pdf_image_tools import get_crop_img-from mineru.utils.pdf_text_tool import get_lines_from_chars, get_page_chars-from mineru.utils.pdfium_guard import close_pdfium_child, pdfium_guard+from .boxbase import calculate_overlap_area_in_bbox1_area_ratio+from .enum_class import BlockType, ContentType+from .pdf_image_tools import get_crop_img+from .pdf_text_tool import get_lines_from_chars, get_page_chars+from .pdfium_guard import close_pdfium_child, pdfium_guardMAX_NATIVE_TEXT_CHARS_PER_PAGE = 65535-def __replace_ligatures(text: str):- ligatures = {- 'fi': 'fi', 'fl': 'fl', 'ff': 'ff', 'ffi': 'ffi', 'ffl': 'ffl', 'ſt': 'ft', 'st': 'st'- }- return re.sub('|'.join(map(re.escape, ligatures.keys())), lambda m: ligatures[m.group()], text)+def __replace_ligatures(text: str) -> str:+ ligatures = {"fi": "fi", "fl": "fl", "ff": "ff", "ffi": "ffi", "ffl": "ffl", "ſt": "ft", "st": "st"}+ return re.sub("|".join(map(re.escape, ligatures.keys())), lambda m: ligatures[m.group()], text)-def __replace_unicode(text: str):++def __replace_unicode(text: str) -> str:ligatures = {- '\r\n': '', '\u0002': '-',+ "\r\n": "",+ "\u0002": "-",}- return re.sub('|'.join(map(re.escape, ligatures.keys())), lambda m: ligatures[m.group()], text)+ return re.sub("|".join(map(re.escape, ligatures.keys())), lambda m: ligatures[m.group()], text)"""pdf_text dict方案 char级别"""-def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discarded_blocks):+++def txt_spans_extract(+ pdf_page: Any,+ spans: list[dict[str, Any]],+ pil_img: Any,+ scale: int,+ all_bboxes: list[tuple[Any, ...]],+ all_discarded_blocks: list[tuple[Any, ...]],+) -> list[dict[str, Any]]:page_char_count = Nonetextpage = Nonetry:@@ -43,13 +55,8 @@ def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discardedlogger.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(- "Fallback to post-OCR in txt_spans_extract due to high char count: "- f"count_chars={page_char_count}"- )- need_ocr_spans = [- span for span in spans if span.get('type') == ContentType.TEXT- ]+ 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.get("type") == ContentType.TEXT]return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)page_chars = get_page_chars(@@ -57,18 +64,15 @@ def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discardedtextpage=textpage,page_char_count=page_char_count,)- page_all_chars = [- char for char in page_chars['chars']- if _is_supported_rotation(char['rotation'])- ]+ page_all_chars = [char for char in page_chars["chars"] if _is_supported_rotation(char["rotation"])]# 计算所有sapn的高度的中位数span_height_list = []for span in spans:- if span['type'] in [ContentType.TEXT]:- span_height = span['bbox'][3] - span['bbox'][1]- span['height'] = span_height- span['width'] = span['bbox'][2] - span['bbox'][0]+ if span["type"] in [ContentType.TEXT]:+ span_height = span["bbox"][3] - span["bbox"][1]+ span["height"] = span_height+ span["width"] = span["bbox"][2] - span["bbox"][0]span_height_list.append(span_height)if len(span_height_list) == 0:return spans@@ -80,12 +84,12 @@ def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discarded# 纵向span的两个特征:1. 高度超过多个line 2. 高宽比超过某个值vertical_spans = []for span in spans:- if span['type'] in [ContentType.TEXT]:+ 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['height'] > median_span_height * 2.3 and span['height'] > span['width'] * 2.3:+ if calculate_overlap_area_in_bbox1_area_ratio(span["bbox"], block[0:4]) > 0.5:+ if span["height"] > median_span_height * 2.3 and span["height"] > span["width"] * 2.3:vertical_spans.append(span)elif block in all_bboxes:useful_spans.append(span)@@ -96,26 +100,25 @@ def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discarded"""垂直的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'])+ 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']+ 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"]breakfor span in vertical_spans:- if len(span['content']) == 0:+ if len(span["content"]) == 0:spans.remove(span)"""水平的span框先用char填充,再用ocr填充空的span框"""new_spans = []for span in useful_spans + unuseful_spans:- if span['type'] in [ContentType.TEXT]:- span['chars'] = []+ if span["type"] in [ContentType.TEXT]:+ span["chars"] = []new_spans.append(span)need_ocr_spans = fill_char_in_spans(new_spans, page_all_chars, median_span_height)@@ -125,29 +128,34 @@ def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discardedclose_pdfium_child(textpage)-def _is_supported_rotation(rotation) -> bool:+def _is_supported_rotation(rotation: float) -> bool:"""判断 pdftext 旋转角是否属于当前可回填的四个标准方向。"""rotation_degrees = math.degrees(rotation)return any(abs(rotation_degrees - angle) < 0.1 for angle in [0, 90, 180, 270])-def _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale):+def _prepare_post_ocr_spans(+ need_ocr_spans: list[dict[str, Any]],+ spans: list[dict[str, Any]],+ pil_img: Any,+ scale: int,+) -> list[dict[str, Any]]:if len(need_ocr_spans) == 0:return spansfor span in need_ocr_spans:# 对span的bbox截图再ocr- span_pil_img = get_crop_img(span['bbox'], pil_img, scale)+ span_pil_img = get_crop_img(span["bbox"], pil_img, scale)span_img = cv2.cvtColor(np.array(span_pil_img), cv2.COLOR_RGB2BGR)# 计算span的对比度,低于0.17的span不进行ocr,等于0.17的临界框保留给后置OCR。- if calculate_contrast(span_img, img_mode='bgr') < 0.17:+ if calculate_contrast(span_img, img_mode="bgr") < 0.17:if span in spans:spans.remove(span)continue- span['content'] = ''- span['score'] = 1.0- span['np_img'] = span_img+ span["content"] = ""+ span["score"] = 1.0+ span["np_img"] = span_imgreturn spans@@ -155,29 +163,27 @@ def _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale):class SpanBlockMatcher:"""按 block 顺序消费 span,并用 y 方向索引减少无效重叠计算。"""- def __init__(self, spans):+ def __init__(self, spans: list[dict[str, Any]]) -> None:self.spans = list(spans)self.used_span_indices = set()self.grid_size = self._get_grid_size(self.spans)self.grid = self._build_grid(self.spans)@staticmethod- def _get_grid_size(spans):+ def _get_grid_size(spans: list[dict[str, Any]]) -> int:"""根据 span 高度估算索引网格大小,避免过细或过粗。"""heights = [- span['bbox'][3] - span['bbox'][1]- for span in spans- if span.get('bbox') and span['bbox'][3] > span['bbox'][1]+ span["bbox"][3] - span["bbox"][1] for span in spans if span.get("bbox") and span["bbox"][3] > span["bbox"][1]]if not heights:return 1return max(1, statistics.median(heights))- def _build_grid(self, spans):+ def _build_grid(self, spans: list[dict[str, Any]]) -> dict[int, list[int]]:"""将 span 按 y 方向网格登记,后续按 block bbox 快速取候选。"""grid = collections.defaultdict(list)for index, span in enumerate(spans):- bbox = span.get('bbox')+ bbox = span.get("bbox")if not bbox:continuestart_cell, end_cell = self._cell_range(bbox)@@ -185,14 +191,14 @@ class SpanBlockMatcher:grid[cell_idx].append(index)return grid- def _cell_range(self, bbox):+ def _cell_range(self, bbox: list[float]) -> tuple[int, int]:"""计算 bbox 覆盖的 y 方向网格范围。"""return (int(bbox[1] / self.grid_size),int(bbox[3] / self.grid_size),)- def _candidate_indices_for_block(self, block_bbox):+ def _candidate_indices_for_block(self, block_bbox: list[float]) -> list[int]:"""取出与 block 纵向范围可能相交的 span 原始索引。"""start_cell, end_cell = self._cell_range(block_bbox)candidate_indices = set()@@ -200,7 +206,12 @@ class SpanBlockMatcher:candidate_indices.update(self.grid.get(cell_idx, []))return sorted(candidate_indices)- def collect_for_block(self, block_bbox, overlap_ratio_getter=None, threshold=0.5):+ def collect_for_block(+ self,+ block_bbox: list[float],+ overlap_ratio_getter: Callable | None = None,+ threshold: float = 0.5,+ ) -> list[dict[str, Any]]:"""返回当前 block 命中的 span,并标记为已消费以保持旧归属语义。"""if overlap_ratio_getter is None:overlap_ratio_getter = self._default_overlap_ratio@@ -215,29 +226,29 @@ class SpanBlockMatcher:self.used_span_indices.add(span_idx)return block_spans- def remaining_spans(self):+ def remaining_spans(self) -> list[dict[str, Any]]:"""返回尚未归属到任何 block 的 span,方便保持后续兼容。"""- return [- span- for index, span in enumerate(self.spans)- if index not in self.used_span_indices- ]+ return [span for index, span in enumerate(self.spans) if index not in self.used_span_indices]@staticmethod- def _default_overlap_ratio(span, block_bbox):+ def _default_overlap_ratio(span: dict[str, Any], block_bbox: list[float]) -> float:"""默认沿用旧逻辑:计算 span 面积中落入 block 的比例。"""- return calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block_bbox)+ return calculate_overlap_area_in_bbox1_area_ratio(span["bbox"], block_bbox)-def fill_char_in_spans(spans, all_chars, median_span_height):+def fill_char_in_spans(+ spans: list[dict[str, Any]],+ all_chars: list[dict[str, Any]],+ median_span_height: float,+) -> list[dict[str, Any]]:# 简单从上到下排一下序- spans = sorted(spans, key=lambda x: x['bbox'][1])+ spans = sorted(spans, key=lambda x: x["bbox"][1])grid_size = max(1, median_span_height)grid = collections.defaultdict(list)span_bboxes = []for i, span in enumerate(spans):- span_bbox = span['bbox']+ span_bbox = span["bbox"]span_bboxes.append(span_bbox)start_cell = int(span_bbox[1] / grid_size)end_cell = int(span_bbox[3] / grid_size)@@ -245,7 +256,7 @@ def fill_char_in_spans(spans, all_chars, median_span_height):grid[cell_idx].append(i)for char in all_chars:- char_bbox = char['bbox']+ char_bbox = char["bbox"]char_center_x = (char_bbox[0] + char_bbox[2]) / 2char_center_y = (char_bbox[1] + char_bbox[3]) / 2cell_idx = int(char_center_y / grid_size)@@ -256,31 +267,78 @@ def fill_char_in_spans(spans, all_chars, median_span_height):span = spans[span_idx]span_bbox = span_bboxes[span_idx]if (- char['char'] not in LINE_STOP_FLAG- and char['char'] not in LINE_START_FLAG+ char["char"] not in LINE_STOP_FLAG+ and char["char"] not in LINE_START_FLAGand not span_bbox[0] < char_center_x < span_bbox[2]):continue- if calculate_char_in_span(char_bbox, span_bbox, char['char']):- span['chars'].append(char)+ if calculate_char_in_span(char_bbox, span_bbox, char["char"]):+ span["chars"].append(char)breakneed_ocr_spans = []for span in spans:chars_to_content(span)# 有的span中虽然没有字但有一两个空的占位符,用宽高和content长度过滤- if len(span['content']) * span['height'] < span['width'] * 0.5:+ if len(span["content"]) * span["height"] < span["width"] * 0.5:# logger.info(f"maybe empty span: {len(span['content'])}, {span['height']}, {span['width']}")need_ocr_spans.append(span)- del span['height'], span['width']+ del span["height"], span["width"]return need_ocr_spans-LINE_STOP_FLAG = ('.', '!', '?', '。', '!', '?', ')', ')', '"', '”', ':', ':', ';', ';', ']', '】', '}', '}', '>', '》', '、', ',', ',', '-', '—', '–',)-LINE_START_FLAG = ('(', '(', '"', '“', '【', '{', '《', '<', '「', '『', '【', '[',)+LINE_STOP_FLAG = (+ ".",+ "!",+ "?",+ "。",+ "!",+ "?",+ ")",+ ")",+ '"',+ "”",+ ":",+ ":",+ ";",+ ";",+ "]",+ "】",+ "}",+ "}",+ ">",+ "》",+ "、",+ ",",+ ",",+ "-",+ "—",+ "–",+)+LINE_START_FLAG = (+ "(",+ "(",+ '"',+ "“",+ "【",+ "{",+ "《",+ "<",+ "「",+ "『",+ "【",+ "[",+)Span_Height_Ratio = 0.33 # 字符的中轴和span的中轴高度差不能超过1/3span高度-def calculate_char_in_span(char_bbox, span_bbox, char, span_height_ratio=Span_Height_Ratio):+++def calculate_char_in_span(+ char_bbox: list[float],+ span_bbox: list[float],+ char: str,+ span_height_ratio: float = Span_Height_Ratio,+) -> bool:char_center_x = (char_bbox[0] + char_bbox[2]) / 2char_center_y = (char_bbox[1] + char_bbox[3]) / 2span_center_y = (span_bbox[1] + span_bbox[3]) / 2@@ -289,45 +347,41 @@ def calculate_char_in_span(char_bbox, span_bbox, char, span_height_ratio=Span_Heif (span_bbox[0] < char_center_x < span_bbox[2]and span_bbox[1] < char_center_y < span_bbox[3]- and abs(char_center_y - span_center_y) < span_height * span_height_ratio # 字符的中轴和span的中轴高度差不能超过Span_Height_Ratio+ and abs(char_center_y - span_center_y)+ < span_height * span_height_ratio # 字符的中轴和span的中轴高度差不能超过Span_Height_Ratio):return True- else:- # 如果char是LINE_STOP_FLAG,就不用中心点判定,换一种方案(左边界在span区域内,高度判定和之前逻辑一致)- # 主要是给结尾符号一个进入span的机会,这个char还应该离span右边界较近- if char in LINE_STOP_FLAG:- if (- (span_bbox[2] - span_height) < char_bbox[0] < span_bbox[2]- and char_center_x > span_bbox[0]- and span_bbox[1] < char_center_y < span_bbox[3]- and abs(char_center_y - span_center_y) < span_height * span_height_ratio- ):- return True- elif char in LINE_START_FLAG:- if (- span_bbox[0] < char_bbox[2] < (span_bbox[0] + span_height)- and char_center_x < span_bbox[2]- and span_bbox[1] < char_center_y < span_bbox[3]- and abs(char_center_y - span_center_y) < span_height * span_height_ratio- ):- return True- else:- return False+ # 如果char是LINE_STOP_FLAG,就不用中心点判定,换一种方案(左边界在span区域内,高度判定和之前逻辑一致)+ # 主要是给结尾符号一个进入span的机会,这个char还应该离span右边界较近+ if char in LINE_STOP_FLAG:+ if (+ (span_bbox[2] - span_height) < char_bbox[0] < span_bbox[2]+ and char_center_x > span_bbox[0]+ and span_bbox[1] < char_center_y < span_bbox[3]+ and abs(char_center_y - span_center_y) < span_height * span_height_ratio+ ):+ return True+ elif char in LINE_START_FLAG:+ if (+ span_bbox[0] < char_bbox[2] < (span_bbox[0] + span_height)+ and char_center_x < span_bbox[2]+ and span_bbox[1] < char_center_y < span_bbox[3]+ and abs(char_center_y - span_center_y) < span_height * span_height_ratio+ ):+ return True+ return False-def chars_to_content(span):+def chars_to_content(span: dict[str, Any]) -> None:# 检查span中的char是否为空- if len(span['chars']) != 0:- chars = span['chars']+ if len(span["chars"]) != 0:+ chars = span["chars"]# 大多数情况下 char 已按 PDF 原始顺序进入,只有乱序时才排序。- if any(- chars[idx]['char_idx'] > chars[idx + 1]['char_idx']- for idx in range(len(chars) - 1)- ):- chars = sorted(chars, key=lambda x: x['char_idx'])+ if any(chars[idx]["char_idx"] > chars[idx + 1]["char_idx"] for idx in range(len(chars) - 1)):+ chars = sorted(chars, key=lambda x: x["char_idx"])# Calculate the width of each character- char_widths = [char['bbox'][2] - char['bbox'][0] for char in chars]+ char_widths = [char["bbox"][2] - char["bbox"][0] for char in chars]# Calculate the median widthmedian_width = statistics.median(char_widths)@@ -338,34 +392,34 @@ def chars_to_content(span):# 如果下一个char的x0和上一个char的x1距离超过0.25个字符宽度,则需要在中间插入一个空格if (char2- and char2['bbox'][0] - char1['bbox'][2] > median_width * 0.25- and char1['char'] != ' '- and char2['char'] != ' '+ and char2["bbox"][0] - char1["bbox"][2] > median_width * 0.25+ and char1["char"] != " "+ and char2["char"] != " "):- parts.append(char1['char'])- parts.append(' ')+ parts.append(char1["char"])+ parts.append(" ")else:- parts.append(char1['char'])+ parts.append(char1["char"])- content = ''.join(parts)+ content = "".join(parts)content = __replace_unicode(content)content = __replace_ligatures(content)- span['content'] = content.strip()+ span["content"] = content.strip()- del span['chars']+ del span["chars"]-def calculate_contrast(img, img_mode) -> float:+def calculate_contrast(img: np.ndarray, img_mode: str) -> float:"""计算给定图像的对比度。:param img: 图像,类型为numpy.ndarray:Param img_mode = 图像的色彩通道,'rgb' 或 'bgr':return: 图像的对比度值"""- if img_mode == 'rgb':+ if img_mode == "rgb":# 将RGB图像转换为灰度图gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)- elif img_mode == 'bgr':+ elif img_mode == "bgr":# 将BGR图像转换为灰度图gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)else:@@ -377,4 +431,4 @@ def calculate_contrast(img, img_mode) -> float:# 对比度定义为标准差除以平均值(加上小常数避免除零错误)contrast = std_dev / (mean_value + 1e-6)# logger.debug(f"contrast: {contrast}")- return round(contrast, 2)+ return round(float(contrast), 2)diff --git a/mineru/utils/table_continuation.py b/mineru/utils/table_continuation.pyindex 6a534639..55eacad7 100644--- a/mineru/utils/table_continuation.py+++ b/mineru/utils/table_continuation.py@@ -1,7 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.-from mineru.utils.char_utils import full_to_half-+from .char_utils import full_to_halfCONTINUATION_END_MARKERS = ["(续)",@@ -26,13 +25,9 @@ def is_table_continuation_text(text: str) -> bool:if not continuation_text:return False- return (- any(- _matches_continuation_end_marker(continuation_text, marker.lower())- for marker in CONTINUATION_END_MARKERS- )- or any(marker.lower() in continuation_text for marker in CONTINUATION_INLINE_MARKERS)- )+ return any(+ _matches_continuation_end_marker(continuation_text, marker.lower()) for marker in CONTINUATION_END_MARKERS+ ) or any(marker.lower() in continuation_text for marker in CONTINUATION_INLINE_MARKERS)def _matches_continuation_end_marker(text: str, marker: str) -> bool:diff --git a/mineru/utils/table_merge.py b/mineru/utils/table_merge.pyindex 64e08bf2..394ca8aa 100644--- a/mineru/utils/table_merge.py+++ b/mineru/utils/table_merge.py@@ -1,15 +1,16 @@# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations+from copy import deepcopyfrom dataclasses import dataclassfrom typing import Any-from bs4 import BeautifulSoup--from mineru.backend.vlm.vlm_middle_json_mkcontent import merge_para_with_text-from mineru.utils.char_utils import full_to_half-from mineru.utils.enum_class import BlockType, SplitFlag-from mineru.utils.table_continuation import is_table_continuation_text+from bs4 import BeautifulSoup, Tag+from ..backend.vlm.vlm_middle_json_mkcontent import merge_para_with_text+from .char_utils import full_to_half+from .enum_class import BlockType, SplitFlag+from .table_continuation import is_table_continuation_textMAX_HEADER_ROWS = 5@@ -67,15 +68,15 @@ class TableMergeState:dirty: bool = False-def _normalize_cell_text(cell) -> str:+def _normalize_cell_text(cell: Tag) -> str:return "".join(full_to_half(cell.get_text()).split())-def _display_cell_text(cell) -> str:+def _display_cell_text(cell: Tag) -> str:return full_to_half(cell.get_text().strip())-def _scan_rows(rows, initial_occupied: dict[int, set[int]] | None = None, start_row_idx: int = 0) -> RowScanResult:+def _scan_rows(rows: list[Tag], initial_occupied: dict[int, set[int]] | None = None, start_row_idx: int = 0) -> RowScanResult:"""Scan rows once and cache effective-column metrics.initial_occupied stores future-row occupancy relative to the first scanned row@@ -87,7 +88,7 @@ def _scan_rows(rows, initial_occupied: dict[int, set[int]] | None = None, start_for row_offset, cols in (initial_occupied or {}).items():if not cols:continue- occupied[row_offset] = {col: True for col in cols}+ occupied[row_offset] = dict.fromkeys(cols, True)max_cols = max(max_cols, max(cols) + 1)row_effective_cols: list[int] = []@@ -132,9 +133,7 @@ def _scan_rows(rows, initial_occupied: dict[int, set[int]] | None = None, start_last_nonempty_row_metrics = metricstail_occupied = {- row_idx - len(rows): set(cols.keys())- for row_idx, cols in occupied.items()- if row_idx >= len(rows) and cols+ row_idx - len(rows): set(cols.keys()) for row_idx, cols in occupied.items() if row_idx >= len(rows) and cols}return RowScanResult(@@ -146,7 +145,7 @@ def _scan_rows(rows, initial_occupied: dict[int, set[int]] | None = None, start_)-def _build_row_signature(row, effective_cols: int) -> RowSignature:+def _build_row_signature(row: Tag, effective_cols: int) -> RowSignature:cells = row.find_all(["td", "th"])return RowSignature(effective_cols=effective_cols,@@ -157,7 +156,9 @@ def _build_row_signature(row, effective_cols: int) -> RowSignature:)-def _build_front_cache(rows, max_header_rows: int = MAX_HEADER_ROWS) -> tuple[list[RowSignature], dict[int, RowMetrics]]:+def _build_front_cache(+ rows: list[Tag], max_header_rows: int = MAX_HEADER_ROWS+) -> tuple[list[RowSignature], dict[int, RowMetrics]]:front_limit = min(len(rows), max_header_rows + 1)front_rows = rows[:front_limit]front_scan = _scan_rows(front_rows)@@ -166,13 +167,11 @@ def _build_front_cache(rows, max_header_rows: int = MAX_HEADER_ROWS) -> tuple[li_build_row_signature(front_rows[idx], front_scan.row_effective_cols[idx])for idx in range(min(len(front_rows), max_header_rows))]- front_first_data_row_metrics = {- idx: metrics for idx, metrics in enumerate(front_scan.row_metrics)- }+ front_first_data_row_metrics = dict(enumerate(front_scan.row_metrics))return front_header_info, front_first_data_row_metrics-def _find_table_body_block(table_block):+def _find_table_body_block(table_block: dict[str, Any]) -> dict[str, Any] | None:"""查找 table block 中的主体子块。"""for block in table_block["blocks"]:if block["type"] == BlockType.TABLE_BODY:@@ -180,7 +179,7 @@ def _find_table_body_block(table_block):return None-def _build_post_body_child_index(table_block, offset: int) -> int | float | None:+def _build_post_body_child_index(table_block: dict[str, Any], offset: int) -> int | float | None:"""为跨页搬运到上一页表格的子块生成表体后的安全 index。"""body_block = _find_table_body_block(table_block)if body_block is None:@@ -193,19 +192,19 @@ def _build_post_body_child_index(table_block, offset: int) -> int | float | Nonereturn body_index + offset-def _find_table_body_span(table_block):+def _find_table_body_span(table_block: dict[str, Any]) -> dict[str, Any] | None:body_block = _find_table_body_block(table_block)if body_block and body_block["lines"] and body_block["lines"][0]["spans"]:return body_block["lines"][0]["spans"][0]return None-def _is_continuation_caption(caption_block) -> bool:+def _is_continuation_caption(caption_block: dict[str, Any]) -> bool:"""判断 caption 文本是否带有续表标记。"""return is_table_continuation_text(merge_para_with_text(caption_block))-def _is_post_table_non_continuation_caption(table_block, caption_block) -> bool:+def _is_post_table_non_continuation_caption(table_block: dict[str, Any], caption_block: dict[str, Any]) -> bool:"""判断 caption 是否是误挂到表格下方的新段落标题。这类 caption 位于 table body 下方,且不含续表标记;它不应作为@@ -226,16 +225,18 @@ def _is_post_table_non_continuation_caption(table_block, caption_block) -> bool:return caption_bbox[1] >= body_bbox[3]-def _get_post_table_caption_blocks(table_block):+def _get_post_table_caption_blocks(table_block: dict[str, Any]) -> list[dict[str, Any]]:"""收集当前表格下方、需要恢复为普通文本的非续表 caption。"""return [- block for block in table_block["blocks"]- if block["type"] == BlockType.TABLE_CAPTION- and _is_post_table_non_continuation_caption(table_block, block)+ block+ for block in table_block["blocks"]+ if block["type"] == BlockType.TABLE_CAPTION and _is_post_table_non_continuation_caption(table_block, block)]-def _restore_post_table_captions_as_text(page_info, table_block, caption_blocks) -> None:+def _restore_post_table_captions_as_text(+ page_info: dict[str, Any], table_block: dict[str, Any], caption_blocks: list[dict[str, Any]]+) -> None:"""将误挂到表格下方的 caption 迁回当前页,作为独立 text block 输出。"""if not caption_blocks:return@@ -254,10 +255,7 @@ def _restore_post_table_captions_as_text(page_info, table_block, caption_blocks)para_blocks[insert_idx:insert_idx] = restored_blocksrestored_caption_ids = {id(block) for block in caption_blocks}- table_block["blocks"] = [- block for block in table_block["blocks"]- if id(block) not in restored_caption_ids- ]+ table_block["blocks"] = [block for block in table_block["blocks"] if id(block) not in restored_caption_ids]def _refresh_table_state_metrics(state: TableMergeState) -> None:@@ -305,7 +303,7 @@ def build_table_state_from_html()-def _build_table_state(table_block, max_header_rows: int = MAX_HEADER_ROWS) -> TableMergeState | None:+def _build_table_state(table_block: dict[str, Any], max_header_rows: int = MAX_HEADER_ROWS) -> TableMergeState | None:body_span = _find_table_body_span(table_block)if body_span is None:return None@@ -336,7 +334,7 @@ def _build_table_state(table_block, max_header_rows: int = MAX_HEADER_ROWS) -> Tdef _get_or_create_table_state(- table_block,+ table_block: dict[str, Any],state_cache: dict[int, TableMergeState],max_header_rows: int = MAX_HEADER_ROWS,) -> TableMergeState | None:@@ -356,32 +354,29 @@ def _serialize_table_state_html(state: TableMergeState) -> None:state.dirty = False-def calculate_table_total_columns(soup):+def calculate_table_total_columns(soup: BeautifulSoup) -> int:"""计算表格的总列数,通过分析整个表格结构来处理rowspan和colspan."""rows = soup.find_all("tr")return _scan_rows(rows).total_cols if rows else 0-def build_table_occupied_matrix(soup):+def build_table_occupied_matrix(soup: BeautifulSoup) -> dict[int, int]:"""构建表格的占用矩阵,返回每行的有效列数."""rows = soup.find_all("tr")if not rows:return {}scan = _scan_rows(rows)- return {- row_idx: effective_cols- for row_idx, effective_cols in enumerate(scan.row_effective_cols)- }+ return dict(enumerate(scan.row_effective_cols))-def calculate_row_effective_columns(soup, row_idx):+def calculate_row_effective_columns(soup: BeautifulSoup, row_idx: int) -> int:"""计算指定行的有效列数(考虑rowspan占用)."""row_effective_cols = build_table_occupied_matrix(soup)return row_effective_cols.get(row_idx, 0)-def calculate_row_columns(row):+def calculate_row_columns(row: Tag) -> int:"""计算表格行的实际列数,考虑colspan属性."""cells = row.find_all(["td", "th"])column_count = 0@@ -393,14 +388,14 @@ def calculate_row_columns(row):return column_count-def calculate_visual_columns(row):+def calculate_visual_columns(row: Tag) -> int:"""计算表格行的视觉列数(实际td/th单元格数量,不考虑colspan)."""cells = row.find_all(["td", "th"])return len(cells)def _scan_row_visual_sources(- rows,+ rows: list[Tag],target_row_index: int,initial_occupied: dict[int, set[int]] | None = None,) -> tuple[dict[int, tuple[int, int]], int]:@@ -421,9 +416,7 @@ def _scan_row_visual_sources(for row_offset, cols in (initial_occupied or {}).items():if not cols:continue- occupied[row_offset] = {- col: (-1, col) for col in cols- }+ occupied[row_offset] = {col: (-1, col) for col in cols}total_cols = max(total_cols, max(cols) + 1)for r_idx in range(target_row_index + 1):@@ -448,7 +441,7 @@ def _scan_row_visual_sources(def build_visual_col_mapping(- rows,+ rows: list[Tag],target_row_index: int,initial_occupied: dict[int, set[int]] | None = None,) -> list[int]:@@ -481,7 +474,7 @@ def build_visual_col_mapping(def build_row_rendered_cell_segments(- rows,+ rows: list[Tag],target_row_index: int,initial_occupied: dict[int, set[int]] | None = None,) -> list[RenderedCellSegment]:@@ -538,7 +531,7 @@ def build_row_rendered_cell_segments(return segments-def calculate_row_rendered_segments(rows, target_row_index: int) -> int:+def calculate_row_rendered_segments(rows: list[Tag], target_row_index: int) -> int:"""计算目标行渲染后的视觉段数。段数按“渲染出来的单元格块”统计:@@ -565,7 +558,9 @@ def calculate_row_rendered_segments(rows, target_row_index: int) -> int:return segment_count-def detect_table_headers(state1: TableMergeState, state2: TableMergeState, max_header_rows: int = MAX_HEADER_ROWS):+def detect_table_headers(+ state1: TableMergeState, state2: TableMergeState, max_header_rows: int = MAX_HEADER_ROWS+) -> tuple[int, bool, list[list[str]]]:"""检测并比较两个表格的表头,仅扫描前几行."""front_rows1 = state1.front_header_info[:max_header_rows]front_rows2 = state2.front_header_info[:max_header_rows]@@ -594,9 +589,7 @@ def detect_table_headers(state1: TableMergeState, state2: TableMergeState, max_hbreakif header_rows == 0:- header_rows, headers_match, header_texts = _detect_table_headers_visual(- state1, state2, max_header_rows=max_header_rows- )+ header_rows, headers_match, header_texts = _detect_table_headers_visual(state1, state2, max_header_rows=max_header_rows)return header_rows, headers_match, header_texts@@ -605,7 +598,7 @@ def _detect_table_headers_visual(state1: TableMergeState,state2: TableMergeState,max_header_rows: int = MAX_HEADER_ROWS,-):+) -> tuple[int, bool, list[list[str]]]:"""基于视觉一致性检测表头(只比较文本内容,忽略colspan/rowspan差异)."""front_rows1 = state1.front_header_info[:max_header_rows]front_rows2 = state2.front_header_info[:max_header_rows]@@ -634,7 +627,7 @@ def _detect_table_headers_visual(return header_rows, headers_match, header_texts-def _expand_header_count_by_rowspan(rows, header_count: int) -> int:+def _expand_header_count_by_rowspan(rows: list[Tag], header_count: int) -> int:"""按表头 rowspan 覆盖范围扩展跳过行数。跨页续表的第一行表头可能包含 rowspan。如果只跳过已匹配的首行,@@ -683,7 +676,7 @@ def can_merge_by_structure(return check_rows_match(previous_state, current_state)-def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeState):+def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeState) -> bool:"""判断两个表格是否可以合并."""current_table_block = current_state.owner_blockprevious_table_block = previous_state.owner_block@@ -694,20 +687,13 @@ def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeS"For HTML-only states from build_table_state_from_html(), use can_merge_by_structure() instead.")- footnote_count = sum(- 1 for block in previous_table_block["blocks"] if block["type"] == BlockType.TABLE_FOOTNOTE- )- caption_blocks = [- block for block in current_table_block["blocks"] if block["type"] == BlockType.TABLE_CAPTION- ]+ footnote_count = sum(1 for block in previous_table_block["blocks"] if block["type"] == BlockType.TABLE_FOOTNOTE)+ caption_blocks = [block for block in current_table_block["blocks"] if block["type"] == BlockType.TABLE_CAPTION]merge_caption_blocks = [- block for block in caption_blocks- if not _is_post_table_non_continuation_caption(current_table_block, block)+ block for block in caption_blocks if not _is_post_table_non_continuation_caption(current_table_block, block)]if merge_caption_blocks:- has_continuation_marker = any(- _is_continuation_caption(block) for block in merge_caption_blocks- )+ has_continuation_marker = any(_is_continuation_caption(block) for block in merge_caption_blocks)if not has_continuation_marker:return False@@ -731,7 +717,7 @@ def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeSreturn check_rows_match(previous_state, current_state)-def check_rows_match(previous_state: TableMergeState, current_state: TableMergeState):+def check_rows_match(previous_state: TableMergeState, current_state: TableMergeState) -> bool:"""检查表格边界行是否匹配."""last_row_metrics = previous_state.last_data_row_metricsif last_row_metrics is None:@@ -753,7 +739,7 @@ def check_rows_match(previous_state: TableMergeState, current_state: TableMergeS)-def check_row_columns_match(row1, row2):+def check_row_columns_match(row1: Tag, row2: Tag) -> bool:cells1 = row1.find_all(["td", "th"])cells2 = row2.find_all(["td", "th"])if len(cells1) != len(cells2):@@ -767,15 +753,15 @@ def check_row_columns_match(row1, row2):def adjust_table_rows_colspan(- rows,- start_idx,- end_idx,- row_effective_cols,- reference_structure,- reference_visual_cols,- target_cols,- match_reference_row,-):+ rows: list[Tag],+ start_idx: int,+ end_idx: int,+ row_effective_cols: list[int],+ reference_structure: list[int],+ reference_visual_cols: int,+ target_cols: int,+ match_reference_row: Tag,+) -> None:"""调整表格行的colspan属性以匹配目标列数."""reference_row_copy = deepcopy(match_reference_row)@@ -791,10 +777,7 @@ def adjust_table_rows_colspan(if current_row_effective_cols >= target_cols or current_row_cols >= target_cols:continue- if (- calculate_visual_columns(row) == reference_visual_cols- and check_row_columns_match(row, reference_row_copy)- ):+ if calculate_visual_columns(row) == reference_visual_cols and check_row_columns_match(row, reference_row_copy):if len(cells) <= len(reference_structure):for cell_idx, cell in enumerate(cells):if cell_idx < len(reference_structure) and reference_structure[cell_idx] > 1:@@ -807,23 +790,20 @@ def adjust_table_rows_colspan(last_cell["colspan"] = str(current_last_span + cols_diff)-def _cell_has_semantic_content(cell) -> bool:+def _cell_has_semantic_content(cell: Tag) -> bool:"""判断单元格是否仍包含用户可见的语义内容。"""if cell.get_text(strip=True):return True- return (- cell.find(["img", "svg", "math", "eq", "table", "figure", "object", "embed", "canvas"])- is not None- )+ return cell.find(["img", "svg", "math", "eq", "table", "figure", "object", "embed", "canvas"]) is not None-def _row_has_semantic_content(row) -> bool:+def _row_has_semantic_content(row: Tag) -> bool:"""判断整行是否仍保留未并回的语义内容。"""return any(_cell_has_semantic_content(cell) for cell in row.find_all(["td", "th"]))-def _insert_cell_before_visual_column(rows, target_row_index: int, start_vcol: int, cell) -> None:+def _insert_cell_before_visual_column(rows: list[Tag], target_row_index: int, start_vcol: int, cell: Tag) -> None:"""将单元格插入到目标行中对应视觉列之前。"""target_row = rows[target_row_index]target_cells = target_row.find_all(["td", "th"])@@ -837,7 +817,7 @@ def _insert_cell_before_visual_column(rows, target_row_index: int, start_vcol: itarget_row.append(cell)-def _carry_rowspan_structure_to_next_row(rows, row_idx: int) -> None:+def _carry_rowspan_structure_to_next_row(rows: list[Tag], row_idx: int) -> None:"""下沉空白结构占位单元格,避免删除当前行后破坏后续列对齐。"""next_row_idx = row_idx + 1if next_row_idx >= len(rows):@@ -866,7 +846,7 @@ def _carry_rowspan_structure_to_next_row(rows, row_idx: int) -> None:def _clip_overlapped_blank_rowspan_cells(- rows,+ rows: list[Tag],initial_occupied: dict[int, set[int]],) -> bool:"""裁剪被上页 rowspan 覆盖的当前页空白结构占位。@@ -1020,9 +1000,9 @@ def _apply_cell_merge(def perform_table_merge(previous_state: TableMergeState,current_state: TableMergeState,- previous_table_block,- wait_merge_table_footnotes,-):+ previous_table_block: dict[str, Any],+ wait_merge_table_footnotes: list[dict[str, Any]],+) -> None:"""执行表格合并操作."""header_count, _, _ = detect_table_headers(previous_state, current_state)header_count = _expand_header_count_by_rowspan(current_state.rows, header_count)@@ -1044,9 +1024,7 @@ def perform_table_merge(table_cols2 = current_state.total_colsif table_cols1 > table_cols2:- reference_structure = [- int(cell.get("colspan", 1)) for cell in last_row1.find_all(["td", "th"])- ]+ reference_structure = [int(cell.get("colspan", 1)) for cell in last_row1.find_all(["td", "th"])]reference_visual_cols = calculate_visual_columns(last_row1)adjust_table_rows_colspan(rows2,@@ -1059,9 +1037,7 @@ def perform_table_merge(first_data_row2,)elif table_cols2 > table_cols1:- reference_structure = [- int(cell.get("colspan", 1)) for cell in first_data_row2.find_all(["td", "th"])- ]+ reference_structure = [int(cell.get("colspan", 1)) for cell in first_data_row2.find_all(["td", "th"])]reference_visual_cols = calculate_visual_columns(first_data_row2)adjust_table_rows_colspan(rows1,@@ -1120,7 +1096,7 @@ def perform_table_merge(previous_state.dirty = True-def merge_table(page_info_list):+def merge_table(page_info_list: list[dict[str, Any]]) -> None:"""合并跨页表格."""state_cache: dict[int, TableMergeState] = {}merged_away_blocks: set[int] = set()@@ -1135,10 +1111,7 @@ def merge_table(page_info_list):if not (page_info["para_blocks"] and page_info["para_blocks"][0]["type"] == BlockType.TABLE):continue- if not (- previous_page_info["para_blocks"]- and previous_page_info["para_blocks"][-1]["type"] == BlockType.TABLE- ):+ if not (previous_page_info["para_blocks"] and previous_page_info["para_blocks"][-1]["type"] == BlockType.TABLE):continuecurrent_table_block = page_info["para_blocks"][0]diff --git a/mineru/utils/title_level_postprocess.py b/mineru/utils/title_level_postprocess.pyindex 344725d0..f3bb9887 100644--- a/mineru/utils/title_level_postprocess.py+++ b/mineru/utils/title_level_postprocess.py@@ -7,8 +7,8 @@ from typing import Anyfrom loguru import logger-from mineru.utils.config_reader import get_llm_aided_config-from mineru.utils.llm_aided import llm_aided_title+from .config_reader import get_llm_aided_config+from .llm_aided import llm_aided_titleSUPPORTED_PDF_BACKENDS = {"pipeline", "vlm", "hybrid"}@@ -24,7 +24,7 @@ def _resolve_title_aided_config() -> dict[str, Any] | None:return deepcopy(title_aided_config)-def apply_title_leveling_to_pdf_info(pdf_info: list[dict[str, Any]]):+def apply_title_leveling_to_pdf_info(pdf_info: list[dict[str, Any]]) -> None:title_aided_config = _resolve_title_aided_config()if title_aided_config:start_time = time.perf_counter()@@ -47,28 +47,16 @@ def finalize_client_side_middle_json(middle_json: dict[str, Any]) -> dict[str, Apdf_info = middle_json.get("pdf_info")if backend == "pipeline":- from mineru.backend.pipeline.model_output_to_middle_json import (- finalize_middle_json_from_preproc,- )+ from mineru.backend.pipeline.model_output_to_middle_json import finalize_middle_json_from_preproc- finalize_middle_json_from_preproc(- pdf_info,- )+ finalize_middle_json_from_preproc(pdf_info)elif backend == "vlm":- from mineru.backend.vlm.model_output_to_middle_json import (- finalize_middle_json,- )+ from mineru.backend.vlm.model_output_to_middle_json import finalize_middle_json- finalize_middle_json(- pdf_info,- )+ finalize_middle_json(pdf_info)elif backend == "hybrid":- from mineru.backend.hybrid.model_output_to_middle_json import (- finalize_middle_json_from_preproc,- )+ from mineru.backend.hybrid.model_output_to_middle_json import finalize_middle_json_from_preproc- finalize_middle_json_from_preproc(- pdf_info,- )+ finalize_middle_json_from_preproc(pdf_info)return middle_jsondiff --git a/mineru/utils/visual_magic_model_utils.py b/mineru/utils/visual_magic_model_utils.pyindex 23e8deca..4ea728df 100644--- a/mineru/utils/visual_magic_model_utils.py+++ b/mineru/utils/visual_magic_model_utils.py@@ -1,14 +1,12 @@# Copyright (c) Opendatalab. All rights reserved.-import re+from __future__ import annotations-from mineru.utils.boxbase import (- bbox_center_distance,- bbox_distance,- calculate_overlap_area_in_bbox1_area_ratio,-)-from mineru.utils.enum_class import BlockType-from mineru.utils.table_continuation import is_table_continuation_text+import re+from typing import Any+from .boxbase import bbox_center_distance, bbox_distance, calculate_overlap_area_in_bbox1_area_ratio+from .enum_class import BlockType+from .table_continuation import is_table_continuation_textIMAGE_BLOCK_BODY = "image_block_body"GENERIC_CHILD_TYPES = (BlockType.CAPTION, BlockType.FOOTNOTE)@@ -56,7 +54,7 @@ VISUAL_TYPE_MAPPING = {}-def isolated_formula_clean(txt):+def isolated_formula_clean(txt: str) -> str:latex = txt[:]if latex.startswith("\\["):latex = latex[2:]@@ -66,7 +64,7 @@ def isolated_formula_clean(txt):return latex-def code_content_clean(content):+def code_content_clean(content: str | None) -> str:"""清理代码内容,移除Markdown代码块的开始和结束标记"""if not content:return ""@@ -86,9 +84,10 @@ def code_content_clean(content):return ""-def clean_content(content):+def clean_content(content: str | None) -> str | None:if content and content.count("\\[") == content.count("\\]") and content.count("\\[") > 0:- def replace_pattern(match):++ def replace_pattern(match: re.Match) -> str:inner_content = match.group(1)return f"[{inner_content}]"@@ -98,7 +97,7 @@ def clean_content(content):return content-def fallback_inline_caption_fragments(blocks, visual_main_types):+def fallback_inline_caption_fragments(blocks: list[dict[str, Any]], visual_main_types: dict[Any, Any] | set[Any]) -> None:"""将紧贴视觉主体上方的同行 text/footnote 片段兜底为通用 caption。"""if len(blocks) < 3:return@@ -129,7 +128,9 @@ def fallback_inline_caption_fragments(blocks, visual_main_types):fallback_stacked_table_caption_fragments(blocks, visual_main_types)-def fallback_leading_table_continuation_captions(blocks, visual_main_types):+def fallback_leading_table_continuation_captions(+ blocks: list[dict[str, Any]], visual_main_types: dict[Any, Any] | set[Any]+) -> None:"""将页首紧贴表格的续表文本兜底为通用 caption。该规则只处理页面有效块开头的 text,避免正文中出现“续表”时被误挂。@@ -141,8 +142,7 @@ def fallback_leading_table_continuation_captions(blocks, visual_main_types):returneffective_blocks = [- block for block in sorted(blocks, key=lambda x: x["index"])- if block.get("type") not in VISUAL_RELATION_IGNORED_TYPES+ block for block in sorted(blocks, key=lambda x: x["index"]) if block.get("type") not in VISUAL_RELATION_IGNORED_TYPES]if len(effective_blocks) < 2:return@@ -172,7 +172,7 @@ def fallback_leading_table_continuation_captions(blocks, visual_main_types):block.pop("merge_prev", None)-def _is_leading_continuation_text_block(block):+def _is_leading_continuation_text_block(block: dict[str, Any]) -> bool:"""判断页首候选块是否是单行续表文本。"""return (block.get("type") in INLINE_CAPTION_FRAGMENT_TYPES@@ -181,16 +181,12 @@ def _is_leading_continuation_text_block(block):)-def _block_text_content(block):+def _block_text_content(block: dict[str, Any]) -> str:"""提取视觉块中的可见文本,用于续表 marker 判断。"""- return "".join(- span.get("content", "")- for line in block.get("lines", [])- for span in line.get("spans", [])- )+ return "".join(span.get("content", "") for line in block.get("lines", []) for span in line.get("spans", []))-def is_transparent_visual_relation_block(block):+def is_transparent_visual_relation_block(block: dict[str, Any]) -> bool:"""判断视觉关系中可忽略的结构性空块。"""if block.get("type") != BlockType.LIST:return False@@ -201,7 +197,7 @@ def is_transparent_visual_relation_block(block):return not _block_text_content(block).strip()-def _is_leading_continuation_cluster_near_table(leading_blocks, table_block):+def _is_leading_continuation_cluster_near_table(leading_blocks: list[dict[str, Any]], table_block: dict[str, Any]) -> bool:"""判断页首续表文本簇是否与后续 table 在几何上相邻。"""next_top = table_block["bbox"][1]max_child_height = 1@@ -223,7 +219,9 @@ def _is_leading_continuation_cluster_near_table(leading_blocks, table_block):return True-def fallback_stacked_table_caption_fragments(blocks, visual_main_types):+def fallback_stacked_table_caption_fragments(+ blocks: list[dict[str, Any]], visual_main_types: dict[Any, Any] | set[Any]+) -> None:"""将 table 上方紧贴标题簇里的 text/footnote 片段兜底为 caption。"""table_main_types = get_table_main_types(visual_main_types)if not table_main_types:@@ -241,30 +239,23 @@ def fallback_stacked_table_caption_fragments(blocks, visual_main_types):if last_caption_pos is None:continue- for block in caption_cluster[last_caption_pos + 1:]:- if (- block.get("type") in INLINE_CAPTION_FRAGMENT_TYPES- and is_single_line_caption_fragment(block)- ):+ for block in caption_cluster[last_caption_pos + 1 :]:+ if block.get("type") in INLINE_CAPTION_FRAGMENT_TYPES and is_single_line_caption_fragment(block):block["type"] = BlockType.CAPTION# fallback 后该块已是视觉 caption 片段,不再参与正文跨块合并。block.pop("merge_prev", None)-def get_table_main_types(visual_main_types):+def get_table_main_types(visual_main_types: dict[Any, Any] | set[Any]) -> set[Any]:"""根据调用方传入的视觉主体类型,找出 table 对应的主体类型。"""if isinstance(visual_main_types, dict):- return {- block_type- for block_type, visual_type in visual_main_types.items()- if visual_type == BlockType.TABLE- }+ return {block_type for block_type, visual_type in visual_main_types.items() if visual_type == BlockType.TABLE}main_types = set(visual_main_types)return main_types & {BlockType.TABLE, BlockType.TABLE_BODY}-def find_stacked_table_caption_cluster(table_block, blocks):+def find_stacked_table_caption_cluster(table_block: dict[str, Any], blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:"""按几何位置收集紧贴 table 上方的 caption/text/footnote 标题簇。"""table_bbox = table_block["bbox"]table_top = table_bbox[1]@@ -300,7 +291,7 @@ def find_stacked_table_caption_cluster(table_block, blocks):return list(reversed(caption_cluster))-def find_last_caption_position(caption_cluster):+def find_last_caption_position(caption_cluster: list[dict[str, Any]]) -> int | None:"""定位标题簇里的最后一个 caption,避免吸收上一张表的尾注。"""for pos in range(len(caption_cluster) - 1, -1, -1):if caption_cluster[pos].get("type") == BlockType.CAPTION:@@ -308,29 +299,26 @@ def find_last_caption_position(caption_cluster):return None-def is_horizontally_near_table(block, table_block):+def is_horizontally_near_table(block: dict[str, Any], table_block: dict[str, Any]) -> bool:"""判断标题簇候选块是否横向落在 table 范围附近。"""table_bbox = table_block["bbox"]block_bbox = block["bbox"]table_width = max(table_bbox[2] - table_bbox[0], 1)tolerance = max(12, table_width * 0.03)- return not (- block_bbox[2] < table_bbox[0] - tolerance- or block_bbox[0] > table_bbox[2] + tolerance- )+ return not (block_bbox[2] < table_bbox[0] - tolerance or block_bbox[0] > table_bbox[2] + tolerance)-def is_single_line_caption_fragment(block):+def is_single_line_caption_fragment(block: dict[str, Any]) -> bool:"""判断待兜底片段是否是单行块,避免吞掉多行正文。"""return len(block.get("lines") or [None]) <= 1-def stacked_caption_max_gap(block_height):+def stacked_caption_max_gap(block_height: float) -> float:"""计算堆叠标题簇允许的最大纵向间距。"""return max(12, block_height * 1.5)-def find_previous_effective_block(ordered_blocks, pos):+def find_previous_effective_block(ordered_blocks: list[dict[str, Any]], pos: int) -> dict[str, Any] | None:"""向前查找参与视觉关系判断的有效块,跳过页眉页脚等外围块。"""for index in range(pos - 1, -1, -1):block = ordered_blocks[index]@@ -339,7 +327,7 @@ def find_previous_effective_block(ordered_blocks, pos):return None-def find_next_effective_block(ordered_blocks, pos):+def find_next_effective_block(ordered_blocks: list[dict[str, Any]], pos: int) -> dict[str, Any] | None:"""向后查找参与视觉关系判断的有效块,跳过页眉页脚等外围块。"""for index in range(pos + 1, len(ordered_blocks)):block = ordered_blocks[index]@@ -348,7 +336,9 @@ def find_next_effective_block(ordered_blocks, pos):return None-def is_inline_caption_fragment(previous_caption, text_block, next_visual):+def is_inline_caption_fragment(+ previous_caption: dict[str, Any], text_block: dict[str, Any], next_visual: dict[str, Any]+) -> bool:"""判断当前块是否是前一 caption 的同行补充片段。"""caption_bbox = previous_caption["bbox"]text_bbox = text_block["bbox"]@@ -359,14 +349,8 @@ def is_inline_caption_fragment(previous_caption, text_block, next_visual):min_text_height = max(min(caption_height, text_height), 1)vertical_overlap = min(caption_bbox[3], text_bbox[3]) - max(caption_bbox[1], text_bbox[1])- center_y_diff = abs(- ((caption_bbox[1] + caption_bbox[3]) / 2)- - ((text_bbox[1] + text_bbox[3]) / 2)- )- is_same_line = (- vertical_overlap / min_text_height >= 0.6- or center_y_diff <= max(caption_height, text_height) * 0.5- )+ center_y_diff = abs(((caption_bbox[1] + caption_bbox[3]) / 2) - ((text_bbox[1] + text_bbox[3]) / 2))+ is_same_line = vertical_overlap / min_text_height >= 0.6 or center_y_diff <= max(caption_height, text_height) * 0.5if not is_same_line:return False@@ -375,30 +359,16 @@ def is_inline_caption_fragment(previous_caption, text_block, next_visual):return 0 <= vertical_gap_to_visual <= max_allowed_gap-def regroup_visual_blocks(blocks):+def regroup_visual_blocks(blocks: list[dict[str, Any]]) -> tuple[dict[Any, list[dict[str, Any]]], list[dict[str, Any]]]:ordered_blocks = sorted(blocks, key=lambda x: x["index"])absorbed_member_indices, sub_images_by_index = absorb_image_block_members(ordered_blocks)- effective_blocks = [- block for block in ordered_blocks if block["index"] not in absorbed_member_indices- ]- visual_relation_blocks = [- block- for block in effective_blocks- if not is_transparent_visual_relation_block(block)- ]- position_by_index = {- block["index"]: pos for pos, block in enumerate(visual_relation_blocks)- }- main_blocks = [- block for block in visual_relation_blocks if block["type"] in VISUAL_MAIN_TYPES- ]- child_blocks = [- block for block in visual_relation_blocks if block["type"] in GENERIC_CHILD_TYPES- ]+ effective_blocks = [block for block in ordered_blocks if block["index"] not in absorbed_member_indices]+ visual_relation_blocks = [block for block in effective_blocks if not is_transparent_visual_relation_block(block)]+ position_by_index = {block["index"]: pos for pos, block in enumerate(visual_relation_blocks)}+ main_blocks = [block for block in visual_relation_blocks if block["type"] in VISUAL_MAIN_TYPES]+ child_blocks = [block for block in visual_relation_blocks if block["type"] in GENERIC_CHILD_TYPES]- grouped_children = {- block["index"]: {"captions": [], "footnotes": []} for block in main_blocks- }+ grouped_children = {block["index"]: {"captions": [], "footnotes": []} for block in main_blocks}unmatched_child_blocks = []for main_block in main_blocks:@@ -474,15 +444,9 @@ def regroup_visual_blocks(blocks):return grouped_blocks, unmatched_child_blocks-def absorb_image_block_members(blocks):- image_block_bodies = [- block for block in blocks if block["type"] == IMAGE_BLOCK_BODY- ]- member_candidates = [- block- for block in blocks- if block["type"] in [BlockType.IMAGE_BODY, BlockType.CHART_BODY]- ]+def absorb_image_block_members(blocks: list[dict[str, Any]]) -> tuple[set[int], dict[int, list[dict[str, Any]]]]:+ image_block_bodies = [block for block in blocks if block["type"] == IMAGE_BLOCK_BODY]+ member_candidates = [block for block in blocks if block["type"] in [BlockType.IMAGE_BODY, BlockType.CHART_BODY]]assignments = {}for member in member_candidates:@@ -511,11 +475,7 @@ def absorb_image_block_members(blocks):absorbed_member_indices = set()sub_images_by_index = {}for image_block in image_block_bodies:- members = [- member- for member in member_candidates- if assignments.get(member["index"]) == image_block["index"]- ]+ members = [member for member in member_candidates if assignments.get(member["index"]) == image_block["index"]]if not members:continue@@ -533,13 +493,13 @@ def absorb_image_block_members(blocks):def find_best_visual_parent(- child_block,- main_blocks,- ordered_blocks,- position_by_index,- main_type_to_visual_type=None,- type_by_index=None,-):+ child_block: dict[str, Any],+ main_blocks: list[dict[str, Any]],+ ordered_blocks: list[dict[str, Any]],+ position_by_index: dict[int, int],+ main_type_to_visual_type: dict[Any, Any] | None = None,+ type_by_index: dict[int, str] | None = None,+) -> dict[str, Any] | None:"""为通用 caption/footnote 查找最合适的视觉主体。"""if main_type_to_visual_type is None:main_type_to_visual_type = VISUAL_MAIN_TYPES@@ -584,8 +544,7 @@ def find_best_visual_parent(return closest_index_candidates[0]edge_distances = [- (main_block, bbox_distance(child_block["bbox"], main_block["bbox"]))- for main_block in closest_index_candidates+ (main_block, bbox_distance(child_block["bbox"], main_block["bbox"])) for main_block in closest_index_candidates]edge_values = [edge_distance for _, edge_distance in edge_distances]if max(edge_values) - min(edge_values) > 2:@@ -595,13 +554,9 @@ def find_best_visual_parent()[0]child_type = block_type(child_block, type_by_index)- if (- child_type == BlockType.CAPTION- and all(- main_type_to_visual_type.get(block_type(main_block, type_by_index))- == BlockType.TABLE- for main_block in closest_index_candidates- )+ if child_type == BlockType.CAPTION and all(+ main_type_to_visual_type.get(block_type(main_block, type_by_index)) == BlockType.TABLE+ for main_block in closest_index_candidates):# 表格 caption 位于两个表之间且距离接近时,优先归属后一个表。return max(closest_index_candidates, key=lambda x: x["index"])@@ -620,15 +575,13 @@ def find_best_visual_parent(def effective_visual_index_diff(- child_block,- main_block,- ordered_blocks,- type_by_index=None,-):+ child_block: dict[str, Any],+ main_block: dict[str, Any],+ ordered_blocks: list[dict[str, Any]],+ type_by_index: dict[int, str] | None = None,+) -> int:"""按有效块序列计算视觉子块与主体距离,吸收的 image 子成员视为零成本。"""- position_by_index = {- block["index"]: position for position, block in enumerate(ordered_blocks)- }+ position_by_index = {block["index"]: position for position, block in enumerate(ordered_blocks)}child_pos = position_by_index[child_block["index"]]main_pos = position_by_index[main_block["index"]]start_pos = min(child_pos, main_pos)@@ -636,7 +589,7 @@ def effective_visual_index_diff(skipped_child_count = 0child_type = block_type(child_block, type_by_index)- for block in ordered_blocks[start_pos + 1:end_pos]:+ for block in ordered_blocks[start_pos + 1 : end_pos]:if block_type(block, type_by_index) == child_type:skipped_child_count += 1@@ -644,12 +597,12 @@ def effective_visual_index_diff(def is_visual_neighbor(- child_block,- main_block,- ordered_blocks,- position_by_index,- type_by_index=None,-):+ child_block: dict[str, Any],+ main_block: dict[str, Any],+ ordered_blocks: list[dict[str, Any]],+ position_by_index: dict[int, int],+ type_by_index: dict[int, str] | None = None,+) -> bool:child_type = block_type(child_block, type_by_index)if child_type == BlockType.FOOTNOTE and child_block["index"] < main_block["index"]:return False@@ -675,7 +628,7 @@ def is_visual_neighbor(return True-def is_block_outside_visual_gap(between_block, child_block, main_block):+def is_block_outside_visual_gap(between_block: dict[str, Any], child_block: dict[str, Any], main_block: dict[str, Any]) -> bool:"""判断阅读顺序夹在中间的块是否没有落入视觉父子块的垂直间隔。"""visual_gap = vertical_gap_between_blocks(child_block, main_block)if visual_gap is None:@@ -694,7 +647,7 @@ def is_block_outside_visual_gap(between_block, child_block, main_block):return False-def vertical_gap_between_blocks(first_block, second_block):+def vertical_gap_between_blocks(first_block: dict[str, Any], second_block: dict[str, Any]) -> tuple[float, float] | None:"""计算两个块上下分离时的垂直间隔;发生纵向重叠时保持严格阻断。"""first_bbox = first_block["bbox"]second_bbox = second_block["bbox"]@@ -705,21 +658,18 @@ def vertical_gap_between_blocks(first_block, second_block):return None-def is_bbox_intersecting_vertical_gap(bbox, vertical_gap):+def is_bbox_intersecting_vertical_gap(bbox: list[float], vertical_gap: tuple[float, float]) -> bool:"""判断 bbox 是否与视觉父子块之间的垂直间隔相交。"""gap_top, gap_bottom = vertical_gapreturn bbox[1] < gap_bottom and bbox[3] > gap_top-def is_bbox_overlapping_visual_relation_block(bbox, child_bbox, main_bbox):+def is_bbox_overlapping_visual_relation_block(bbox: list[float], child_bbox: list[float], main_bbox: list[float]) -> bool:"""判断 bbox 是否覆盖到父子块本身;覆盖时不能当作普通 index 噪声跳过。"""- return (- are_bboxes_overlapping(bbox, child_bbox)- or are_bboxes_overlapping(bbox, main_bbox)- )+ return are_bboxes_overlapping(bbox, child_bbox) or are_bboxes_overlapping(bbox, main_bbox)-def are_bboxes_overlapping(first_bbox, second_bbox):+def are_bboxes_overlapping(first_bbox: list[float], second_bbox: list[float]) -> bool:"""判断两个 bbox 是否存在二维相交。"""return not (first_bbox[2] <= second_bbox[0]@@ -729,30 +679,30 @@ def are_bboxes_overlapping(first_bbox, second_bbox):)-def block_type(block, type_by_index=None):+def block_type(block: dict[str, Any], type_by_index: dict[int, str] | None = None) -> str:"""读取块类型;pipeline 会传入改写前的原始类型映射。"""if type_by_index is not None:return type_by_index[block["index"]]return block["type"]-def child_kind_from_type(block_type):+def child_kind_from_type(block_type: str) -> str:if block_type == BlockType.CAPTION:return "caption"return "footnote"-def child_visual_type(block_type):+def child_visual_type(block_type: str) -> str:if block_type == BlockType.CHART_BODY:return BlockType.CHARTreturn BlockType.IMAGE-def bbox_area(bbox):+def bbox_area(bbox: list[float]) -> float:return max(0, bbox[2] - bbox[0]) * max(0, bbox[3] - bbox[1])-def relative_bbox(child_bbox, parent_bbox):+def relative_bbox(child_bbox: list[float], parent_bbox: list[float]) -> list[float]:parent_x0, parent_y0, parent_x1, parent_y1 = parent_bboxparent_w = max(parent_x1 - parent_x0, 1)parent_h = max(parent_y1 - parent_y0, 1)@@ -764,5 +714,5 @@ def relative_bbox(child_bbox, parent_bbox):]-def clamp_and_round(value):+def clamp_and_round(value: float) -> float:return round(min(max(value, 0.0), 1.0), 3)