Skip to content

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

refactor: convert dict[str, Any] to dataclass types in backend modules

jinzhenj5feecda32b64
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 705e2f91..efcea6a1 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -321,7 +321,7 @@ def _build_formula_mask_inputs(images_layout_res: list[dict[str, Any]]) -> list[
return page_formula_masks
-def _normalize_page_size(page_image: Any) -> list[int]:
+def _normalize_page_size(page_image: Any) -> tuple[int, int]:
"""从PIL或numpy图像中读取页面宽高,供归一化bbox还原为像素bbox。"""
if hasattr(page_image, "size"):
return page_image.size
@@ -330,7 +330,7 @@ def _normalize_page_size(page_image: Any) -> list[int]:
return width, height
-def _bbox_to_pixel_bbox(bbox: list[float], page_size: list[int]) -> list[int] | None:
+def _bbox_to_pixel_bbox(bbox: list[float], page_size: list[int]) -> list[float] | None:
"""将归一化或像素bbox统一成像素bbox,异常bbox返回None。"""
if bbox is None or len(bbox) != 4:
return None
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index e7b885ad..a9ab7035 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -64,7 +64,7 @@ class MagicModel:
_vlm_ocr_enable: bool,
) -> None:
(
- self.page_blocks,
+ page_blocks,
self.page_inline_formula,
self.page_ocr_res,
) = self._split_page_model_list(copy.deepcopy(page_model_list))
@@ -72,8 +72,8 @@ class MagicModel:
self.width = width
self.height = height
- blocks = []
- self.all_spans = []
+ blocks: list[Block] = []
+ self.all_spans: list[Span] = []
page_text_inline_formula_spans = []
for inline_formula in self.page_inline_formula:
@@ -111,7 +111,7 @@ class MagicModel:
span_matcher = SpanBlockMatcher(page_text_inline_formula_spans)
# 解析每个块
- for index, block_info in enumerate(self.page_blocks):
+ for index, block_info in enumerate(page_blocks):
try:
block_bbox = self.cal_real_bbox(block_info["bbox"])
block_type = block_info["type"]
@@ -273,17 +273,15 @@ class MagicModel:
if block_type == BlockType.CODE_BODY:
if switch_code_to_algorithm and code_block_sub_type == "code":
code_block_sub_type = "algorithm"
- line = Line(spans=spans, bbox=block_bbox)
- line["extra"] = {"type": code_block_sub_type, "guess_lang": guess_lang}
+ line = Line(spans=spans, bbox=block_bbox, _code_type=code_block_sub_type, _code_guess_lang=guess_lang)
else:
line = Line(spans=spans, bbox=block_bbox)
block = Block(index=index, type=block_type, bbox=block_bbox, lines=[line], angle=block_angle)
- block.index = index
if block_sub_type:
block.sub_type = block_sub_type
if raw_block_type == "table" and "cell_merge" in block_info:
- block["cell_merge"] = block_info["cell_merge"]
+ block._cell_merge = block_info["cell_merge"]
if _vlm_ocr_enable and self._supports_ocr_det_lines(block_type):
ocr_det_lines = self._build_ocr_det_lines(span_matcher.collect_for_block(block_bbox))
if ocr_det_lines:
@@ -291,14 +289,8 @@ class MagicModel:
_copy_raw_text_block_metadata(raw_block_type, block_info, block)
else:
block_spans = span_matcher.collect_for_block(block_bbox)
-
- block = {
- "bbox": block_bbox,
- "type": block_type,
- "angle": block_angle,
- "spans": block_spans,
- "index": index,
- }
+ block = Block(index=index, type=block_type, bbox=block_bbox, angle=block_angle)
+ block._fix_spans = block_spans
block = fix_text_block(block)
_copy_raw_text_block_metadata(raw_block_type, block_info, block)
@@ -307,17 +299,17 @@ class MagicModel:
fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)
fallback_leading_table_continuation_captions(blocks, VISUAL_MAIN_TYPES)
- self.image_blocks = []
- self.table_blocks = []
- self.chart_blocks = []
- self.interline_equation_blocks = []
- self.text_blocks = []
- self.title_blocks = []
- self.code_blocks = []
- self.discarded_blocks = []
- self.ref_text_blocks = []
- self.phonetic_blocks = []
- self.list_blocks = []
+ self.image_blocks: list[Block] = []
+ self.table_blocks: list[Block] = []
+ self.chart_blocks: list[Block] = []
+ self.interline_equation_blocks: list[Block] = []
+ self.text_blocks: list[Block] = []
+ self.title_blocks: list[Block] = []
+ self.code_blocks: list[Block] = []
+ self.discarded_blocks: list[Block] = []
+ self.ref_text_blocks: list[Block] = []
+ self.phonetic_blocks: list[Block] = []
+ self.list_blocks: list[Block] = []
for block in blocks:
if block.type in VISUAL_MAIN_TYPES or block.type in GENERIC_CHILD_TYPES:
@@ -326,7 +318,7 @@ class MagicModel:
self.interline_equation_blocks.append(block)
elif block.type == BlockType.TEXT:
self.text_blocks.append(block)
- elif block["type"] in [
+ elif block.type in [
BlockType.TITLE,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
@@ -364,10 +356,11 @@ class MagicModel:
if block.type == BlockType.CODE_BODY:
if block.lines:
line = block.lines[0]
- code_block.sub_type = line["extra"]["type"]
+ code_block.sub_type = line._code_type or ""
+ line._code_type = None
if code_block.sub_type == "code":
- code_block.guess_lang = line["extra"]["guess_lang"]
- del line["extra"]
+ code_block.guess_lang = line._code_guess_lang or ""
+ line._code_guess_lang = None
else:
code_block.sub_type = "code"
code_block.guess_lang = "txt"
diff --git a/mineru/backend/office/mkcontent/output_builders.py b/mineru/backend/office/mkcontent/output_builders.py
index a711f720..e63f870c 100644
--- a/mineru/backend/office/mkcontent/output_builders.py
+++ b/mineru/backend/office/mkcontent/output_builders.py
@@ -748,7 +748,7 @@ def union_make(
pdf_info_dict: list[dict[str, Any]],
make_mode: MakeMode,
img_buket_path: str = "",
-) -> list[str]:
+) -> list[str] | None:
output_content = []
for page_info in pdf_info_dict:
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index cf8e6edd..5958d4e0 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -13,10 +13,8 @@ from ..utils.magic_model_utils import tie_up_category_by_index
class MagicModel:
def __init__(self, page_blocks: list[dict[str, Any]]) -> None:
- self.page_blocks = page_blocks
-
blocks: list[Block] = []
- self.all_spans = []
+ self.all_spans: list[Span] = []
# 对caption块进行分类,将其分类为image_caption, table_caption, chart_caption
page_blocks = classify_caption_blocks(page_blocks)
diff --git a/mineru/backend/pipeline/para_split.py b/mineru/backend/pipeline/para_split.py
index f3178dee..6c53cb84 100644
--- a/mineru/backend/pipeline/para_split.py
+++ b/mineru/backend/pipeline/para_split.py
@@ -245,7 +245,7 @@ def __is_list_or_index_block(block: Block) -> str:
return BlockType.TEXT
-def __merge_2_text_blocks(block1: Block, block2: Block) -> Block | None:
+def __merge_2_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
if len(block1.lines) > 0 and len(block2.lines) > 0:
first_line = block1.lines[0]
line_height = first_line.bbox[3] - first_line.bbox[1]
@@ -289,7 +289,7 @@ def __merge_2_text_blocks(block1: Block, block2: Block) -> Block | None:
return block1, block2
-def __merge_2_vertical_text_blocks(block1: Block, block2: Block) -> Block | None:
+def __merge_2_vertical_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
if len(block1.lines) > 0 and len(block2.lines) > 0:
first_line = block1.lines[0]
line_width = first_line.bbox[2] - first_line.bbox[0]
@@ -326,7 +326,7 @@ def __merge_2_vertical_text_blocks(block1: Block, block2: Block) -> Block | None
return block1, block2
-def __merge_2_list_blocks(block1: Block, block2: Block) -> Block | None:
+def __merge_2_list_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
if block1["page_num"] != block2["page_num"]:
for line in block1.lines:
for span in line.spans:
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index 1cf504c6..d0176742 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -138,16 +138,16 @@ class MagicModel:
@staticmethod
def __fix_text_block(block: Block) -> Block:
- if block.type == BlockType.TEXT and is_vertical_text_block_by_spans(block["spans"]):
+ if block.type == BlockType.TEXT and is_vertical_text_block_by_spans(block._fix_spans):
# layout 偶发会把竖排正文识别为横排 text,这里用旧版 span 高宽比规则兜底。
block.type = BlockType.VERTICAL_TEXT
if block.type == BlockType.VERTICAL_TEXT:
# 如果是纵向文本块,则按纵向lines处理
- block_lines = merge_spans_to_vertical_line(block["spans"])
+ block_lines = merge_spans_to_vertical_line(block._fix_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._fix_spans)
sort_block_lines = line_sort_spans_by_left_to_right(block_lines)
if block.type == BlockType.CODE:
@@ -156,11 +156,11 @@ class MagicModel:
code_content = _merge_para_text({"lines": sort_block_lines}, False, "\n")
guess_lang = guess_language_by_text(code_content)
if guess_lang not in ["txt", "unknown"]:
- block["sub_type"] = "code"
- block["guess_lang"] = guess_lang
+ block.sub_type = "code"
+ block.guess_lang = guess_lang
block.lines = sort_block_lines
- del block["spans"]
+ block._fix_spans = []
return block
@staticmethod
@@ -211,9 +211,11 @@ class MagicModel:
if block.type in [BlockType.CODE]:
for sub_block in block.blocks:
if sub_block.type == BlockType.CODE_BODY:
- block["sub_type"] = sub_block.pop("sub_type", "algorithm")
- if block["sub_type"] == "code":
- block["guess_lang"] = sub_block.pop("guess_lang", "txt")
+ block.sub_type = sub_block.sub_type or "algorithm"
+ sub_block.sub_type = ""
+ if block.sub_type == "code":
+ block.guess_lang = sub_block.guess_lang or "txt"
+ sub_block.guess_lang = ""
self.preproc_blocks.append(block)
@@ -256,16 +258,16 @@ class MagicModel:
ContentType.INTERLINE_EQUATION,
]:
span = Span(type=span_type, bbox=block.bbox)
- if span_type == ContentType.IMAGE and block.get("sub_type") == "seal":
+ if span_type == ContentType.IMAGE and block.sub_type == "seal":
seal_text = self.__normalize_seal_text(block.get("text"))
if seal_text:
- span["content"] = seal_text
+ span.content = seal_text
block.pop("text", None)
if span_type == ContentType.TABLE:
- span["html"] = block.get("html", "")
- block.pop("html", None)
+ span.html = block.html
+ block.html = ""
if span_type == ContentType.INTERLINE_EQUATION:
- span["content"] = block.get("latex", "")
+ span.content = block.get("latex", "")
block.pop("latex", None)
self.all_image_spans.append(span)
@@ -283,7 +285,7 @@ class MagicModel:
else:
block_spans = span_matcher.collect_for_block(block.bbox)
- block["spans"] = block_spans
+ block._fix_spans = block_spans
block = self.__fix_text_block(block)
self.page_text_inline_formula_spans = span_matcher.remaining_spans()
@@ -291,8 +293,8 @@ class MagicModel:
def __formula_number_overlap_ratio(span: Span, block_bbox: list[float]) -> float:
"""公式编号框较窄时,沿用最小框重叠比例提高回填召回。"""
return max(
- calculate_overlap_area_in_bbox1_area_ratio(span["bbox"], block_bbox),
- calculate_overlap_area_2_minbox_area_ratio(span["bbox"], block_bbox),
+ 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) -> None:
@@ -348,7 +350,7 @@ class MagicModel:
if not self.page_blocks:
return
- ordered_blocks = sorted(self.page_blocks, key=lambda x: x["index"])
+ ordered_blocks = sorted(self.page_blocks, key=lambda x: x.index)
original_type_by_index = {block.index: block.type for block in ordered_blocks}
position_by_index = {block.index: pos for pos, block in enumerate(ordered_blocks)}
main_blocks = [block for block in ordered_blocks if original_type_by_index[block.index] in self.VISUAL_MAIN_TYPES]
@@ -405,17 +407,17 @@ class MagicModel:
mapping = self.VISUAL_TYPE_MAPPING[original_block_type]
body_block = self.__make_child_block(block, mapping["body"])
if original_block_type in [BlockType.IMAGE, BlockType.CHART]:
- body_block.pop("sub_type", None)
+ body_block.sub_type = ""
captions = sorted(
[self.__make_child_block(caption, mapping["caption"]) for caption in grouped_children[block.index]["captions"]],
- key=lambda x: x["index"],
+ key=lambda x: x.index,
)
footnotes = sorted(
[
self.__make_child_block(footnote, mapping["footnote"])
for footnote in grouped_children[block.index]["footnotes"]
],
- key=lambda x: x["index"],
+ key=lambda x: x.index,
)
self.__sync_layout_det_type(block.index, mapping["body"])
@@ -433,17 +435,16 @@ class MagicModel:
self.chart_groups.append(group_info)
two_layer_block = Block(
+ index=block.index,
type=original_block_type,
bbox=block.bbox,
blocks=[body_block, *captions, *footnotes],
+ score=block.score,
)
- two_layer_block.index = block.index
- if block.score is not None:
- two_layer_block.score = block.score
if original_block_type in [BlockType.IMAGE, BlockType.CHART] and block.sub_type:
two_layer_block.sub_type = block.sub_type
# 对blocks按index排序
- two_layer_block["blocks"].sort(key=lambda x: x["index"])
+ two_layer_block.blocks.sort(key=lambda x: x.index)
rebuilt_page_blocks.append(two_layer_block)
self.page_blocks = rebuilt_page_blocks
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
index 76a13e0b..b355d727 100644
--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
@@ -91,7 +91,7 @@ def get_blocks_in_index_order(blocks: list[Block]) -> list[Block]:
]
-def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> None:
+def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> Block | dict[str, Any]:
# pipeline_magic_model 会把 code_body 的 sub_type/guess_lang 提升到父 code block。
# markdown 渲染 code_body 时需要把这两个字段临时透传回来,但不能修改原始输入。
if block.type != BlockType.CODE_BODY:
@@ -459,7 +459,7 @@ def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list
return merged_blocks
-def _build_bbox(para_bbox: list[float], page_size: list[int]) -> tuple[int, int, int, int]:
+def _build_bbox(para_bbox: list[float], page_size: list[int]) -> list[int] | None:
if not para_bbox or not page_size:
return None
@@ -732,7 +732,7 @@ def make_blocks_to_content_list(
return para_content
-def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_size: list[int]) -> list[dict[str, Any]]:
+def make_blocks_to_content_list_v2(para_block: Block, img_buket_path: str, page_size: list[int]) -> list[dict[str, Any]] | None:
para_type = para_block.type
para_content = None
diff --git a/mineru/backend/utils/span_block_fix.py b/mineru/backend/utils/span_block_fix.py
index 88235b56..54cc8ec8 100644
--- a/mineru/backend/utils/span_block_fix.py
+++ b/mineru/backend/utils/span_block_fix.py
@@ -1,6 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-from typing import Any
-
+from ...types import Block, Line, Span
from ...utils.enum_class import ContentType
from ...utils.ocr_utils import _is_overlaps_x_exceeds_threshold, _is_overlaps_y_exceeds_threshold
@@ -8,12 +7,12 @@ VERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2
VERTICAL_SPAN_IN_BLOCK_THRESHOLD = 0.8
-def is_vertical_text_block_by_spans(spans: list[dict[str, Any]]) -> bool:
+def is_vertical_text_block_by_spans(spans: list[Span]) -> bool:
"""根据块内文本 span 的高宽比判断文本块是否更像竖排文本。"""
valid_span_count = 0
vertical_span_count = 0
for span in spans:
- bbox = span.get("bbox")
+ bbox = span.bbox
if not bbox or len(bbox) < 4:
continue
@@ -32,39 +31,39 @@ def is_vertical_text_block_by_spans(spans: list[dict[str, Any]]) -> bool:
return vertical_span_count / valid_span_count > VERTICAL_SPAN_IN_BLOCK_THRESHOLD
-def fix_text_block(block: dict[str, Any]) -> dict[str, Any]:
+def fix_text_block(block: Block) -> Block:
# 文本block中的公式span都应该转换成行内type
- for span in block["spans"]:
- if span["type"] == ContentType.INTERLINE_EQUATION:
- span["type"] = ContentType.INLINE_EQUATION
+ for span in block._extra["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._extra["spans"]):
# 如果是纵向文本块,则按纵向lines处理
- block_lines = merge_spans_to_vertical_line(block["spans"])
+ block_lines = merge_spans_to_vertical_line(block._extra["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._extra["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._extra["spans"]
return block
-def merge_spans_to_line(spans: list[dict[str, Any]], threshold: float = 0.6) -> list[list[dict[str, Any]]]:
+def merge_spans_to_line(spans: list[Span], threshold: float = 0.6) -> list[list[Span]]:
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)
@@ -72,7 +71,7 @@ def merge_spans_to_line(spans: list[dict[str, Any]], threshold: float = 0.6) ->
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:
# 否则,开始新行
@@ -86,28 +85,28 @@ def merge_spans_to_line(spans: list[dict[str, Any]], threshold: float = 0.6) ->
return lines
-def merge_spans_to_vertical_line(spans: list[dict[str, Any]], threshold: float = 0.6) -> list[list[dict[str, Any]]]:
+def merge_spans_to_vertical_line(spans: list[Span], threshold: float = 0.6) -> list[list[Span]]:
"""将纵向文本的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)
@@ -121,45 +120,34 @@ def merge_spans_to_vertical_line(spans: list[dict[str, Any]], threshold: float =
# 将每一个line中的span从左到右排序
-def line_sort_spans_by_left_to_right(lines: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:
+def line_sort_spans_by_left_to_right(lines: list[list[Span]]) -> list[Line]:
line_objects = []
for line in lines:
# 按照x0坐标排序
- 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
- ]
- line_objects.append(
- {
- "bbox": line_bbox,
- "spans": line,
- }
+ 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
)
+ line_objects.append(Line(bbox=line_bbox, spans=line))
return line_objects
-def vertical_line_sort_spans_from_top_to_bottom(vertical_lines: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:
+def vertical_line_sort_spans_from_top_to_bottom(vertical_lines: list[list[Span]]) -> list[Line]:
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
- ]
-
- # 组装结果
- line_objects.append(
- {
- "bbox": line_bbox,
- "spans": line,
- }
+ 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
)
+
+ line_objects.append(Line(bbox=line_bbox, spans=line))
return line_objects
diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.py
index b74489a1..a35603d2 100644
--- a/mineru/backend/utils/span_pre_proc.py
+++ b/mineru/backend/utils/span_pre_proc.py
@@ -172,7 +172,7 @@ class SpanBlockMatcher:
self.grid = self._build_grid(self.spans)
@staticmethod
- def _get_grid_size(spans: list[Span]) -> int:
+ def _get_grid_size(spans: list[Span]) -> float:
"""根据 span 高度估算索引网格大小,避免过细或过粗。"""
heights = [
span.bbox[3] - span.bbox[1] for span in spans if span.bbox and span.bbox[3] > span.bbox[1]
diff --git a/mineru/backend/utils/table_merge.py b/mineru/backend/utils/table_merge.py
index 701421ce..346e6767 100644
--- a/mineru/backend/utils/table_merge.py
+++ b/mineru/backend/utils/table_merge.py
@@ -69,6 +69,18 @@ class TableMergeState:
dirty: bool = False
+def _colspan(cell: Any) -> int:
+ val = cell.get("colspan", "1")
+ assert isinstance(val, str)
+ return int(val)
+
+
+def _rowspan(cell: Any) -> int:
+ val = cell.get("rowspan", "1")
+ assert isinstance(val, str)
+ return int(val)
+
+
def _normalize_cell_text(cell: Tag) -> str:
return "".join(full_to_half(cell.get_text()).split())
@@ -106,8 +118,8 @@ def _scan_rows(rows: list[Tag], initial_occupied: dict[int, set[int]] | None = N
while col_idx in occupied_row:
col_idx += 1
- colspan = int(cell.get("colspan", 1))
- rowspan = int(cell.get("rowspan", 1))
+ colspan = _colspan(cell)
+ rowspan = _rowspan(cell)
actual_cols += colspan
for row_offset in range(rowspan):
@@ -150,8 +162,8 @@ def _build_row_signature(row: Tag, effective_cols: int) -> RowSignature:
cells = row.find_all(["td", "th"])
return RowSignature(
effective_cols=effective_cols,
- colspans=tuple(int(cell.get("colspan", 1)) for cell in cells),
- rowspans=tuple(int(cell.get("rowspan", 1)) for cell in cells),
+ colspans=tuple(_colspan(cell) for cell in cells),
+ rowspans=tuple(_rowspan(cell) for cell in cells),
normalized_texts=tuple(_normalize_cell_text(cell) for cell in cells),
display_texts=tuple(_display_cell_text(cell) for cell in cells),
)
@@ -381,7 +393,7 @@ def calculate_row_columns(row: Tag) -> int:
column_count = 0
for cell in cells:
- colspan = int(cell.get("colspan", 1))
+ colspan = _colspan(cell)
column_count += colspan
return column_count
@@ -425,8 +437,8 @@ def _scan_row_visual_sources(
for cell_idx, cell in enumerate(cells):
while col_idx in occupied_row:
col_idx += 1
- colspan = int(cell.get("colspan", 1))
- rowspan = int(cell.get("rowspan", 1))
+ colspan = _colspan(cell)
+ rowspan = _rowspan(cell)
source_marker = (r_idx, cell_idx)
for ro in range(rowspan):
target_idx = r_idx + ro
@@ -467,7 +479,7 @@ def build_visual_col_mapping(
while col_idx in target_occupied and target_occupied[col_idx][0] < target_row_index:
col_idx += 1
mapping.append(col_idx)
- colspan = int(cell.get("colspan", 1))
+ colspan = _colspan(cell)
col_idx += colspan
return mapping
@@ -641,7 +653,7 @@ def _expand_header_count_by_rowspan(rows: list[Tag], header_count: int) -> int:
while row_idx < expanded_header_count:
row = rows[row_idx]
for cell in row.find_all(["td", "th"]):
- rowspan = int(cell.get("rowspan", 1))
+ rowspan = _rowspan(cell)
if rowspan > 1:
expanded_header_count = max(expanded_header_count, row_idx + rowspan)
expanded_header_count = min(expanded_header_count, len(rows))
@@ -744,8 +756,8 @@ def check_row_columns_match(row1: Tag, row2: Tag) -> bool:
if len(cells1) != len(cells2):
return False
for cell1, cell2 in zip(cells1, cells2):
- colspan1 = int(cell1.get("colspan", 1))
- colspan2 = int(cell2.get("colspan", 1))
+ colspan1 = _colspan(cell1)
+ colspan2 = _colspan(cell2)
if colspan1 != colspan2:
return False
return True
@@ -785,7 +797,7 @@ def adjust_table_rows_colspan(
cols_diff = target_cols - current_row_effective_cols
if cols_diff > 0:
last_cell = cells[-1]
- current_last_span = int(last_cell.get("colspan", 1))
+ current_last_span = _colspan(last_cell)
last_cell["colspan"] = str(current_last_span + cols_diff)
@@ -828,7 +840,7 @@ def _carry_rowspan_structure_to_next_row(rows: list[Tag], row_idx: int) -> None:
carried_cells = []
for cell, start_vcol in zip(current_cells, current_vcol_map):
- rowspan = int(cell.get("rowspan", 1))
+ rowspan = _rowspan(cell)
if rowspan <= 1 or _cell_has_semantic_content(cell):
continue
@@ -865,11 +877,11 @@ def _clip_overlapped_blank_rowspan_cells(
cells = row.find_all(["td", "th"])
visual_col_map = build_visual_col_mapping(rows, row_idx)
for cell, start_vcol in zip(cells, visual_col_map):
- rowspan = int(cell.get("rowspan", 1))
+ rowspan = _rowspan(cell)
if rowspan <= 1 or _cell_has_semantic_content(cell):
continue
- colspan = int(cell.get("colspan", 1))
+ colspan = _colspan(cell)
occupied_cols = set(range(start_vcol, start_vcol + colspan))
if not occupied_cols:
continue
@@ -928,7 +940,7 @@ def _apply_cell_merge(
cell_merge 按视觉列索引对齐,通过构建视觉列映射来正确匹配
两个表格中可能因 rowspan 而具有不同 <td> 元素数量的行。
"""
- cell_merge = current_state.owner_block.get("cell_merge")
+ cell_merge = current_state.owner_block._cell_merge
if not cell_merge:
return
diff --git a/mineru/backend/utils/visual_magic_model_utils.py b/mineru/backend/utils/visual_magic_model_utils.py
index d051911d..b53041b7 100644
--- a/mineru/backend/utils/visual_magic_model_utils.py
+++ b/mineru/backend/utils/visual_magic_model_utils.py
@@ -2,8 +2,10 @@
from __future__ import annotations
import re
+from copy import deepcopy
from typing import Any
+from ...types import Block
from ...utils.enum_class import BlockType
from .boxbase import bbox_center_distance, bbox_distance, calculate_overlap_area_in_bbox1_area_ratio
from .table_continuation import is_table_continuation_text
@@ -97,40 +99,33 @@ def clean_content(content: str | None) -> str | None:
return content
-def fallback_inline_caption_fragments(blocks: list[dict[str, Any]], visual_main_types: dict[Any, Any] | set[Any]) -> None:
+def fallback_inline_caption_fragments(blocks: list[Block], visual_main_types: dict[Any, Any] | set[Any]) -> None:
"""将紧贴视觉主体上方的同行 text/footnote 片段兜底为通用 caption。"""
if len(blocks) < 3:
return
main_types = set(visual_main_types)
- ordered_blocks = sorted(blocks, key=lambda x: x["index"])
+ ordered_blocks = sorted(blocks, key=lambda x: x.index or 0)
for pos, block in enumerate(ordered_blocks):
- if block.get("type") not in INLINE_CAPTION_FRAGMENT_TYPES:
+ if block.type not in INLINE_CAPTION_FRAGMENT_TYPES:
continue
previous_block = find_previous_effective_block(ordered_blocks, pos)
next_block = find_next_effective_block(ordered_blocks, pos)
- if not (
- previous_block
- and next_block
- and previous_block.get("type") == BlockType.CAPTION
- and next_block.get("type") in main_types
- ):
+ if not (previous_block and next_block and previous_block.type == BlockType.CAPTION and next_block.type in main_types):
continue
if not is_inline_caption_fragment(previous_block, block, next_block):
continue
- block["type"] = BlockType.CAPTION
+ block.type = BlockType.CAPTION
# fallback 后该块已是视觉 caption 片段,不再参与正文跨块合并。
- block.pop("merge_prev", None)
+ block.merge_prev = False
fallback_stacked_table_caption_fragments(blocks, visual_main_types)
-def fallback_leading_table_continuation_captions(
- blocks: list[dict[str, Any]], visual_main_types: dict[Any, Any] | set[Any]
-) -> None:
+def fallback_leading_table_continuation_captions(blocks: list[Block], visual_main_types: dict[Any, Any] | set[Any]) -> None:
"""将页首紧贴表格的续表文本兜底为通用 caption。
该规则只处理页面有效块开头的 text,避免正文中出现“续表”时被误挂。
@@ -142,7 +137,7 @@ def fallback_leading_table_continuation_captions(
return
effective_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 or 0) if block.type not in VISUAL_RELATION_IGNORED_TYPES
]
if len(effective_blocks) < 2:
return
@@ -160,75 +155,73 @@ def fallback_leading_table_continuation_captions(
return
table_block = effective_blocks[cursor]
- if table_block.get("type") not in table_main_types:
+ if table_block.type not in table_main_types:
return
if not _is_leading_continuation_cluster_near_table(leading_blocks, table_block):
return
for block in leading_blocks:
- block["type"] = BlockType.CAPTION
+ block.type = BlockType.CAPTION
# fallback 后该块已是视觉 caption,不再参与正文跨块合并。
- block.pop("merge_prev", None)
+ block.merge_prev = False
-def _is_leading_continuation_text_block(block: dict[str, Any]) -> bool:
+def _is_leading_continuation_text_block(block: Block) -> bool:
"""判断页首候选块是否是单行续表文本。"""
return (
- block.get("type") in INLINE_CAPTION_FRAGMENT_TYPES
+ block.type in INLINE_CAPTION_FRAGMENT_TYPES
and is_single_line_caption_fragment(block)
and is_table_continuation_text(_block_text_content(block))
)
-def _block_text_content(block: dict[str, Any]) -> str:
+def _block_text_content(block: Block) -> str:
"""提取视觉块中的可见文本,用于续表 marker 判断。"""
- return "".join(span.get("content", "") for line in block.get("lines", []) for span in line.get("spans", []))
+ return "".join(span.content for line in block.lines for span in line.spans)
-def is_transparent_visual_relation_block(block: dict[str, Any]) -> bool:
+def is_transparent_visual_relation_block(block: Block) -> bool:
"""判断视觉关系中可忽略的结构性空块。"""
- if block.get("type") != BlockType.LIST:
+ if block.type != BlockType.LIST:
return False
- if block.get("blocks"):
+ if block.blocks:
return False
return not _block_text_content(block).strip()
-def _is_leading_continuation_cluster_near_table(leading_blocks: list[dict[str, Any]], table_block: dict[str, Any]) -> bool:
+def _is_leading_continuation_cluster_near_table(leading_blocks: list[Block], table_block: Block) -> bool:
"""判断页首续表文本簇是否与后续 table 在几何上相邻。"""
- next_top = table_block["bbox"][1]
+ next_top = table_block.bbox[1]
max_child_height = 1
for block in reversed(leading_blocks):
if not is_horizontally_near_table(block, table_block):
return False
- block_height = max(block["bbox"][3] - block["bbox"][1], 1)
- vertical_gap = next_top - block["bbox"][3]
+ block_height = max(block.bbox[3] - block.bbox[1], 1)
+ vertical_gap = next_top - block.bbox[3]
max_gap = stacked_caption_max_gap(max(max_child_height, block_height))
max_overlap = max(2, block_height * 0.3)
if vertical_gap > max_gap or vertical_gap < -max_overlap:
return False
- next_top = block["bbox"][1]
+ next_top = block.bbox[1]
max_child_height = max(max_child_height, block_height)
return True
-def fallback_stacked_table_caption_fragments(
- blocks: list[dict[str, Any]], visual_main_types: dict[Any, Any] | set[Any]
-) -> None:
+def fallback_stacked_table_caption_fragments(blocks: list[Block], 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:
return
for table_block in blocks:
- if table_block.get("type") not in table_main_types:
+ if table_block.type not in table_main_types:
continue
caption_cluster = find_stacked_table_caption_cluster(table_block, blocks)
@@ -240,10 +233,10 @@ def fallback_stacked_table_caption_fragments(
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):
- block["type"] = BlockType.CAPTION
+ if block.type in INLINE_CAPTION_FRAGMENT_TYPES and is_single_line_caption_fragment(block):
+ block.type = BlockType.CAPTION
# fallback 后该块已是视觉 caption 片段,不再参与正文跨块合并。
- block.pop("merge_prev", None)
+ block.merge_prev = False
def get_table_main_types(visual_main_types: dict[Any, Any] | set[Any]) -> set[Any]:
@@ -255,16 +248,16 @@ def get_table_main_types(visual_main_types: dict[Any, Any] | set[Any]) -> set[An
return main_types & {BlockType.TABLE, BlockType.TABLE_BODY}
-def find_stacked_table_caption_cluster(table_block: dict[str, Any], blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:
+def find_stacked_table_caption_cluster(table_block: Block, blocks: list[Block]) -> list[Block]:
"""按几何位置收集紧贴 table 上方的 caption/text/footnote 标题簇。"""
- table_bbox = table_block["bbox"]
+ table_bbox = table_block.bbox
table_top = table_bbox[1]
above_candidates = [
block
for block in blocks
if block is not table_block
- and block.get("type") in STACKED_TABLE_CAPTION_CLUSTER_TYPES
- and block["bbox"][3] <= table_top
+ and block.type in STACKED_TABLE_CAPTION_CLUSTER_TYPES
+ and block.bbox[3] <= table_top
and is_horizontally_near_table(block, table_block)
]
if not above_candidates:
@@ -275,42 +268,42 @@ def find_stacked_table_caption_cluster(table_block: dict[str, Any], blocks: list
max_child_height = 1
for block in sorted(
above_candidates,
- key=lambda x: (x["bbox"][1], x["index"]),
+ key=lambda x: (x.bbox[1], x.index),
reverse=True,
):
- block_height = max(block["bbox"][3] - block["bbox"][1], 1)
+ block_height = max(block.bbox[3] - block.bbox[1], 1)
max_allowed_gap = stacked_caption_max_gap(max(max_child_height, block_height))
- vertical_gap = next_top - block["bbox"][3]
+ vertical_gap = next_top - block.bbox[3]
if not 0 <= vertical_gap <= max_allowed_gap:
break
caption_cluster.append(block)
- next_top = block["bbox"][1]
+ next_top = block.bbox[1]
max_child_height = max(max_child_height, block_height)
return list(reversed(caption_cluster))
-def find_last_caption_position(caption_cluster: list[dict[str, Any]]) -> int | None:
+def find_last_caption_position(caption_cluster: list[Block]) -> int | None:
"""定位标题簇里的最后一个 caption,避免吸收上一张表的尾注。"""
for pos in range(len(caption_cluster) - 1, -1, -1):
- if caption_cluster[pos].get("type") == BlockType.CAPTION:
+ if caption_cluster[pos].type == BlockType.CAPTION:
return pos
return None
-def is_horizontally_near_table(block: dict[str, Any], table_block: dict[str, Any]) -> bool:
+def is_horizontally_near_table(block: Block, table_block: Block) -> bool:
"""判断标题簇候选块是否横向落在 table 范围附近。"""
- table_bbox = table_block["bbox"]
- block_bbox = block["bbox"]
+ 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)
-def is_single_line_caption_fragment(block: dict[str, Any]) -> bool:
+def is_single_line_caption_fragment(block: Block) -> bool:
"""判断待兜底片段是否是单行块,避免吞掉多行正文。"""
- return len(block.get("lines") or [None]) <= 1
+ return len(block.lines or [None]) <= 1
def stacked_caption_max_gap(block_height: float) -> float:
@@ -318,31 +311,29 @@ def stacked_caption_max_gap(block_height: float) -> float:
return max(12, block_height * 1.5)
-def find_previous_effective_block(ordered_blocks: list[dict[str, Any]], pos: int) -> dict[str, Any] | None:
+def find_previous_effective_block(ordered_blocks: list[Block], pos: int) -> Block | None:
"""向前查找参与视觉关系判断的有效块,跳过页眉页脚等外围块。"""
for index in range(pos - 1, -1, -1):
block = ordered_blocks[index]
- if block.get("type") not in VISUAL_RELATION_IGNORED_TYPES:
+ if block.type not in VISUAL_RELATION_IGNORED_TYPES:
return block
return None
-def find_next_effective_block(ordered_blocks: list[dict[str, Any]], pos: int) -> dict[str, Any] | None:
+def find_next_effective_block(ordered_blocks: list[Block], pos: int) -> Block | None:
"""向后查找参与视觉关系判断的有效块,跳过页眉页脚等外围块。"""
for index in range(pos + 1, len(ordered_blocks)):
block = ordered_blocks[index]
- if block.get("type") not in VISUAL_RELATION_IGNORED_TYPES:
+ if block.type not in VISUAL_RELATION_IGNORED_TYPES:
return block
return None
-def is_inline_caption_fragment(
- previous_caption: dict[str, Any], text_block: dict[str, Any], next_visual: dict[str, Any]
-) -> bool:
+def is_inline_caption_fragment(previous_caption: Block, text_block: Block, next_visual: Block) -> bool:
"""判断当前块是否是前一 caption 的同行补充片段。"""
- caption_bbox = previous_caption["bbox"]
- text_bbox = text_block["bbox"]
- visual_bbox = next_visual["bbox"]
+ caption_bbox = previous_caption.bbox
+ text_bbox = text_block.bbox
+ visual_bbox = next_visual.bbox
caption_height = max(caption_bbox[3] - caption_bbox[1], 1)
text_height = max(text_bbox[3] - text_bbox[1], 1)
@@ -359,21 +350,23 @@ def is_inline_caption_fragment(
return 0 <= vertical_gap_to_visual <= max_allowed_gap
-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"])
+def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]], list[Block]]:
+ ordered_blocks = sorted(blocks, key=lambda x: x.index or 0)
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]
+ 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]
+ 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: dict[int, dict[str, list[Block]]] = {
+ block.index: {"captions": [], "footnotes": []} for block in main_blocks
+ }
unmatched_child_blocks = []
for main_block in main_blocks:
- if main_block["index"] in sub_images_by_index:
- main_block["sub_images"] = sub_images_by_index[main_block["index"]]
+ if main_block.index in sub_images_by_index:
+ main_block._extra["sub_images"] = sub_images_by_index[main_block.index]
for child_block in child_blocks:
parent_block = find_best_visual_parent(
@@ -386,10 +379,10 @@ def regroup_visual_blocks(blocks: list[dict[str, Any]]) -> tuple[dict[Any, list[
unmatched_child_blocks.append(child_block)
continue
- child_kind = child_kind_from_type(child_block["type"])
- grouped_children[parent_block["index"]][f"{child_kind}s"].append(child_block)
+ child_kind = child_kind_from_type(child_block.type)
+ grouped_children[parent_block.index][f"{child_kind}s"].append(child_block)
- grouped_blocks = {
+ grouped_blocks: dict[str, list[Block]] = {
BlockType.IMAGE: [],
BlockType.TABLE: [],
BlockType.CHART: [],
@@ -397,56 +390,56 @@ def regroup_visual_blocks(blocks: list[dict[str, Any]]) -> tuple[dict[Any, list[
}
for main_block in main_blocks:
- visual_type = VISUAL_MAIN_TYPES[main_block["type"]]
+ visual_type = VISUAL_MAIN_TYPES[main_block.type]
mapping = VISUAL_TYPE_MAPPING[visual_type]
- body_block = dict(main_block)
- body_block["type"] = mapping["body"]
+ body_block = deepcopy(main_block)
+ body_block.type = mapping["body"]
body_block.pop("sub_images", None)
- body_block.pop("sub_type", None)
+ body_block.sub_type = ""
captions = []
for caption in sorted(
- grouped_children[main_block["index"]]["captions"],
- key=lambda x: x["index"],
+ grouped_children[main_block.index]["captions"],
+ key=lambda x: x.index or 0,
):
- child_block = dict(caption)
- child_block["type"] = mapping["caption"]
+ child_block = deepcopy(caption)
+ child_block.type = mapping["caption"]
captions.append(child_block)
footnotes = []
for footnote in sorted(
- grouped_children[main_block["index"]]["footnotes"],
- key=lambda x: x["index"],
+ grouped_children[main_block.index]["footnotes"],
+ key=lambda x: x.index or 0,
):
- child_block = dict(footnote)
- child_block["type"] = mapping["footnote"]
+ child_block = deepcopy(footnote)
+ child_block.type = mapping["footnote"]
footnotes.append(child_block)
- two_layer_block = {
- "type": visual_type,
- "bbox": body_block["bbox"],
- "blocks": [body_block, *captions, *footnotes],
- "index": body_block["index"],
- }
- if visual_type in [BlockType.IMAGE, BlockType.CHART] and main_block.get("sub_type"):
- two_layer_block["sub_type"] = main_block["sub_type"]
- if visual_type == BlockType.IMAGE and main_block.get("sub_images"):
- two_layer_block["sub_images"] = main_block["sub_images"]
- if visual_type == BlockType.TABLE and main_block.get("cell_merge"):
- two_layer_block["cell_merge"] = main_block["cell_merge"]
- two_layer_block["blocks"].sort(key=lambda x: x["index"])
+ two_layer_block = Block(
+ index=body_block.index,
+ type=visual_type,
+ bbox=body_block.bbox,
+ blocks=[body_block, *captions, *footnotes],
+ )
+ if visual_type in [BlockType.IMAGE, BlockType.CHART] and main_block.sub_type:
+ two_layer_block.sub_type = main_block.sub_type
+ if visual_type == BlockType.IMAGE and main_block._extra.get("sub_images"):
+ two_layer_block["sub_images"] = main_block._extra["sub_images"]
+ if visual_type == BlockType.TABLE and main_block._cell_merge:
+ two_layer_block._cell_merge = main_block._cell_merge
+ two_layer_block.blocks.sort(key=lambda x: x.index or 0)
grouped_blocks[visual_type].append(two_layer_block)
for blocks_of_type in grouped_blocks.values():
- blocks_of_type.sort(key=lambda x: x["index"])
+ blocks_of_type.sort(key=lambda x: x.index or 0)
return grouped_blocks, unmatched_child_blocks
-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]]
+def absorb_image_block_members(blocks: list[Block]) -> tuple[set[int], dict[int, list[Block]]]:
+ 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:
@@ -454,37 +447,37 @@ def absorb_image_block_members(blocks: list[dict[str, Any]]) -> tuple[set[int],
best_parent_index = None
for image_block in image_block_bodies:
overlap_ratio = calculate_overlap_area_in_bbox1_area_ratio(
- member["bbox"],
- image_block["bbox"],
+ member.bbox,
+ image_block.bbox,
)
if overlap_ratio < 0.9:
continue
candidate_key = (
-overlap_ratio,
- bbox_area(image_block["bbox"]),
- image_block["index"],
+ bbox_area(image_block.bbox),
+ image_block.index,
)
if best_key is None or candidate_key < best_key:
best_key = candidate_key
- best_parent_index = image_block["index"]
+ best_parent_index = image_block.index
if best_parent_index is not None:
- assignments[member["index"]] = best_parent_index
+ assignments[member.index] = best_parent_index
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
- members.sort(key=lambda x: x["index"])
- absorbed_member_indices.update(member["index"] for member in members)
- sub_images_by_index[image_block["index"]] = [
+ members.sort(key=lambda x: x.index or 0)
+ absorbed_member_indices.update(member.index for member in members)
+ sub_images_by_index[image_block.index] = [
{
- "type": child_visual_type(member["type"]),
- "bbox": relative_bbox(member["bbox"], image_block["bbox"]),
+ "type": child_visual_type(member.type),
+ "bbox": relative_bbox(member.bbox, image_block.bbox),
}
for member in members
]
@@ -493,13 +486,13 @@ def absorb_image_block_members(blocks: list[dict[str, Any]]) -> tuple[set[int],
def find_best_visual_parent(
- child_block: dict[str, Any],
- main_blocks: list[dict[str, Any]],
- ordered_blocks: list[dict[str, Any]],
+ child_block: Block,
+ main_blocks: list[Block],
+ ordered_blocks: list[Block],
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:
+) -> Block | None:
"""为通用 caption/footnote 查找最合适的视觉主体。"""
if main_type_to_visual_type is None:
main_type_to_visual_type = VISUAL_MAIN_TYPES
@@ -543,14 +536,12 @@ def find_best_visual_parent(
if len(closest_index_candidates) == 1:
return closest_index_candidates[0]
- edge_distances = [
- (main_block, bbox_distance(child_block["bbox"], main_block["bbox"])) for main_block in closest_index_candidates
- ]
+ edge_distances = [(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:
return min(
edge_distances,
- key=lambda item: (item[1], item[0]["index"]),
+ key=lambda item: (item[1], item[0].index),
)[0]
child_type = block_type(child_block, type_by_index)
@@ -559,31 +550,31 @@ def find_best_visual_parent(
for main_block in closest_index_candidates
):
# 表格 caption 位于两个表之间且距离接近时,优先归属后一个表。
- return max(closest_index_candidates, key=lambda x: x["index"])
+ return max(closest_index_candidates, key=lambda x: x.index or 0)
if child_type == BlockType.FOOTNOTE:
# 视觉脚注位于两个主体之间且距离接近时,优先归属前一个主体。
- return min(closest_index_candidates, key=lambda x: x["index"])
+ return min(closest_index_candidates, key=lambda x: x.index or 0)
return min(
closest_index_candidates,
key=lambda main_block: (
- bbox_center_distance(child_block["bbox"], main_block["bbox"]),
- main_block["index"],
+ bbox_center_distance(child_block.bbox, main_block.bbox),
+ main_block.index,
),
)
def effective_visual_index_diff(
- child_block: dict[str, Any],
- main_block: dict[str, Any],
- ordered_blocks: list[dict[str, Any]],
+ child_block: Block,
+ main_block: Block,
+ ordered_blocks: list[Block],
type_by_index: dict[int, str] | None = None,
) -> int:
"""按有效块序列计算视觉子块与主体距离,吸收的 image 子成员视为零成本。"""
- 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"]]
+ 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)
end_pos = max(child_pos, main_pos)
skipped_child_count = 0
@@ -597,14 +588,14 @@ def effective_visual_index_diff(
def is_visual_neighbor(
- child_block: dict[str, Any],
- main_block: dict[str, Any],
- ordered_blocks: list[dict[str, Any]],
+ child_block: Block,
+ main_block: Block,
+ ordered_blocks: list[Block],
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"]:
+ if child_type == BlockType.FOOTNOTE and child_block.index < main_block.index:
return False
if child_type == BlockType.CAPTION:
@@ -612,8 +603,8 @@ def is_visual_neighbor(
else:
allowed_between_types = set(GENERIC_CHILD_TYPES)
- child_pos = position_by_index[child_block["index"]]
- main_pos = position_by_index[main_block["index"]]
+ child_pos = position_by_index[child_block.index]
+ main_pos = position_by_index[main_block.index]
start_pos = min(child_pos, main_pos) + 1
end_pos = max(child_pos, main_pos)
@@ -628,29 +619,29 @@ def is_visual_neighbor(
return True
-def is_block_outside_visual_gap(between_block: dict[str, Any], child_block: dict[str, Any], main_block: dict[str, Any]) -> bool:
+def is_block_outside_visual_gap(between_block: Block, child_block: Block, main_block: Block) -> bool:
"""判断阅读顺序夹在中间的块是否没有落入视觉父子块的垂直间隔。"""
visual_gap = vertical_gap_between_blocks(child_block, main_block)
if visual_gap is None:
return False
if is_bbox_overlapping_visual_relation_block(
- between_block["bbox"],
- child_block["bbox"],
- main_block["bbox"],
+ between_block.bbox,
+ child_block.bbox,
+ main_block.bbox,
):
return False
- if not is_bbox_intersecting_vertical_gap(between_block["bbox"], visual_gap):
+ if not is_bbox_intersecting_vertical_gap(between_block.bbox, visual_gap):
return True
return False
-def vertical_gap_between_blocks(first_block: dict[str, Any], second_block: dict[str, Any]) -> tuple[float, float] | None:
+def vertical_gap_between_blocks(first_block: Block, second_block: Block) -> tuple[float, float] | None:
"""计算两个块上下分离时的垂直间隔;发生纵向重叠时保持严格阻断。"""
- first_bbox = first_block["bbox"]
- second_bbox = second_block["bbox"]
+ first_bbox = first_block.bbox
+ second_bbox = second_block.bbox
if first_bbox[3] <= second_bbox[1]:
return first_bbox[3], second_bbox[1]
if second_bbox[3] <= first_bbox[1]:
@@ -658,18 +649,20 @@ def vertical_gap_between_blocks(first_block: dict[str, Any], second_block: dict[
return None
-def is_bbox_intersecting_vertical_gap(bbox: list[float], vertical_gap: tuple[float, float]) -> bool:
+def is_bbox_intersecting_vertical_gap(bbox: tuple[float, ...], vertical_gap: tuple[float, float]) -> bool:
"""判断 bbox 是否与视觉父子块之间的垂直间隔相交。"""
gap_top, gap_bottom = vertical_gap
return bbox[1] < gap_bottom and bbox[3] > gap_top
-def is_bbox_overlapping_visual_relation_block(bbox: list[float], child_bbox: list[float], main_bbox: list[float]) -> bool:
+def is_bbox_overlapping_visual_relation_block(
+ bbox: tuple[float, ...], child_bbox: tuple[float, ...], main_bbox: tuple[float, ...]
+) -> bool:
"""判断 bbox 是否覆盖到父子块本身;覆盖时不能当作普通 index 噪声跳过。"""
return are_bboxes_overlapping(bbox, child_bbox) or are_bboxes_overlapping(bbox, main_bbox)
-def are_bboxes_overlapping(first_bbox: list[float], second_bbox: list[float]) -> bool:
+def are_bboxes_overlapping(first_bbox: tuple[float, ...], second_bbox: tuple[float, ...]) -> bool:
"""判断两个 bbox 是否存在二维相交。"""
return not (
first_bbox[2] <= second_bbox[0]
@@ -679,11 +672,11 @@ def are_bboxes_overlapping(first_bbox: list[float], second_bbox: list[float]) ->
)
-def block_type(block: dict[str, Any], type_by_index: dict[int, str] | None = None) -> str:
+def block_type(block: Block, 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"]
+ return type_by_index[block.index]
+ return block.type
def child_kind_from_type(block_type: str) -> str:
@@ -698,11 +691,11 @@ def child_visual_type(block_type: str) -> str:
return BlockType.IMAGE
-def bbox_area(bbox: list[float]) -> float:
+def bbox_area(bbox: tuple[float, ...]) -> float:
return max(0, bbox[2] - bbox[0]) * max(0, bbox[3] - bbox[1])
-def relative_bbox(child_bbox: list[float], parent_bbox: list[float]) -> list[float]:
+def relative_bbox(child_bbox: tuple[float, ...], parent_bbox: tuple[float, ...]) -> list[float]:
parent_x0, parent_y0, parent_x1, parent_y1 = parent_bbox
parent_w = max(parent_x1 - parent_x0, 1)
parent_h = max(parent_y1 - parent_y0, 1)
diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.py
index d47b5e84..49b4143c 100644
--- a/mineru/backend/vlm/model_output_to_middle_json.py
+++ b/mineru/backend/vlm/model_output_to_middle_json.py
@@ -63,26 +63,24 @@ def blocks_to_page_info(
replace_inline_table_images(table_blocks, image_writer, page_index)
- page_blocks = []
- page_blocks.extend(
- [
- *image_blocks,
- *table_blocks,
- *chart_blocks,
- *code_blocks,
- *ref_text_blocks,
- *phonetic_blocks,
- *title_blocks,
- *text_blocks,
- *interline_equation_blocks,
- *list_blocks,
- ]
- )
+ blocks = [
+ *image_blocks,
+ *table_blocks,
+ *chart_blocks,
+ *code_blocks,
+ *ref_text_blocks,
+ *phonetic_blocks,
+ *title_blocks,
+ *text_blocks,
+ *interline_equation_blocks,
+ *list_blocks,
+ ]
+
# 对page_blocks根据index的值进行排序
- page_blocks.sort(key=lambda x: x["index"])
+ blocks.sort(key=lambda x: x.index)
page_info = PageInfo(
- preproc_blocks=page_blocks,
+ preproc_blocks=blocks,
discarded_blocks=discarded_blocks,
page_size=[width, height],
page_idx=page_index,
diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.py
index 33ac888b..ac1e5c2f 100644
--- a/mineru/backend/vlm/vlm_magic_model.py
+++ b/mineru/backend/vlm/vlm_magic_model.py
@@ -32,10 +32,8 @@ def _copy_raw_text_block_metadata(raw_block_type: str, block_info: ContentBlock,
class MagicModel:
def __init__(self, page_blocks: ExtractResult, width: int, height: int) -> None:
- self.page_blocks = page_blocks
-
- blocks = []
- self.all_spans = []
+ blocks: list[Block] = []
+ self.all_spans: list[Span] = []
# 解析每个块
for index, content_block in enumerate(page_blocks):
block_bbox = content_block["bbox"]
@@ -206,16 +204,20 @@ class MagicModel:
if block_type == BlockType.CODE_BODY:
if switch_code_to_algorithm and code_block_sub_type == "code":
code_block_sub_type = "algorithm"
- line = Line(spans=spans, bbox=block_bbox)
- line["extra"] = {"type": code_block_sub_type, "guess_lang": guess_lang}
+ line = Line(spans=spans, bbox=block_bbox, _code_type=code_block_sub_type, _code_guess_lang=guess_lang)
else:
line = Line(spans=spans, bbox=block_bbox)
- block = Block(index=index, type=block_type, bbox=block_bbox, lines=[line], angle=block_angle)
- if block_sub_type:
- block["sub_type"] = block_sub_type
+ block = Block(
+ index=index,
+ type=block_type,
+ bbox=block_bbox,
+ lines=[line],
+ angle=block_angle,
+ sub_type=block_sub_type or "",
+ )
if raw_block_type == "table" and "cell_merge" in content_block:
- block["cell_merge"] = content_block["cell_merge"]
+ block._cell_merge = content_block["cell_merge"]
_copy_raw_text_block_metadata(raw_block_type, content_block, block)
blocks.append(block)
@@ -223,32 +225,32 @@ class MagicModel:
fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)
fallback_leading_table_continuation_captions(blocks, VISUAL_MAIN_TYPES)
- self.image_blocks = []
- self.table_blocks = []
- self.chart_blocks = []
- self.interline_equation_blocks = []
- self.text_blocks = []
- self.title_blocks = []
- self.code_blocks = []
- self.discarded_blocks = []
- self.ref_text_blocks = []
- self.phonetic_blocks = []
- self.list_blocks = []
+ self.image_blocks: list[Block] = []
+ self.table_blocks: list[Block] = []
+ self.chart_blocks: list[Block] = []
+ self.interline_equation_blocks: list[Block] = []
+ self.text_blocks: list[Block] = []
+ self.title_blocks: list[Block] = []
+ self.code_blocks: list[Block] = []
+ self.discarded_blocks: list[Block] = []
+ self.ref_text_blocks: list[Block] = []
+ self.phonetic_blocks: list[Block] = []
+ self.list_blocks: list[Block] = []
for block in blocks:
- if block["type"] in VISUAL_MAIN_TYPES or block["type"] in GENERIC_CHILD_TYPES:
+ if block.type in VISUAL_MAIN_TYPES or block.type in GENERIC_CHILD_TYPES:
continue
- elif block["type"] == BlockType.INTERLINE_EQUATION:
+ elif block.type == BlockType.INTERLINE_EQUATION:
self.interline_equation_blocks.append(block)
- elif block["type"] == BlockType.TEXT:
+ elif block.type == BlockType.TEXT:
self.text_blocks.append(block)
- elif block["type"] == BlockType.TITLE:
+ elif block.type == BlockType.TITLE:
self.title_blocks.append(block)
- elif block["type"] == BlockType.REF_TEXT:
+ elif block.type == BlockType.REF_TEXT:
self.ref_text_blocks.append(block)
- elif block["type"] == BlockType.PHONETIC:
+ elif block.type == BlockType.PHONETIC:
self.phonetic_blocks.append(block)
- elif block["type"] in [
+ elif block.type in [
BlockType.HEADER,
BlockType.FOOTER,
BlockType.PAGE_NUMBER,
@@ -256,7 +258,7 @@ class MagicModel:
BlockType.PAGE_FOOTNOTE,
]:
self.discarded_blocks.append(block)
- elif block["type"] == BlockType.LIST:
+ elif block.type == BlockType.LIST:
self.list_blocks.append(block)
self.list_blocks, self.text_blocks, self.ref_text_blocks = fix_list_blocks(
@@ -272,20 +274,21 @@ class MagicModel:
self.code_blocks = visual_groups[BlockType.CODE]
for code_block in self.code_blocks:
- for block in code_block["blocks"]:
- if block["type"] == BlockType.CODE_BODY:
- if block["lines"]:
- line = block["lines"][0]
- code_block["sub_type"] = line["extra"]["type"]
- if code_block["sub_type"] == "code":
- code_block["guess_lang"] = line["extra"]["guess_lang"]
- del line["extra"]
+ for block in code_block.blocks:
+ if block.type == BlockType.CODE_BODY:
+ if block.lines:
+ line = block.lines[0]
+ code_block.sub_type = line._code_type or ""
+ line._code_type = None
+ if code_block.sub_type == "code":
+ code_block.guess_lang = line._code_guess_lang or ""
+ line._code_guess_lang = None
else:
- code_block["sub_type"] = "code"
- code_block["guess_lang"] = "txt"
+ code_block.sub_type = "code"
+ code_block.guess_lang = "txt"
for block in unmatched_child_blocks:
- block["type"] = BlockType.TEXT
+ block.type = BlockType.TEXT
self.text_blocks.append(block)
def get_list_blocks(self) -> list[Block]:
diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
index c9680be4..3fed5456 100644
--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py
+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
@@ -855,7 +855,7 @@ def union_make(
pdf_info_dict: list,
make_mode: str,
img_buket_path: str = "",
-) -> str | list:
+) -> str | list | None:
formula_enable = get_formula_enable(os.getenv("MINERU_VLM_FORMULA_ENABLE", "True").lower() == "true")
table_enable = get_table_enable(os.getenv("MINERU_VLM_TABLE_ENABLE", "True").lower() == "true")
diff --git a/mineru/types.py b/mineru/types.py
index 5b621152..2b5e7ed7 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -411,6 +411,9 @@ class Line:
_is_list_start: bool = False
_is_list_end: bool = False
+ _code_type: str | None = None
+ _code_guess_lang: str | None = None
+
@classmethod
def from_dict(cls, d: dict) -> Line:
return cls(
@@ -445,6 +448,8 @@ class Block:
_lines_deleted: bool = False
_ocr_det_lines: list[Line] = field(default_factory=list)
_line_avg_height: int = 0
+ _cell_merge: list[int] = field(default_factory=list)
+ _fix_spans: list[Span] = field(default_factory=list)
_extra: dict = field(default_factory=dict)
diff --git a/mineru/utils/ocr_utils.py b/mineru/utils/ocr_utils.py
index a686de44..6aeff52b 100644
--- a/mineru/utils/ocr_utils.py
+++ b/mineru/utils/ocr_utils.py
@@ -45,8 +45,8 @@ def merge_spans_to_line(spans: list[dict[str, Any]], threshold: float = 0.6) ->
def _is_overlaps_y_exceeds_threshold(
- bbox1: list[float],
- bbox2: list[float],
+ bbox1: list[float] | tuple[float, ...],
+ bbox2: list[float] | tuple[float, ...],
overlap_ratio_threshold: float = 0.8,
) -> bool:
"""检查两个bbox在y轴上是否有重叠,并且该重叠区域的高度占两个bbox高度更低的那个超过80%"""
@@ -62,8 +62,8 @@ def _is_overlaps_y_exceeds_threshold(
def _is_overlaps_x_exceeds_threshold(
- bbox1: list[float],
- bbox2: list[float],
+ bbox1: list[float] | tuple[float, ...],
+ bbox2: list[float] | tuple[float, ...],
overlap_ratio_threshold: float = 0.8,
) -> bool:
"""检查两个bbox在x轴上是否有重叠,并且该重叠区域的宽度占两个bbox宽度更低的那个超过指定阈值"""
diff --git a/mineru/utils/pdf_text_tool.py b/mineru/utils/pdf_text_tool.py
index f08bcf37..aec91ef5 100644
--- a/mineru/utils/pdf_text_tool.py
+++ b/mineru/utils/pdf_text_tool.py
@@ -1,6 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
import math
-from typing import Any, List
+from typing import Any
import pypdfium2 as pdfium
from pdftext.pdf.chars import deduplicate_chars, get_chars
@@ -44,7 +44,7 @@ def get_page_chars(
with pdfium_guard():
if textpage is None:
textpage = page.get_textpage()
- page_bbox: List[float] = page.get_bbox()
+ page_bbox = 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]))