Skip to content

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

perf: Optimize PDF text span extraction and block matching for faster, more accurate text recovery

myhlolidd61cd227c49
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index 59a64e93..c0300d3c 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -8,7 +8,7 @@ from mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
from mineru.utils.enum_class import ContentType, BlockType, NotExtractType
from mineru.utils.guess_suffix_or_lang import guess_language_by_text
from mineru.utils.span_block_fix import fix_text_block
-from mineru.utils.span_pre_proc import txt_spans_extract
+from mineru.utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
from mineru.utils.visual_magic_model_utils import (
GENERIC_CHILD_TYPES,
IMAGE_BLOCK_BODY,
@@ -90,6 +90,7 @@ class MagicModel:
[virtual_block],
[],
)
+ span_matcher = SpanBlockMatcher(page_text_inline_formula_spans)
# 解析每个块
for index, block_info in enumerate(self.page_blocks):
@@ -285,20 +286,7 @@ class MagicModel:
block["cell_merge"] = block_info["cell_merge"]
_copy_raw_text_block_metadata(raw_block_type, block_info, block)
else:
- block_spans = []
- for span in page_text_inline_formula_spans:
- if (
- calculate_overlap_area_in_bbox1_area_ratio(
- span["bbox"],
- block_bbox,
- )
- > 0.5
- ):
- block_spans.append(span)
-
- if block_spans:
- for span in block_spans:
- page_text_inline_formula_spans.remove(span)
+ block_spans = span_matcher.collect_for_block(block_bbox)
block = {
"bbox": block_bbox,
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index e60a3a04..59c5360f 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -9,7 +9,7 @@ from mineru.utils.enum_class import ContentType, BlockType
from mineru.utils.guess_suffix_or_lang import guess_language_by_text
from mineru.utils.span_block_fix import merge_spans_to_vertical_line, vertical_line_sort_spans_from_top_to_bottom, \
merge_spans_to_line, line_sort_spans_by_left_to_right, is_vertical_text_block_by_spans
-from mineru.utils.span_pre_proc import txt_spans_extract
+from mineru.utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
from mineru.utils.visual_magic_model_utils import (
fallback_inline_caption_fragments,
find_best_visual_parent,
@@ -206,6 +206,7 @@ class MagicModel:
def __build_page_blocks(self):
span_type = "unknown"
+ span_matcher = SpanBlockMatcher(self.page_text_inline_formula_spans)
for block in self.page_blocks:
if block["type"] in [
BlockType.ABSTRACT,
@@ -265,28 +266,25 @@ class MagicModel:
block["lines"] = [line]
else:
# span填充
- block_spans = []
- for span in self.page_text_inline_formula_spans:
- overlap_ratio = calculate_overlap_area_in_bbox1_area_ratio(
- span['bbox'], block["bbox"]
+ if block["type"] == BlockType.FORMULA_NUMBER:
+ block_spans = span_matcher.collect_for_block(
+ block["bbox"],
+ overlap_ratio_getter=self.__formula_number_overlap_ratio,
)
- if block["type"] == BlockType.FORMULA_NUMBER:
- # OCR 检测框通常会比公式编号框更大,使用最小框重叠比避免编号文字无法回填。
- overlap_ratio = max(
- overlap_ratio,
- calculate_overlap_area_2_minbox_area_ratio(
- span['bbox'], block["bbox"]
- ),
- )
- if overlap_ratio > 0.5:
- block_spans.append(span)
- # 从spans删除已经放入block_spans中的span
- if len(block_spans) > 0:
- for span in block_spans:
- self.page_text_inline_formula_spans.remove(span)
+ else:
+ block_spans = span_matcher.collect_for_block(block["bbox"])
block["spans"] = block_spans
block = self.__fix_text_block(block)
+ self.page_text_inline_formula_spans = span_matcher.remaining_spans()
+
+ @staticmethod
+ def __formula_number_overlap_ratio(span, block_bbox):
+ """公式编号框较窄时,沿用最小框重叠比例提高回填召回。"""
+ return max(
+ calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block_bbox),
+ calculate_overlap_area_2_minbox_area_ratio(span['bbox'], block_bbox),
+ )
def __fix_axis(self):
need_remove_list = []
diff --git a/mineru/utils/pdf_text_tool.py b/mineru/utils/pdf_text_tool.py
index 999827e9..a1321de1 100644
--- a/mineru/utils/pdf_text_tool.py
+++ b/mineru/utils/pdf_text_tool.py
@@ -15,8 +15,33 @@ def get_page(
superscript_height_threshold: float = 0.7,
line_distance_threshold: float = 0.1,
) -> dict:
+ page_chars = get_page_chars(page, quote_loosebox=quote_loosebox)
+ lines = get_lines_from_chars(
+ page_chars["chars"],
+ superscript_height_threshold=superscript_height_threshold,
+ line_distance_threshold=line_distance_threshold,
+ )
+ blocks = get_blocks(lines)
+
+ return {
+ "bbox": page_chars["bbox"],
+ "width": page_chars["width"],
+ "height": page_chars["height"],
+ "rotation": page_chars["rotation"],
+ "blocks": blocks,
+ }
+
+
+def get_page_chars(
+ page: pdfium.PdfPage,
+ textpage=None,
+ quote_loosebox: bool = True,
+ page_char_count: int | None = None,
+) -> dict:
+ """轻量读取页面字符坐标,供只需要 char 级信息的路径复用。"""
with pdfium_guard():
- textpage = page.get_textpage()
+ if textpage is None:
+ textpage = page.get_textpage()
page_bbox: List[float] = page.get_bbox()
page_width = math.ceil(abs(page_bbox[2] - page_bbox[0]))
page_height = math.ceil(abs(page_bbox[1] - page_bbox[3]))
@@ -27,26 +52,38 @@ def get_page(
except Exception:
pass
+ if page_char_count is None:
+ page_char_count = textpage.count_chars()
+
chars = deduplicate_chars(
get_chars(textpage, page_bbox, page_rotation, quote_loosebox)
)
- spans = get_spans(
- chars,
- superscript_height_threshold=superscript_height_threshold,
- line_distance_threshold=line_distance_threshold,
- )
- lines = get_lines(spans)
- assign_scripts(
- lines,
- height_threshold=superscript_height_threshold,
- line_distance_threshold=line_distance_threshold,
- )
- blocks = get_blocks(lines)
-
- return {
- "bbox": page_bbox,
- "width": page_width,
- "height": page_height,
- "rotation": page_rotation,
- "blocks": blocks,
- }
+
+ return {
+ "bbox": page_bbox,
+ "width": page_width,
+ "height": page_height,
+ "rotation": page_rotation,
+ "char_count": page_char_count,
+ "chars": chars,
+ }
+
+
+def get_lines_from_chars(
+ chars,
+ superscript_height_threshold: float = 0.7,
+ line_distance_threshold: float = 0.1,
+):
+ """从已提取的字符构建 pdftext lines,避免重复读取 PDFium textpage。"""
+ spans = get_spans(
+ chars,
+ superscript_height_threshold=superscript_height_threshold,
+ line_distance_threshold=line_distance_threshold,
+ )
+ lines = get_lines(spans)
+ assign_scripts(
+ lines,
+ height_threshold=superscript_height_threshold,
+ line_distance_threshold=line_distance_threshold,
+ )
+ return lines
diff --git a/mineru/utils/span_pre_proc.py b/mineru/utils/span_pre_proc.py
index cd441c5a..855cc0da 100644
--- a/mineru/utils/span_pre_proc.py
+++ b/mineru/utils/span_pre_proc.py
@@ -11,7 +11,8 @@ from 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_page
+from mineru.utils.pdf_text_tool import get_lines_from_chars, get_page_chars
+from mineru.utils.pdfium_guard import pdfium_guard
MAX_NATIVE_TEXT_CHARS_PER_PAGE = 65535
@@ -32,8 +33,11 @@ def __replace_unicode(text: str):
"""pdf_text dict方案 char级别"""
def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discarded_blocks):
page_char_count = None
+ textpage = None
try:
- page_char_count = pdf_page.get_textpage().count_chars()
+ with pdfium_guard():
+ textpage = pdf_page.get_textpage()
+ page_char_count = textpage.count_chars()
except Exception as exc:
logger.debug(f"Failed to get page char count before txt extraction: {exc}")
@@ -47,20 +51,15 @@ def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discarded
]
return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
- page_dict = get_page(pdf_page)
-
- page_all_chars = []
- page_all_lines = []
- for block in page_dict['blocks']:
- for line in block['lines']:
- rotation_degrees = math.degrees(line['rotation'])
- # 旋转角度不为0, 90, 180, 270的行,直接跳过(rotation_degrees的值可能不为整数)
- if not any(abs(rotation_degrees - angle) < 0.1 for angle in [0, 90, 180, 270]):
- continue
- page_all_lines.append(line)
- for span in line['spans']:
- for char in span['chars']:
- page_all_chars.append(char)
+ page_chars = get_page_chars(
+ pdf_page,
+ textpage=textpage,
+ page_char_count=page_char_count,
+ )
+ page_all_chars = [
+ char for char in page_chars['chars']
+ if _is_supported_rotation(char['rotation'])
+ ]
# 计算所有sapn的高度的中位数
span_height_list = []
@@ -95,6 +94,10 @@ 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'])
+ ]
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:
@@ -119,6 +122,12 @@ def txt_spans_extract(pdf_page, spans, pil_img, scale, all_bboxes, all_discarded
return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
+def _is_supported_rotation(rotation) -> 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):
if len(need_ocr_spans) == 0:
return spans
@@ -140,27 +149,116 @@ def _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale):
return spans
+class SpanBlockMatcher:
+ """按 block 顺序消费 span,并用 y 方向索引减少无效重叠计算。"""
+
+ def __init__(self, spans):
+ 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):
+ """根据 span 高度估算索引网格大小,避免过细或过粗。"""
+ heights = [
+ 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 1
+ return max(1, statistics.median(heights))
+
+ def _build_grid(self, spans):
+ """将 span 按 y 方向网格登记,后续按 block bbox 快速取候选。"""
+ grid = collections.defaultdict(list)
+ for index, span in enumerate(spans):
+ bbox = span.get('bbox')
+ if not bbox:
+ continue
+ start_cell, end_cell = self._cell_range(bbox)
+ for cell_idx in range(start_cell, end_cell + 1):
+ grid[cell_idx].append(index)
+ return grid
+
+ def _cell_range(self, bbox):
+ """计算 bbox 覆盖的 y 方向网格范围。"""
+ return (
+ int(bbox[1] / self.grid_size),
+ int(bbox[3] / self.grid_size),
+ )
+
+ def _candidate_indices_for_block(self, block_bbox):
+ """取出与 block 纵向范围可能相交的 span 原始索引。"""
+ start_cell, end_cell = self._cell_range(block_bbox)
+ candidate_indices = set()
+ for cell_idx in range(start_cell, end_cell + 1):
+ 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):
+ """返回当前 block 命中的 span,并标记为已消费以保持旧归属语义。"""
+ if overlap_ratio_getter is None:
+ overlap_ratio_getter = self._default_overlap_ratio
+
+ block_spans = []
+ for span_idx in self._candidate_indices_for_block(block_bbox):
+ if span_idx in self.used_span_indices:
+ continue
+ span = self.spans[span_idx]
+ if overlap_ratio_getter(span, block_bbox) > threshold:
+ block_spans.append(span)
+ self.used_span_indices.add(span_idx)
+ return block_spans
+
+ def remaining_spans(self):
+ """返回尚未归属到任何 block 的 span,方便保持后续兼容。"""
+ 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):
+ """默认沿用旧逻辑:计算 span 面积中落入 block 的比例。"""
+ return calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block_bbox)
+
+
def fill_char_in_spans(spans, all_chars, median_span_height):
# 简单从上到下排一下序
spans = sorted(spans, key=lambda x: x['bbox'][1])
- grid_size = median_span_height
+ grid_size = max(1, median_span_height)
grid = collections.defaultdict(list)
+ span_bboxes = []
for i, span in enumerate(spans):
- start_cell = int(span['bbox'][1] / grid_size)
- end_cell = int(span['bbox'][3] / grid_size)
+ 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)
for cell_idx in range(start_cell, end_cell + 1):
grid[cell_idx].append(i)
for char in all_chars:
- char_center_y = (char['bbox'][1] + char['bbox'][3]) / 2
+ char_bbox = char['bbox']
+ char_center_x = (char_bbox[0] + char_bbox[2]) / 2
+ char_center_y = (char_bbox[1] + char_bbox[3]) / 2
cell_idx = int(char_center_y / grid_size)
candidate_span_indices = grid.get(cell_idx, [])
for span_idx in candidate_span_indices:
span = spans[span_idx]
- if calculate_char_in_span(char['bbox'], span['bbox'], char['char']):
+ span_bbox = span_bboxes[span_idx]
+ if (
+ char['char'] not in LINE_STOP_FLAG
+ and char['char'] not in LINE_START_FLAG
+ and 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)
break
@@ -217,8 +315,13 @@ def calculate_char_in_span(char_bbox, span_bbox, char, span_height_ratio=Span_He
def chars_to_content(span):
# 检查span中的char是否为空
if len(span['chars']) != 0:
- # 给chars按char_idx排序
- chars = sorted(span['chars'], key=lambda x: x['char_idx'])
+ 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'])
# Calculate the width of each character
char_widths = [char['bbox'][2] - char['bbox'][0] for char in chars]
@@ -244,7 +347,6 @@ def chars_to_content(span):
content = ''.join(parts)
content = __replace_unicode(content)
content = __replace_ligatures(content)
- content = __replace_ligatures(content)
span['content'] = content.strip()
del span['chars']