Skip to content

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

feat: update span handling to use content instead of html for various types and introduce VlmContentBlockDraft for layout processing

myhloli7c916ec4c052
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index 8220bea6..f1ce452c 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -11,6 +11,7 @@ from PIL import Image
from ...types import EMPTY_BBOX, NOT_EXTRACT_TYPES, BBox, Block, BlockType, ContentType, IntBBox, Line, Span
from ...utils.guess_suffix_or_lang import guess_language_by_text
from ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
+from ..utils.content_block_draft import VlmContentBlockDraft
from ..utils.span_block_fix import fix_text_block
from ..utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
from ..utils.visual_magic_model_utils import (
@@ -46,11 +47,10 @@ OCR_DET_LINE_BLOCK_TYPES = {
}
-def _copy_raw_text_block_metadata(raw_block_type: str, block_info: dict[str, Any], block: Block) -> None:
- if raw_block_type != BlockType.TEXT:
+def _copy_raw_text_block_metadata(draft: VlmContentBlockDraft, block: Block) -> None:
+ if draft.raw_type != BlockType.TEXT:
return
- if "merge_prev" in block_info:
- block.merge_prev = block_info["merge_prev"]
+ block.merge_prev = draft.merge_prev
class MagicModel:
@@ -115,12 +115,13 @@ class MagicModel:
# 解析每个块
for index, block_info in enumerate(page_blocks):
try:
- block_bbox = self.cal_real_bbox(block_info["bbox"])
- block_type = block_info["type"]
- raw_block_type = block_type
- block_content = block_info.get("content")
- block_angle = block_info.get("angle", 0)
- block_sub_type = block_info.get("sub_type") if raw_block_type in ["image", "chart"] else None
+ draft = VlmContentBlockDraft.from_content_block(block_info, width, height)
+ block_bbox = draft.bbox
+ block_type = draft.raw_type
+ raw_block_type = draft.raw_type
+ block_content = draft.content
+ block_angle = draft.angle
+ block_sub_type = draft.sub_type if raw_block_type in ["image", "chart"] else None
except Exception as e:
# 如果解析失败,可能是因为格式不正确,跳过这个块
logger.warning(f"Invalid block format: {block_info}, error: {e}")
@@ -184,7 +185,7 @@ class MagicModel:
if span_type in [ContentType.IMAGE, ContentType.TABLE, ContentType.CHART]:
span = Span(type=span_type, bbox=block_bbox)
if span_type == ContentType.TABLE and block_content is not None:
- span.html = block_content
+ span.content = block_content
elif raw_block_type in ["image", "chart"] and block_content is not None:
span.content = block_content
elif span_type == ContentType.INTERLINE_EQUATION:
@@ -280,19 +281,19 @@ class MagicModel:
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
- if raw_block_type == "table" and "cell_merge" in block_info:
- block._cell_merge = block_info["cell_merge"]
+ if raw_block_type == "table" and draft.cell_merge:
+ block._cell_merge = draft.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:
block._ocr_det_lines = ocr_det_lines
- _copy_raw_text_block_metadata(raw_block_type, block_info, block)
+ _copy_raw_text_block_metadata(draft, block)
else:
block_spans = span_matcher.collect_for_block(block_bbox)
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)
+ _copy_raw_text_block_metadata(draft, block)
blocks.append(block)
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index 1450e086..9b7bc98f 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -41,7 +41,7 @@ class MagicModel:
span = Span(type=ContentType.IMAGE, bbox=EMPTY_BBOX, image_base64=block_content)
elif block_type in ["table"]:
block_type = BlockType.TABLE_BODY
- span = Span(type=ContentType.TABLE, bbox=EMPTY_BBOX, html=clean_table_html(block_content))
+ span = Span(type=ContentType.TABLE, bbox=EMPTY_BBOX, content=clean_table_html(block_content))
elif block_type in ["chart"]:
block_type = BlockType.CHART_BODY
span = Span(type=ContentType.CHART, bbox=EMPTY_BBOX, content=block_content)
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
index 96376358..f77cfd04 100644
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ b/mineru/backend/pipeline/pipeline_magic_model.py
@@ -1,6 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
+from dataclasses import dataclass
from copy import deepcopy
from typing import TYPE_CHECKING, Any
@@ -26,6 +27,54 @@ if TYPE_CHECKING:
from PIL.Image import Image as PILImage
+@dataclass(slots=True)
+class PipelineLayoutBlockDraft:
+ """Pipeline layout_det 的内部适配层,隔离模型输出字段和 middle_json block。"""
+
+ raw_label: str
+ type: str
+ bbox: BBox
+ index: int
+ score: float | None = None
+ text: str | list[str] = ""
+ html: str = ""
+ latex: str = ""
+ angle: int | None = None
+
+ @classmethod
+ def from_layout_det(
+ cls,
+ layout_det: dict[str, Any],
+ *,
+ block_type: str,
+ bbox: BBox,
+ index: int,
+ score: float | None,
+ ) -> PipelineLayoutBlockDraft:
+ """显式抽取 layout_det 中允许进入转换阶段的字段,避免 raw dict 直灌 Block。"""
+ return cls(
+ raw_label=str(layout_det.get("label", "")),
+ type=block_type,
+ bbox=bbox,
+ index=index,
+ score=score,
+ text=layout_det.get("text", ""),
+ html=layout_det.get("html", ""),
+ latex=layout_det.get("latex", ""),
+ angle=layout_det.get("angle"),
+ )
+
+ def to_middle_block(self) -> Block:
+ """生成 middle_json block 包装,raw 载荷保留在 draft 中按 index 查取。"""
+ return Block(
+ index=self.index,
+ type=self.type,
+ bbox=self.bbox,
+ score=self.score,
+ angle=self.angle,
+ )
+
+
class MagicModel:
PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES: dict[str, str] = {
"abstract": BlockType.ABSTRACT,
@@ -103,6 +152,7 @@ class MagicModel:
self.image_groups: list[dict[str, Any]] = []
self.table_groups: list[dict[str, Any]] = []
self.chart_groups: list[dict[str, Any]] = []
+ self.__layout_draft_by_index: dict[int, PipelineLayoutBlockDraft] = {}
self.__layout_det_by_index: dict[int, dict[str, Any]] = {}
self.__scale = scale
self.__fix_axis() # bbox坐标修正,删除高度或者宽度小于等于0的spans
@@ -126,13 +176,16 @@ class MagicModel:
block_type = self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES[layout_det["label"]]
block_index = layout_det["index"]
block_score = layout_det["score"]
- block = self.__copy_block_fields(
+ draft = PipelineLayoutBlockDraft.from_layout_det(
layout_det,
- type=block_type,
+ block_type=block_type,
bbox=block_bbox,
index=block_index,
score=block_score,
)
+ block = draft.to_middle_block()
+ self.__layout_draft_by_index[block_index] = draft
+ self.__layout_det_by_index[block_index] = layout_det
if self.__is_seal_layout_block(layout_det):
block.sub_type = "seal"
self.page_blocks.append(block)
@@ -172,12 +225,6 @@ class MagicModel:
block._fix_spans = []
return block
- @staticmethod
- def __copy_block_fields(block: dict[str, Any], **overrides: Any) -> Block:
- kwargs = {k: v for k, v in block.items() if k not in {"cls_id", "label"}}
- kwargs = {**kwargs, **overrides}
- return Block(**kwargs)
-
@staticmethod
def __is_inline_formula_block(layout_det: dict[str, Any]) -> bool:
return layout_det.get("label") == "inline_formula" or layout_det.get("cls_id") == 15
@@ -200,6 +247,13 @@ class MagicModel:
return content.strip()
return ""
+ def __draft_payload(self, block: Block, field_name: str, default: Any = "") -> Any:
+ """从 pipeline draft 读取转换载荷,避免把 raw 字段挂到 middle_json Block。"""
+ draft = self.__layout_draft_by_index.get(block.index)
+ if draft is None:
+ return default
+ return getattr(draft, field_name, default)
+
def __build_return_blocks(self) -> None:
self.preproc_blocks: list[Block] = []
self.discarded_blocks: list[Block] = []
@@ -265,16 +319,13 @@ class MagicModel:
]:
span = Span(type=span_type, bbox=block.bbox)
if span_type == ContentType.IMAGE and block.sub_type == "seal":
- seal_text = self.__normalize_seal_text(block.text)
+ seal_text = self.__normalize_seal_text(self.__draft_payload(block, "text", ""))
if seal_text:
span.content = seal_text
- block.text = ""
if span_type == ContentType.TABLE:
- span.html = block.html
- block.html = ""
+ span.content = self.__draft_payload(block, "html", "")
if span_type == ContentType.INTERLINE_EQUATION:
- span.content = block.latex
- block.latex = ""
+ span.content = self.__draft_payload(block, "latex", "")
# 构造line对象
spans = [span]
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
index 9a6c7f0c..00227a84 100644
--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
@@ -24,8 +24,9 @@ def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> N
def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list[Block]:
- merged_blocks = []
- ref_group = []
+ """将连续 ref_text 包装为临时父 Block,供 content_list 输出为参考文献列表。"""
+ merged_blocks: list[Block] = []
+ ref_group: list[Block] = []
def flush_ref_group() -> None:
nonlocal ref_group
@@ -35,11 +36,12 @@ def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list
merged_blocks.append(ref_group[0])
else:
merged_blocks.append(
- {
- "type": BlockType.REF_TEXT,
- "blocks": list(ref_group),
- "bbox": ref_group[0].get("bbox"),
- }
+ Block(
+ index=ref_group[0].index,
+ type=BlockType.REF_TEXT,
+ bbox=ref_group[0].bbox,
+ blocks=list(ref_group),
+ )
)
ref_group = []
@@ -104,7 +106,7 @@ def _get_body_data(para_block: Block) -> tuple[str, str]:
for span in line.spans:
span_type = span.type
if span_type == ContentType.TABLE:
- return span.image_path, span.html
+ return span.image_path, span.content
if span_type == ContentType.CHART:
return span.image_path, span.content
if span_type == ContentType.IMAGE:
diff --git a/mineru/backend/utils/content_block_draft.py b/mineru/backend/utils/content_block_draft.py
new file mode 100644
index 00000000..41836778
--- /dev/null
+++ b/mineru/backend/utils/content_block_draft.py
@@ -0,0 +1,45 @@
+# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Mapping
+
+from ...types import BBox
+
+
+@dataclass(slots=True)
+class VlmContentBlockDraft:
+ """VLM raw content block 的内部适配层,不作为 middle_json block 输出。"""
+
+ raw_type: str
+ bbox: BBox
+ angle: int | None = None
+ content: str | None = None
+ merge_prev: bool = False
+ sub_type: str | None = None
+ cell_merge: list[int] = field(default_factory=list)
+
+ @classmethod
+ def from_content_block(cls, content_block: Mapping[str, Any], width: int, height: int) -> VlmContentBlockDraft:
+ """将 mineru_vl_utils 的相对坐标 content block 转为页面绝对坐标 draft。"""
+ x1, y1, x2, y2 = content_block["bbox"]
+ x_1, y_1, x_2, y_2 = (
+ int(x1 * width),
+ int(y1 * height),
+ int(x2 * width),
+ int(y2 * height),
+ )
+ if x_2 < x_1:
+ x_1, x_2 = x_2, x_1
+ if y_2 < y_1:
+ y_1, y_2 = y_2, y_1
+
+ return cls(
+ raw_type=str(content_block["type"]),
+ bbox=(x_1, y_1, x_2, y_2),
+ angle=content_block.get("angle", 0),
+ content=content_block.get("content", ""),
+ merge_prev=bool(content_block.get("merge_prev", False)),
+ sub_type=content_block.get("sub_type"),
+ cell_merge=list(content_block.get("cell_merge") or []),
+ )
diff --git a/mineru/backend/utils/html_image_utils.py b/mineru/backend/utils/html_image_utils.py
index 3006f859..91a4fd2f 100644
--- a/mineru/backend/utils/html_image_utils.py
+++ b/mineru/backend/utils/html_image_utils.py
@@ -143,8 +143,8 @@ def replace_inline_table_images(
for span in line.spans:
if span.type != table_span_type:
continue
- span.html = _replace_inline_base64_img_src(
- span.html,
+ span.content = _replace_inline_base64_img_src(
+ span.content,
image_writer,
page_index,
)
diff --git a/mineru/backend/utils/table_merge.py b/mineru/backend/utils/table_merge.py
index 7b59b980..7f030efc 100644
--- a/mineru/backend/utils/table_merge.py
+++ b/mineru/backend/utils/table_merge.py
@@ -314,7 +314,7 @@ def _build_table_state(table_block: Block, max_header_rows: int = MAX_HEADER_ROW
if body_span is None:
return None
- html = body_span.html
+ html = body_span.content
if not html:
return None
@@ -356,7 +356,7 @@ def _get_or_create_table_state(
def _serialize_table_state_html(state: TableMergeState) -> None:
- state.body_span.html = str(state.soup)
+ state.body_span.content = str(state.soup)
state.dirty = False
@@ -687,9 +687,9 @@ def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeS
current_table_block = current_state.owner_block
previous_table_block = previous_state.owner_block
- if "blocks" not in previous_table_block or "blocks" not in current_table_block:
+ if not isinstance(previous_table_block, Block) or not isinstance(current_table_block, Block):
raise ValueError(
- "can_merge_tables() requires owner_block with 'blocks' key. "
+ "can_merge_tables() requires owner_block to be a Block instance. "
"For HTML-only states from build_table_state_from_html(), use can_merge_by_structure() instead."
)
diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.py
index 8521bbbd..0ec4ed63 100644
--- a/mineru/backend/vlm/vlm_magic_model.py
+++ b/mineru/backend/vlm/vlm_magic_model.py
@@ -4,10 +4,11 @@ from __future__ import annotations
import re
from loguru import logger
-from mineru_vl_utils.structs import ContentBlock, ExtractResult
+from mineru_vl_utils.structs import ExtractResult
from ...types import Block, BlockType, ContentType, Line, Span
from ...utils.guess_suffix_or_lang import guess_language_by_text
+from ..utils.content_block_draft import VlmContentBlockDraft
from ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
from ..utils.visual_magic_model_utils import (
GENERIC_CHILD_TYPES,
@@ -22,11 +23,10 @@ from ..utils.visual_magic_model_utils import (
)
-def _copy_raw_text_block_metadata(raw_block_type: str, block_info: ContentBlock, block: Block) -> None:
- if raw_block_type != BlockType.TEXT:
+def _copy_raw_text_block_metadata(draft: VlmContentBlockDraft, block: Block) -> None:
+ if draft.raw_type != BlockType.TEXT:
return
- if "merge_prev" in block_info:
- block.merge_prev = block_info["merge_prev"]
+ block.merge_prev = draft.merge_prev
class MagicModel:
@@ -34,25 +34,14 @@ class MagicModel:
blocks: list[Block] = []
# 解析每个块
for index, content_block in enumerate(page_blocks):
- block_bbox = content_block["bbox"]
try:
- x1, y1, x2, y2 = block_bbox
- x_1, y_1, x_2, y_2 = (
- int(x1 * width),
- int(y1 * height),
- int(x2 * width),
- int(y2 * height),
- )
- if x_2 < x_1:
- x_1, x_2 = x_2, x_1
- if y_2 < y_1:
- y_1, y_2 = y_2, y_1
- block_bbox = (x_1, y_1, x_2, y_2)
- block_type = content_block["type"]
- raw_block_type = block_type
- block_content = content_block.get("content", "")
- block_angle = content_block.get("angle", 0)
- block_sub_type = content_block.get("sub_type") if raw_block_type in ["image", "chart"] else None
+ draft = VlmContentBlockDraft.from_content_block(content_block, width, height)
+ block_bbox = draft.bbox
+ block_type = draft.raw_type
+ raw_block_type = draft.raw_type
+ block_content = draft.content
+ block_angle = draft.angle
+ block_sub_type = draft.sub_type if raw_block_type in ["image", "chart"] else None
except Exception as e:
# 如果解析失败,可能是因为格式不正确,跳过这个块
logger.warning(f"Invalid block format: {content_block}, error: {e}")
@@ -113,7 +102,7 @@ class MagicModel:
if span_type in [ContentType.IMAGE, ContentType.TABLE, ContentType.CHART]:
span = Span(type=span_type, bbox=block_bbox)
if span_type == ContentType.TABLE:
- span.html = block_content
+ span.content = block_content or ""
elif raw_block_type in ["image", "chart"] and block_content is not None:
span.content = block_content
elif span_type == ContentType.INTERLINE_EQUATION:
@@ -212,9 +201,9 @@ class MagicModel:
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"]
- _copy_raw_text_block_metadata(raw_block_type, content_block, block)
+ if raw_block_type == "table" and draft.cell_merge:
+ block._cell_merge = draft.cell_merge
+ _copy_raw_text_block_metadata(draft, block)
blocks.append(block)
diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
index 7e212dc7..aee86dd7 100644
--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py
+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
@@ -267,7 +267,7 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
for span in line.spans:
span_type = span.type
if span_type == ContentType.TABLE:
- return span.image_path, span.html
+ return span.image_path, span.content
elif span_type == ContentType.CHART:
return span.image_path, span.content
elif span_type == ContentType.IMAGE:
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index 827e47e5..663de991 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -52,7 +52,7 @@ class ParseResult:
pages.append(page)
return ParseResult(pages=pages)
- def to_dict(self, *, skip_defaults: bool = False) -> dict[str, Any]:
+ def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
return {
"schema_version": MIDDLE_JSON_SCHEMA_VERSION,
"pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.pages],
@@ -158,8 +158,8 @@ class ParseResult:
result[span.image_path or f"{hash_fn(span.image_base64)}.{m.group(1)}"] = base64.b64decode(m.group(2))
except Exception:
pass
- if span.html:
- for m in _INLINE_IMAGE_DATA_URI_RE.finditer(span.html):
+ if span.content:
+ for m in _INLINE_IMAGE_DATA_URI_RE.finditer(span.content):
try:
result[f"{hash_fn(m.group(0))}.{m.group(1)}"] = base64.b64decode(m.group(2))
except Exception:
diff --git a/mineru/parser/html.py b/mineru/parser/html.py
index 1dd6be66..cea3ed43 100644
--- a/mineru/parser/html.py
+++ b/mineru/parser/html.py
@@ -6,7 +6,7 @@ from pathlib import Path
from bs4 import BeautifulSoup, Tag
from .base import DocumentParser, ParseResult
-from ..types import Block, Line, PageInfo, Span
+from ..types import EMPTY_BBOX, Block, Line, PageInfo, Span
class HtmlParser(DocumentParser):
@@ -26,6 +26,7 @@ class HtmlParser(DocumentParser):
body = soup.body or soup
blocks: list[Block] = []
_walk_elements(body, blocks)
+ _assign_block_indexes(blocks)
return ParseResult(
pages=[PageInfo(page_idx=0, para_blocks=blocks)],
@@ -46,15 +47,27 @@ def _extract_text(element: Tag) -> str:
return element.get_text(separator=" ", strip=True)
+def _assign_block_indexes(blocks: list[Block]) -> None:
+ """递归补齐 HTML 解析产生的局部顺序号,保证 middle_json block 契约稳定。"""
+ for index, block in enumerate(blocks):
+ block.index = index
+ _assign_block_indexes(block.blocks)
+
+
+def _line_with_spans(spans: list[Span]) -> Line:
+ """HTML 没有页面坐标,统一使用 EMPTY_BBOX 表示未知行框。"""
+ return Line(bbox=EMPTY_BBOX, spans=spans)
+
+
def _build_span(element: Tag) -> Span:
content = _extract_text(element)
img = element.find("img")
if img is not None:
src: str = img.get("src", "") or ""
if src.startswith("data:image"):
- return Span(type="image", image_base64=src, content=content)
- return Span(type="image", image_path=src, content=content)
- return Span(type="text", content=content)
+ return Span(type="image", bbox=EMPTY_BBOX, image_base64=src, content=content)
+ return Span(type="image", bbox=EMPTY_BBOX, image_path=src, content=content)
+ return Span(type="text", bbox=EMPTY_BBOX, content=content)
def _walk_elements(parent: Tag, blocks: list[Block]) -> None: # type: ignore[type-arg]
@@ -63,8 +76,10 @@ def _walk_elements(parent: Tag, blocks: list[Block]) -> None: # type: ignore[ty
text = str(child).strip()
if text:
blocks.append(Block(
+ index=0,
type="text",
- lines=[Line(spans=[Span(type="text", content=text)])],
+ bbox=EMPTY_BBOX,
+ lines=[_line_with_spans([Span(type="text", bbox=EMPTY_BBOX, content=text)])],
))
continue
@@ -95,25 +110,31 @@ def _walk_elements(parent: Tag, blocks: list[Block]) -> None: # type: ignore[ty
def _build_heading(element: Tag) -> Block:
level = _heading_level(element.name)
return Block(
+ index=0,
type="title",
+ bbox=EMPTY_BBOX,
level=level,
- lines=[Line(spans=[_build_span(element)])],
+ lines=[_line_with_spans([_build_span(element)])],
)
def _build_text_block(element: Tag) -> Block:
# Collapse nested inline children into a single span.
return Block(
+ index=0,
type="text",
- lines=[Line(spans=[_build_span(element)])],
+ bbox=EMPTY_BBOX,
+ lines=[_line_with_spans([_build_span(element)])],
)
def _build_image_block(element: Tag) -> Block:
span = _build_span(element)
return Block(
+ index=0,
type="image",
- lines=[Line(spans=[span])],
+ bbox=EMPTY_BBOX,
+ lines=[_line_with_spans([span])],
)
@@ -123,18 +144,21 @@ def _build_list(element: Tag) -> Block:
nested_blocks: list[Block] = []
_walk_elements(li, nested_blocks)
items.append(Block(
+ index=0,
type="list_item",
- lines=[Line(spans=[Span(type="text", content=_extract_text(li))])],
+ bbox=EMPTY_BBOX,
+ lines=[_line_with_spans([Span(type="text", bbox=EMPTY_BBOX, content=_extract_text(li))])],
blocks=nested_blocks,
))
- return Block(type="list", blocks=items)
+ return Block(index=0, type="list", bbox=EMPTY_BBOX, blocks=items)
def _build_table(element: Tag) -> Block:
return Block(
+ index=0,
type="table",
- html=str(element),
- lines=[Line(spans=[Span(type="table", html=str(element))])],
+ bbox=EMPTY_BBOX,
+ lines=[_line_with_spans([Span(type="table", bbox=EMPTY_BBOX, content=str(element))])],
)
@@ -142,6 +166,8 @@ def _build_code(element: Tag) -> Block:
code = element.find("code")
content = _extract_text(code) if code else _extract_text(element)
return Block(
+ index=0,
type="code",
- lines=[Line(spans=[Span(type="code", content=content)])],
+ bbox=EMPTY_BBOX,
+ lines=[_line_with_spans([Span(type="code", bbox=EMPTY_BBOX, content=content)])],
)
diff --git a/mineru/render/content_list.py b/mineru/render/content_list.py
index 2bd0ac1d..dc5245a8 100644
--- a/mineru/render/content_list.py
+++ b/mineru/render/content_list.py
@@ -142,7 +142,7 @@ def _body_data(para_block: Block, img_bucket_path: str) -> tuple[str, str]:
if span.type == ContentType.IMAGE:
image_path, content = span.image_path, _normalize_visual_content(span.content)
elif span.type == ContentType.TABLE:
- image_path, content = span.image_path, _format_embedded_html(span.html, img_bucket_path)
+ image_path, content = span.image_path, _format_embedded_html(span.content, img_bucket_path)
elif span.type == ContentType.CHART:
image_path, content = span.image_path, span.content
elif span.type == ContentType.INTERLINE_EQUATION:
diff --git a/mineru/render/merge_visual.py b/mineru/render/merge_visual.py
index fc0f5753..c973dbef 100644
--- a/mineru/render/merge_visual.py
+++ b/mineru/render/merge_visual.py
@@ -199,8 +199,8 @@ def _render_visual_block_segments(block: Block, para_block: Block, img_bucket_pa
for span in line.spans:
if span.type != ContentType.TABLE:
continue
- if span.html: # (VLM) also checks table_enable
- table_segments.append((_format_embedded_html(span.html, img_bucket_path), "html_block"))
+ if span.content: # (VLM) also checks table_enable
+ table_segments.append((_format_embedded_html(span.content, img_bucket_path), "html_block"))
elif span.image_path:
if media_path := _build_media_path(img_bucket_path, span.image_path):
table_segments.append((f"![]({media_path})", "markdown_line"))
diff --git a/mineru/render/office/output.py b/mineru/render/office/output.py
index 4074f51c..414c35e6 100644
--- a/mineru/render/office/output.py
+++ b/mineru/render/office/output.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import re
from collections.abc import Generator
-from dataclasses import asdict
from typing import Any
from ...types import Block, BlockType, ContentType, ContentTypeV2, Line, Span
@@ -396,7 +395,7 @@ def blocks_to_markdown(
if no_rich_content:
continue
for span in _iter_body_spans(para_block, BlockType.TABLE_BODY, ContentType.TABLE):
- para_text += f"\n{_format_embedded_html(span.html, img_bucket_path)}\n"
+ para_text += f"\n{_format_embedded_html(span.content, img_bucket_path)}\n"
for caption_text in _collect_caption_texts(para_block, BlockType.TABLE_CAPTION):
para_text += " \n" + caption_text
elif para_type == BlockType.CHART:
@@ -472,8 +471,8 @@ def make_blocks_to_content_list(para_block: Block, img_bucket_path: str, page_id
BlockType.TABLE_BODY,
ContentType.TABLE,
):
- if span.html:
- para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.html, img_bucket_path)
+ if span.content:
+ para_content[BlockType.TABLE_BODY] = _format_embedded_html(span.content, img_bucket_path)
para_content[BlockType.TABLE_CAPTION].extend(_collect_caption_texts(para_block, BlockType.TABLE_CAPTION))
elif para_type == BlockType.CHART:
para_content = {
@@ -645,7 +644,7 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
for span in line.spans:
span_type = span.type
if span_type == ContentType.TABLE:
- return span.image_path, span.html
+ return span.image_path, span.content
elif span_type == ContentType.CHART:
return span.image_path, span.content
elif span_type == ContentType.IMAGE:
@@ -690,6 +689,20 @@ def _span_has_content_for_v2(span: Span, visible_styles: set[str]) -> bool:
return False
+def _render_span_for_v2(span: Span) -> dict[str, Any]:
+ """显式渲染 Office v2 span,避免 dataclass 内部字段泄漏到结构化输出。"""
+ rendered_span = span.to_dict()
+ if rendered_span["type"] == ContentType.INLINE_EQUATION:
+ rendered_span["type"] = ContentTypeV2.SPAN_EQUATION_INLINE
+ if span._url:
+ rendered_span["url"] = span._url
+ if span._style:
+ rendered_span["style"] = list(span._style)
+ if span._children:
+ rendered_span["children"] = [_render_span_for_v2(child) for child in span._children]
+ return rendered_span
+
+
def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
"""将 Office 段落转换为 content_list_v2 spans,避免原地修改 middle_json。"""
_visible_styles = {"underline", "strikethrough"}
@@ -707,8 +720,5 @@ def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
for line in para_block.lines:
for span in line.spans:
if _span_has_content_for_v2(span, _visible_styles):
- rendered_span = asdict(span)
- if rendered_span["type"] == ContentType.INLINE_EQUATION:
- rendered_span["type"] = ContentTypeV2.SPAN_EQUATION_INLINE
- para_content.append(rendered_span)
+ para_content.append(_render_span_for_v2(span))
return para_content
diff --git a/mineru/schema/middle_json/__init__.py b/mineru/schema/middle_json/__init__.py
index 86c25642..f1cd76a0 100644
--- a/mineru/schema/middle_json/__init__.py
+++ b/mineru/schema/middle_json/__init__.py
@@ -305,31 +305,31 @@ def _validate_span_content(span: Span, path: str, issues: list[ValidationIssue])
message="text span should provide content.",
)
)
- elif span.type in IMAGE_SPAN_TYPES and not (span.image_path or span.image_base64 or span.html):
+ elif span.type in IMAGE_SPAN_TYPES and not (span.image_path or span.image_base64):
issues.append(
ValidationIssue(
severity="warning",
code="span_image_missing",
path=path,
- message="image span should provide image_path, image_base64, or html.",
+ message="image span should provide image_path or image_base64.",
)
)
- elif span.type in TABLE_SPAN_TYPES and not (span.html or span.content):
+ elif span.type in TABLE_SPAN_TYPES and not span.content:
issues.append(
ValidationIssue(
severity="warning",
code="span_table_missing",
path=path,
- message="table span should provide html or content.",
+ message="table span should provide content.",
)
)
- elif span.type in EQUATION_SPAN_TYPES and not (span.content or span.latex):
+ elif span.type in EQUATION_SPAN_TYPES and not span.content:
issues.append(
ValidationIssue(
severity="warning",
code="span_equation_missing",
path=path,
- message="equation span should provide content or latex.",
+ message="equation span should provide content.",
)
)
diff --git a/mineru/types.py b/mineru/types.py
index bf0c8ec3..d0665b02 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -1,7 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
-from dataclasses import MISSING, Field, dataclass, field, fields
+from dataclasses import MISSING, Field, InitVar, dataclass, field, fields
from typing import Any, Iterator, Literal, TypeAlias, TypeVar, get_type_hints
T = TypeVar("T", bound="_DocElement")
@@ -333,6 +333,11 @@ def _is_default_value(f: Field, value: Any) -> bool:
return False
+def _initvar_default(value: Any, default: Any) -> Any:
+ """修正 InitVar 与同名 property 共存时产生的 property 默认值。"""
+ return default if isinstance(value, property) else value
+
+
EMPTY_BBOX: BBox = (0.0, 0.0, 0.0, 0.0)
@@ -349,7 +354,7 @@ def _list_arg(tp: Any) -> Any | None:
class _DocElement:
"""Base class for document-model nodes (Span, Line, Block, PageInfo)."""
- def to_dict(self, *, skip_defaults: bool = False) -> dict[str, Any]:
+ def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
"""Serialize to dict, excluding private fields (prefixed with ``_``).
When *skip_defaults* is True, fields whose value equals their
@@ -398,12 +403,12 @@ class Span(_DocElement):
bbox: BBox
content: str = ""
score: float = 0.0
- image_path: str = ""
- image_base64: str = ""
- html: str = ""
- latex: str = ""
+ image_path: InitVar[str] = ""
+ image_base64: InitVar[str] = ""
# Internal
+ _image_path: str = ""
+ _image_base64: str = ""
_cross_page: bool = False
_np_img: Any = None
@@ -413,6 +418,48 @@ class Span(_DocElement):
_extra: dict = field(default_factory=dict)
+ def __post_init__(self, image_path: str, image_base64: str) -> None:
+ """接收图片类 span 的路径字段,但仅在有值时序列化到 middle_json。"""
+ self._image_path = _initvar_default(image_path, "")
+ self._image_base64 = _initvar_default(image_base64, "")
+
+ @property
+ def image_path(self) -> str:
+ """图片类/表格类/公式类 span 的外部图片产物路径。"""
+ return self._image_path
+
+ @image_path.setter
+ def image_path(self, value: str) -> None:
+ self._image_path = value
+
+ @property
+ def image_base64(self) -> str:
+ """Office 等输入中的内联图片,仅在写出图片前临时保留。"""
+ return self._image_base64
+
+ @image_base64.setter
+ def image_base64(self, value: str) -> None:
+ self._image_base64 = value
+
+ def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
+ """按 span 类型输出实际载荷字段,避免文本 span 带空图片字段。"""
+ result = super().to_dict(skip_defaults=skip_defaults)
+ for name, value in (
+ ("image_path", self.image_path),
+ ("image_base64", self.image_base64),
+ ):
+ if value:
+ result[name] = value
+ return result
+
+ @classmethod
+ def from_dict(cls, d: dict) -> Span:
+ """读取当前 middle_json 中图片类 span 的非 content 载荷字段。"""
+ span = _DocElement.from_dict.__func__(cls, d)
+ span.image_path = d.get("image_path", "")
+ span.image_base64 = d.get("image_base64", "")
+ return span
+
@dataclass
class Line(_DocElement):
@@ -441,25 +488,29 @@ class Block(_DocElement):
blocks: list[Block] = field(default_factory=list)
# Optional
- angle: int | None = None
- score: float | None = None
level: int | None = None
sub_type: str = ""
guess_lang: str = ""
- merge_prev: bool = False
section_number: str = ""
- html: str = ""
- text: str = ""
- latex: str = ""
# Office
anchor: str = ""
start: int | None = None
ilevel: int | None = None
- is_numbered_style: bool = False
+
+ # Init-only draft fields. These are accepted for backend conversion
+ # compatibility, but are not middle_json block fields and never serialize.
+ angle: InitVar[int | None] = None
+ score: InitVar[float | None] = None
+ merge_prev: InitVar[bool] = False
+ is_numbered_style: InitVar[bool] = False
# Internal
_cross_page: bool = False
+ _angle: int | None = None
+ _layout_score: float | None = None
+ _merge_prev: bool = False
+ _is_numbered_style: bool = False
_lines_deleted: bool = False
_ocr_det_lines: list[Line] = field(default_factory=list)
_line_avg_height: int = 0
@@ -471,6 +522,55 @@ class Block(_DocElement):
_bbox_fs: BBox | None = None
_sub_images: list[Block] = field(default_factory=list)
+ def __post_init__(
+ self,
+ angle: int | None,
+ score: float | None,
+ merge_prev: bool,
+ is_numbered_style: bool,
+ ) -> None:
+ """接收转换阶段临时字段,但只存入内部属性,避免污染 middle_json 输出。"""
+ self._angle = _initvar_default(angle, None)
+ self._layout_score = _initvar_default(score, None)
+ self._merge_prev = _initvar_default(merge_prev, False)
+ self._is_numbered_style = _initvar_default(is_numbered_style, False)
+
+ @property
+ def angle(self) -> int | None:
+ """转换阶段读取的原始旋转角,默认不作为 middle_json block 字段输出。"""
+ return self._angle
+
+ @angle.setter
+ def angle(self, value: int | None) -> None:
+ self._angle = value
+
+ @property
+ def score(self) -> float | None:
+ """layout 置信度只作为内部调试/传递信息保存,不进入 public block。"""
+ return self._layout_score
+
+ @score.setter
+ def score(self, value: float | None) -> None:
+ self._layout_score = value
+
+ @property
+ def merge_prev(self) -> bool:
+ """raw content block 的合并提示,仅供段落合并阶段消费。"""
+ return self._merge_prev
+
+ @merge_prev.setter
+ def merge_prev(self, value: bool) -> None:
+ self._merge_prev = value
+
+ @property
+ def is_numbered_style(self) -> bool:
+ """Office 标题编号中间状态,生成 section_number 后不输出。"""
+ return self._is_numbered_style
+
+ @is_numbered_style.setter
+ def is_numbered_style(self, value: bool) -> None:
+ self._is_numbered_style = value
+
def all_spans(self) -> Iterator[Span]:
"""Depth-first yield every span in this block tree."""
for line in self.lines: