Skip to content

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

feat: implement formula number processing functions and optimize hybrid flash layout handling

myhloli41e100267f60
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 46cf05ed..aaa548d0 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -25,6 +25,8 @@ from mineru.backend.pipeline.model_init import (
run_mfr_inference,
run_ocr_inference,
)
+from mineru.backend.pipeline.model_list import AtomicModel
+from mineru.backend.utils.formula_number import optimize_flash_formula_number_blocks
from mineru.backend.vlm.vlm_analyze import (
ModelSingleton,
aio_predictor_execution_guard,
@@ -70,7 +72,7 @@ FLASH_LAYOUT_LABEL_TO_VLM_TYPE = {
"footer": BlockType.FOOTER,
"footer_image": BlockType.FOOTER,
"footnote": BlockType.PAGE_FOOTNOTE,
- "formula_number": BlockType.TEXT,
+ "formula_number": BlockType.FORMULA_NUMBER,
"header": BlockType.HEADER,
"header_image": BlockType.HEADER,
"number": BlockType.PAGE_NUMBER,
@@ -330,6 +332,42 @@ def _layout_det_bbox_to_unit(layout_det, page_width, page_height):
return bbox_item["bbox"]
+def _layout_det_bbox_to_pixel(layout_det, page_width, page_height):
+ """将layout bbox转换为页面像素坐标,兼容归一化和像素两种输入。"""
+ bbox = layout_det.get("bbox")
+ if bbox is None or len(bbox) != 4:
+ return None
+
+ x0, y0, x1, y1 = [float(v) for v in bbox]
+ if (
+ 0.0 <= x0 <= 1.0
+ and 0.0 <= y0 <= 1.0
+ and 0.0 <= x1 <= 1.0
+ and 0.0 <= y1 <= 1.0
+ ):
+ x0, x1 = x0 * page_width, x1 * page_width
+ y0, y1 = y0 * page_height, y1 * page_height
+
+ x0 = max(0, min(page_width, x0))
+ y0 = max(0, min(page_height, y0))
+ x1 = max(0, min(page_width, x1))
+ y1 = max(0, min(page_height, y1))
+ if x1 <= x0 or y1 <= y0:
+ return None
+ return [x0, y0, x1, y1]
+
+
+def _normalize_flash_vlm_angle(angle):
+ """将pipeline方向标签转换为mineru-vl-utils接受的整数角度。"""
+ try:
+ normalized_angle = int(angle)
+ except (TypeError, ValueError):
+ return 0
+ if normalized_angle in {0, 90, 180, 270}:
+ return normalized_angle
+ return 0
+
+
def _build_flash_vlm_layout_blocks(layout_dets, page_width, page_height):
"""用 pipeline layout 构造 VLM 外部 layout 输入,跳过 VLM 自身 layout 解析。"""
blocks = []
@@ -345,7 +383,7 @@ def _build_flash_vlm_layout_blocks(layout_dets, page_width, page_height):
block = ContentBlock(
vlm_type,
bbox,
- angle=layout_det.get("angle", 0),
+ angle=_normalize_flash_vlm_angle(layout_det.get("angle", 0)),
content=layout_det.get("content"),
)
except AssertionError as exc:
@@ -355,6 +393,55 @@ def _build_flash_vlm_layout_blocks(layout_dets, page_width, page_height):
return blocks
+def _apply_flash_table_orientation_labels(
+ images_pil_list,
+ images_layout_res,
+ hybrid_pipeline_model,
+ batch_ratio: int = 1,
+):
+ """复用pipeline表格方向分类,为Hybrid flash的table layout写入VLM旋转角度。"""
+ table_inputs = []
+ table_layout_refs = []
+ for pil_img, layout_res in zip(images_pil_list, images_layout_res):
+ page_width, page_height = pil_img.size
+ for layout_det in layout_res or []:
+ if layout_det.get("label") != "table":
+ continue
+ pixel_bbox = _layout_det_bbox_to_pixel(layout_det, page_width, page_height)
+ if pixel_bbox is None:
+ continue
+ try:
+ table_img, _ = crop_img({"bbox": pixel_bbox}, pil_img)
+ except Exception as exc:
+ logger.warning(
+ f"Skip Hybrid flash table orientation crop: {layout_det}, error: {exc}"
+ )
+ continue
+ table_inputs.append({"table_img": table_img})
+ table_layout_refs.append(layout_det)
+
+ if not table_inputs:
+ return
+
+ try:
+ table_orientation_cls_model = hybrid_pipeline_model.atom_model_manager.get_atom_model(
+ atom_model_name=AtomicModel.TableOrientationCls,
+ lang=getattr(hybrid_pipeline_model, "lang", None),
+ )
+ rotate_labels = table_orientation_cls_model.batch_predict(
+ table_inputs,
+ det_batch_size=max(1, batch_ratio * OCR_DET_BASE_BATCH_SIZE),
+ )
+ if len(rotate_labels) != len(table_layout_refs):
+ raise ValueError("Table orientation prediction result count mismatch")
+ for layout_det, rotate_label in zip(table_layout_refs, rotate_labels):
+ layout_det["angle"] = str(rotate_label or "0")
+ except Exception as exc:
+ logger.warning(
+ f"Hybrid flash table orientation classification failed: {exc}, using original table images"
+ )
+
+
def _formula_item_to_pixel_bbox(item):
bbox = item.get('bbox')
if bbox is not None and len(bbox) == 4:
@@ -891,6 +978,12 @@ def doc_analyze(
_vlm_ocr_enable,
)
if mode == "flash":
+ _apply_flash_table_orientation_labels(
+ images_pil_list,
+ images_layout_res,
+ hybrid_pipeline_model,
+ batch_ratio=batch_ratio,
+ )
vlm_blocks_list = [
_build_flash_vlm_layout_blocks(
page_layout_res,
@@ -906,6 +999,7 @@ def doc_analyze(
not_extract_list=None if _vlm_ocr_enable else not_extract_list,
image_analysis=image_analysis,
)
+ optimize_flash_formula_number_blocks(window_model_list)
if _vlm_ocr_enable:
_apply_vlm_ocr_det_sidecars_for_window(
images_pil_list,
@@ -1092,6 +1186,13 @@ async def aio_doc_analyze(
_vlm_ocr_enable,
)
if mode == "flash":
+ await asyncio.to_thread(
+ _apply_flash_table_orientation_labels,
+ images_pil_list,
+ images_layout_res,
+ hybrid_pipeline_model,
+ batch_ratio,
+ )
vlm_blocks_list = [
_build_flash_vlm_layout_blocks(
page_layout_res,
@@ -1107,6 +1208,7 @@ async def aio_doc_analyze(
not_extract_list=None if _vlm_ocr_enable else not_extract_list,
image_analysis=image_analysis,
)
+ optimize_flash_formula_number_blocks(window_model_list)
if _vlm_ocr_enable:
await asyncio.to_thread(
_apply_vlm_ocr_det_sidecars_for_window,
diff --git a/mineru/backend/pipeline/model_json_to_middle_json.py b/mineru/backend/pipeline/model_json_to_middle_json.py
index 5c4cc9b9..dcd66c40 100644
--- a/mineru/backend/pipeline/model_json_to_middle_json.py
+++ b/mineru/backend/pipeline/model_json_to_middle_json.py
@@ -4,13 +4,13 @@ import copy
from tqdm import tqdm
from mineru.backend.utils.html_image_utils import replace_inline_table_images
+from mineru.backend.utils.formula_number import optimize_formula_number_blocks
from mineru.backend.utils.runtime_utils import cross_page_table_merge
from mineru.backend.pipeline.model_init import (
AtomModelSingleton,
run_ocr_inference,
)
from mineru.backend.pipeline.para_split import para_split
-from mineru.utils.char_utils import full_to_half
from mineru.utils.cut_image import cut_image_and_table
from mineru.utils.enum_class import ContentType, BlockType
from mineru.utils.title_level_postprocess import apply_title_leveling_to_pdf_info
@@ -136,15 +136,6 @@ def append_batch_results_to_middle_json(
)
-def _extract_text_from_block(block):
- text_parts = []
- for line in block.get("lines", []):
- for span in line.get("spans", []):
- if span.get("type") == ContentType.TEXT:
- text_parts.append(span.get("content", ""))
- return "".join(text_parts).strip()
-
-
def _iter_block_spans(block):
for line in block.get("lines", []):
for span in line.get("spans", []):
@@ -154,61 +145,6 @@ def _iter_block_spans(block):
yield from _iter_block_spans(sub_block)
-def _normalize_formula_tag_content(tag_content):
- tag_content = full_to_half(tag_content.strip())
- if tag_content.startswith("("):
- tag_content = tag_content[1:].strip()
- if tag_content.endswith(")"):
- tag_content = tag_content[:-1].strip()
- return tag_content
-
-
-def _get_interline_equation_span(block):
- for line in block.get("lines", []):
- for span in line.get("spans", []):
- if span.get("type") == ContentType.INTERLINE_EQUATION:
- return span
- return None
-
-
-def _append_formula_number_tag(equation_block, formula_number_block):
- equation_span = _get_interline_equation_span(equation_block)
- tag_content = _normalize_formula_tag_content(_extract_text_from_block(formula_number_block))
- if equation_span is not None:
- formula = equation_span.get("content", "")
- equation_span["content"] = f"{formula}\\tag{{{tag_content}}}"
-
-
-def _optimize_formula_number_blocks(pdf_info_list):
- for page_info in pdf_info_list:
- optimized_blocks = []
- blocks = page_info.get("preproc_blocks", [])
- for index, block in enumerate(blocks):
- if block.get("type") != BlockType.FORMULA_NUMBER:
- optimized_blocks.append(block)
- continue
-
- prev_block = blocks[index - 1] if index > 0 else None
- if prev_block and prev_block.get("type") == BlockType.INTERLINE_EQUATION:
- _append_formula_number_tag(prev_block, block)
- continue
-
- next_block = blocks[index + 1] if index + 1 < len(blocks) else None
- next_next_block = blocks[index + 2] if index + 2 < len(blocks) else None
- if (
- next_block
- and next_block.get("type") == BlockType.INTERLINE_EQUATION
- and (next_next_block is None or next_next_block.get("type") != BlockType.FORMULA_NUMBER)
- ):
- _append_formula_number_tag(next_block, block)
- continue
-
- block["type"] = BlockType.TEXT
- optimized_blocks.append(block)
-
- page_info["preproc_blocks"] = optimized_blocks
-
-
def _apply_post_ocr(pdf_info_list, lang=None):
need_ocr_list = []
img_crop_list = []
@@ -279,7 +215,7 @@ def apply_server_side_postprocess(pdf_info_list, lang=None):
def finalize_middle_json_from_preproc(pdf_info_list):
"""从 preproc_blocks 执行确定性 finalize,供服务端完整路径和客户端复用。"""
- _optimize_formula_number_blocks(pdf_info_list)
+ optimize_formula_number_blocks(pdf_info_list)
para_split(pdf_info_list)
cross_page_table_merge(pdf_info_list)
apply_title_leveling_to_pdf_info(pdf_info_list)
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index fa82e223..30f43b05 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -1,10 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
from mineru.backend.pipeline.para_split import ListLineTag
from mineru.backend.pipeline.pipeline_middle_json_mkcontent import _merge_para_text
-from mineru.utils.boxbase import (
- calculate_overlap_area_2_minbox_area_ratio,
- calculate_overlap_area_in_bbox1_area_ratio,
-)
+from mineru.backend.utils.formula_number import formula_number_max_overlap_ratio
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, \
@@ -286,7 +283,7 @@ class MagicModel:
if block["type"] == BlockType.FORMULA_NUMBER:
block_spans = span_matcher.collect_for_block(
block["bbox"],
- overlap_ratio_getter=self.__formula_number_overlap_ratio,
+ overlap_ratio_getter=formula_number_max_overlap_ratio,
)
else:
block_spans = span_matcher.collect_for_block(block["bbox"])
@@ -295,14 +292,6 @@ class MagicModel:
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 = []
layout_dets = self.__page_model_info["layout_dets"]
diff --git a/mineru/backend/utils/formula_number.py b/mineru/backend/utils/formula_number.py
new file mode 100644
index 00000000..2245c3a1
--- /dev/null
+++ b/mineru/backend/utils/formula_number.py
@@ -0,0 +1,154 @@
+# Copyright (c) Opendatalab. All rights reserved.
+from collections.abc import Callable, Iterable, Sequence
+from typing import Any
+
+from mineru.utils.boxbase import (
+ calculate_overlap_area_2_minbox_area_ratio,
+ calculate_overlap_area_in_bbox1_area_ratio,
+)
+from mineru.utils.char_utils import full_to_half
+from mineru.utils.enum_class import BlockType, ContentType
+
+Block = dict[str, Any]
+
+
+def formula_number_max_overlap_ratio(span: Block, block_bbox: Sequence[float]) -> float:
+ """取公式编号span与block的两种重叠比例最大值,兼容block窄于span的情况。"""
+ 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 extract_formula_number_text(block: Block) -> str:
+ """从公式编号块中提取文本,优先使用VLM直接返回的content。"""
+ content = block.get("content")
+ if isinstance(content, str) and content.strip():
+ return content.strip()
+
+ text_parts = []
+ for line in block.get("lines", []):
+ for span in line.get("spans", []):
+ if span.get("type") == ContentType.TEXT:
+ text_parts.append(span.get("content", ""))
+ return "".join(text_parts).strip()
+
+
+def normalize_formula_tag_content(tag_content: str) -> str:
+ """归一化公式编号文本,去掉外层括号并转换全角字符。"""
+ tag_content = full_to_half(tag_content.strip())
+ if tag_content.startswith("("):
+ tag_content = tag_content[1:].strip()
+ if tag_content.endswith(")"):
+ tag_content = tag_content[:-1].strip()
+ return tag_content
+
+
+def build_tagged_formula_content(
+ formula_content: str,
+ formula_number_block: Block,
+) -> str:
+ """将公式正文和公式编号合成带LaTeX tag的公式内容。"""
+ tag_content = normalize_formula_tag_content(
+ extract_formula_number_text(formula_number_block)
+ )
+ return f"{formula_content}\\tag{{{tag_content}}}"
+
+
+def get_interline_equation_span(block: Block) -> Block | None:
+ """查找行间公式块中的公式span。"""
+ for line in block.get("lines", []):
+ for span in line.get("spans", []):
+ if span.get("type") == ContentType.INTERLINE_EQUATION:
+ return span
+ return None
+
+
+def append_formula_number_tag(
+ equation_block: Block,
+ formula_number_block: Block,
+) -> None:
+ """将公式编号写入pipeline middle-json行间公式span。"""
+ equation_span = get_interline_equation_span(equation_block)
+ if equation_span is not None:
+ equation_span["content"] = build_tagged_formula_content(
+ equation_span.get("content", ""),
+ formula_number_block,
+ )
+
+
+def _optimize_formula_number_sequence(
+ blocks: Sequence[Block],
+ is_formula_number: Callable[[Block], bool],
+ is_equation: Callable[[Block], bool],
+ append_tag: Callable[[Block, Block], None],
+ downgrade_block: Callable[[Block], None],
+) -> list[Block]:
+ """按统一相邻规则优化公式编号序列,调用方负责适配不同block结构。"""
+ optimized_blocks = []
+ for index, block in enumerate(blocks):
+ if not is_formula_number(block):
+ optimized_blocks.append(block)
+ continue
+
+ prev_block = blocks[index - 1] if index > 0 else None
+ if prev_block and is_equation(prev_block):
+ append_tag(prev_block, block)
+ continue
+
+ next_block = blocks[index + 1] if index + 1 < len(blocks) else None
+ next_next_block = blocks[index + 2] if index + 2 < len(blocks) else None
+ if (
+ next_block
+ and is_equation(next_block)
+ and (next_next_block is None or not is_formula_number(next_next_block))
+ ):
+ append_tag(next_block, block)
+ continue
+
+ downgrade_block(block)
+ optimized_blocks.append(block)
+
+ return optimized_blocks
+
+
+def _downgrade_formula_number_to_text(block: Block) -> None:
+ """将未匹配公式编号降级为普通文本块。"""
+ block["type"] = BlockType.TEXT
+
+
+def _append_flash_formula_number_tag(
+ equation_block: Block,
+ formula_number_block: Block,
+) -> None:
+ """将公式编号写入Hybrid flash的VLM行间公式内容。"""
+ equation_block["content"] = build_tagged_formula_content(
+ equation_block.get("content", ""),
+ formula_number_block,
+ )
+
+
+def optimize_formula_number_blocks(pdf_info_list: Iterable[Block]) -> None:
+ """按pipeline规则合并公式编号块,未匹配的编号降级为普通文本。"""
+ for page_info in pdf_info_list:
+ blocks = page_info.get("preproc_blocks", [])
+ page_info["preproc_blocks"] = _optimize_formula_number_sequence(
+ blocks,
+ lambda block: block.get("type") == BlockType.FORMULA_NUMBER,
+ lambda block: block.get("type") == BlockType.INTERLINE_EQUATION,
+ append_formula_number_tag,
+ _downgrade_formula_number_to_text,
+ )
+
+
+def optimize_flash_formula_number_blocks(model_list: Iterable[list[Block]]) -> None:
+ """按统一相邻规则处理Hybrid flash的VLM公式编号块。"""
+ for page_model_list in model_list:
+ optimized_blocks = _optimize_formula_number_sequence(
+ page_model_list or [],
+ lambda block: block.get("type") == BlockType.FORMULA_NUMBER,
+ lambda block: block.get("type") == BlockType.EQUATION,
+ _append_flash_formula_number_tag,
+ _downgrade_formula_number_to_text,
+ )
+ page_model_list[:] = optimized_blocks
diff --git a/pyproject.toml b/pyproject.toml
index ed6fd3e0..79cc4dd7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -50,7 +50,7 @@ dependencies = [
"openai>=1.70.0,<3",
"beautifulsoup4>=4.13.5,<5",
"magika>=0.6.2,<1.1.0",
- "mineru-vl-utils>=1.0.2,<2",
+ "mineru-vl-utils>=1.0.4,<2",
"python-docx>=1.2.0,<2",
'pypptx-with-oxml>=1.0.3,<2',
"mammoth>=1.11.0,<2",