Skip to content

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

feat: remove unused files and refactor markdown utilities for improved structure

myhlolibfbfd2c97434
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.py
index 49f97ed1..f1e2e9f1 100644
--- a/mineru/backend/analyze.py
+++ b/mineru/backend/analyze.py
@@ -30,7 +30,7 @@ from mineru.backend.utils.boxbase import (
calculate_overlap_area_2_minbox_area_ratio,
calculate_overlap_area_in_bbox1_area_ratio,
)
-from mineru.backend.utils.char_utils import resolve_text_line_boundary
+from mineru.backend.utils.char_utils import full_to_half_exclude_marks, resolve_text_line_boundary
from mineru.backend.utils.formula_number import optimize_hybrid_formula_number_blocks
from mineru.backend.utils.analyze_draft import _AnalyzeLine, _AnalyzeSpan
from mineru.backend.utils.span_block_fix import group_spans_to_lines
@@ -110,6 +110,21 @@ LINE_METADATA_BLOCK_TYPES = {
RAW_CAPTION,
RAW_FOOTNOTE,
}
+NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES = {
+ BlockType.TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.ASIDE_TEXT,
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.PAGE_FOOTNOTE,
+ BlockType.REF_TEXT,
+ BlockType.LIST,
+ BlockType.INDEX,
+ RAW_CAPTION,
+ RAW_FOOTNOTE,
+}
VLM_VISUAL_ANNOTATION_TYPE_MAP = {
BlockType.TABLE_CAPTION: RAW_CAPTION,
BlockType.IMAGE_CAPTION: RAW_CAPTION,
@@ -2502,6 +2517,36 @@ def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:
return True
+def _normalize_natural_language_content(content: str) -> str:
+ """将自然语言中的全角字母和数字转为半角,同时原样保留行内公式片段。"""
+ normalized_parts: list[str] = []
+ cursor = 0
+ formula_markers = (("\\(", "\\)"), ("<eq>", "</eq>"))
+
+ while cursor < len(content):
+ formula_starts = [
+ (start, opening, closing)
+ for opening, closing in formula_markers
+ if (start := content.find(opening, cursor)) >= 0
+ ]
+ if not formula_starts:
+ normalized_parts.append(full_to_half_exclude_marks(content[cursor:]))
+ break
+
+ formula_start, opening, closing = min(formula_starts, key=lambda item: item[0])
+ normalized_parts.append(full_to_half_exclude_marks(content[cursor:formula_start]))
+ formula_end = content.find(closing, formula_start + len(opening))
+ if formula_end < 0:
+ normalized_parts.append(content[formula_start:])
+ break
+
+ formula_end += len(closing)
+ normalized_parts.append(content[formula_start:formula_end])
+ cursor = formula_end
+
+ return "".join(normalized_parts)
+
+
def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
"""清理 PDF block 元数据、规范公式,并过滤正文或行框无效的文本块。"""
for page_idx, page_model_list in enumerate(model_list):
@@ -2527,6 +2572,8 @@ def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
content = block.get("content")
if not isinstance(content, str):
continue
+ if block.get("type") in NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES:
+ content = _normalize_natural_language_content(content)
block["content"] = _INLINE_FORMULA_PATTERN.sub(
lambda match: f"<eq>{match.group(1)}</eq>",
content,
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index f60c1efd..f64ba567 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -1,9 +1 @@
-from .markdown_table import to_markdown_table
-from .union_make import render_content_list, render_markdown, render_structured_content
-
-__all__ = [
- "to_markdown_table",
- "render_content_list",
- "render_markdown",
- "render_structured_content",
-]
+# Copyright (c) Opendatalab. All rights reserved.
\ No newline at end of file
diff --git a/mineru/render/content_list.py b/mineru/render/content_list.py
deleted file mode 100644
index 50a0a3bd..00000000
--- a/mineru/render/content_list.py
+++ /dev/null
@@ -1,166 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from ..backend.utils.raw_block_types import RAW_PHONETIC
-from ..types import EMPTY_BBOX, BBox, Block, BlockType, ContentItem, ContentType, IntBBox
-from .markdown import _build_media_path, _get_title_level
-from .merge import _merge_para_text, merge_para_text
-from .merge_visual import _format_embedded_html, _inherit_parent_code_render_metadata, _normalize_visual_content
-
-
-def block_to_content_list(
- para_block: Block,
- img_bucket_path: str,
- page_idx: int,
- page_size: tuple[int, int] | None,
-) -> ContentItem | None:
- para_type = para_block.type
- if para_type in [
- BlockType.TEXT,
- RAW_PHONETIC,
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.PAGE_NUMBER,
- BlockType.ASIDE_TEXT,
- BlockType.PAGE_FOOTNOTE,
- ]:
- item = ContentItem(
- type=para_type,
- text=merge_para_text(para_block),
- )
- elif para_type == BlockType.INDEX:
- item = ContentItem(
- type=ContentType.TEXT,
- text=merge_para_text(para_block),
- )
- elif para_type == BlockType.LIST:
- if para_block.blocks:
- # Some LayoutModel use LIST as a container.
- item = ContentItem(type=para_type, sub_type=para_block.sub_type or None)
- for block in para_block.blocks:
- if (item_text := _merge_para_text(block)).strip():
- item.list_items.append(item_text)
- else:
- item = ContentItem(
- type=ContentType.TEXT,
- text=merge_para_text(para_block),
- )
- elif para_type == BlockType.REF_TEXT:
- if para_block.blocks:
- item = ContentItem(type=BlockType.LIST, sub_type=BlockType.REF_TEXT)
- for block in para_block.blocks:
- if (item_text := _merge_para_text(block)).strip():
- item.list_items.append(item_text)
- else:
- item = ContentItem(
- type=para_type,
- text=merge_para_text(para_block),
- )
- elif para_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- title_level = _get_title_level(para_block)
- item = ContentItem(
- type=ContentType.TEXT,
- text=merge_para_text(para_block),
- text_level=title_level if title_level != 0 else None,
- )
- elif para_type == BlockType.EQUATION:
- item = ContentItem(
- type=ContentType.EQUATION,
- img_path=_body_data(para_block, img_bucket_path)[0],
- text=merge_para_text(para_block),
- text_format="latex",
- )
- elif para_type == BlockType.IMAGE:
- item = ContentItem(
- type=ContentType.IMAGE,
- sub_type=para_block.sub_type or None,
- )
- for block in para_block.blocks:
- if block.type == BlockType.IMAGE_BODY:
- item.img_path, item.content = _body_data(block, img_bucket_path)
- if block.type == BlockType.IMAGE_CAPTION:
- item.image_caption.append(merge_para_text(block))
- if block.type == BlockType.IMAGE_FOOTNOTE:
- item.image_footnote.append(merge_para_text(block))
- elif para_type == BlockType.TABLE:
- item = ContentItem(type=ContentType.TABLE)
- for block in para_block.blocks:
- if block.type == BlockType.TABLE_BODY:
- item.img_path, item.table_body = _body_data(block, img_bucket_path)
- if block.type == BlockType.TABLE_CAPTION:
- item.table_caption.append(merge_para_text(block))
- if block.type == BlockType.TABLE_FOOTNOTE:
- item.table_footnote.append(merge_para_text(block))
- elif para_type == BlockType.CHART:
- item = ContentItem(
- type=ContentType.CHART,
- sub_type=para_block.sub_type or None,
- )
- for block in para_block.blocks:
- if block.type == BlockType.CHART_BODY:
- item.img_path, item.content = _body_data(block, img_bucket_path)
- if block.type == BlockType.CHART_CAPTION:
- item.chart_caption.append(merge_para_text(block))
- if block.type == BlockType.CHART_FOOTNOTE:
- item.chart_footnote.append(merge_para_text(block))
- elif para_type == BlockType.CODE:
- item = ContentItem(
- type=BlockType.CODE,
- sub_type=para_block.sub_type or None,
- )
- for block in para_block.blocks:
- if block.type == BlockType.CODE_BODY:
- render_block = _inherit_parent_code_render_metadata(block, para_block)
- item.code_body = merge_para_text(render_block)
- if block.type == BlockType.CODE_CAPTION:
- item.code_caption.append(merge_para_text(block))
- if block.type == BlockType.CODE_FOOTNOTE:
- item.code_footnote.append(merge_para_text(block))
- else:
- return None
-
- item.page_idx = page_idx
- if bbox := _norm1k_bbox(para_block.bbox, page_size):
- item.bbox = bbox
- return item
-
-
-def _body_data(para_block: Block, img_bucket_path: str) -> tuple[str, str]:
- image_path, content = "", ""
- for span in (
- span
- for block in para_block.blocks or [para_block]
- if block.type
- in [
- BlockType.IMAGE_BODY,
- BlockType.TABLE_BODY,
- BlockType.CHART_BODY,
- BlockType.EQUATION,
- ]
- for line in block.lines
- for span in line.spans
- ):
- 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.content, img_bucket_path)
- elif span.type == ContentType.CHART:
- image_path, content = span.image_path, span.content
- elif span.type == ContentType.INTERLINE_EQUATION:
- image_path, content = span.image_path, span.content
- if image_path or content:
- break
- return _build_media_path(img_bucket_path, image_path), content
-
-
-def _norm1k_bbox(para_bbox: BBox, page_size: tuple[int, int] | None) -> IntBBox | None:
- if para_bbox == EMPTY_BBOX or not page_size:
- return None
- page_width, page_height = page_size
- x0, y0, x1, y1 = para_bbox
- return (
- int(x0 * 1000 / page_width),
- int(y0 * 1000 / page_height),
- int(x1 * 1000 / page_width),
- int(y1 * 1000 / page_height),
- )
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
deleted file mode 100644
index 0b3392c1..00000000
--- a/mineru/render/markdown.py
+++ /dev/null
@@ -1,103 +0,0 @@
-from ..backend.utils.raw_block_types import RAW_PHONETIC
-from ..types import Block, BlockType, ContentType
-from .markdown_table import to_markdown_table
-from .merge import merge_para_text
-from .merge_visual import _build_media_path, merge_visual_para_text
-
-
-def blocks_to_markdown(
- para_blocks: list[Block],
- img_bucket_path: str = "",
- table_as_image: bool = False,
- formula_as_image: bool = False,
- no_rich_content: bool = False,
- prefer_markdown_table: bool = False,
-) -> list[str]:
- para_texts: list[str] = []
- for para_block in para_blocks:
- para_text = _block_to_markdown(
- para_block=para_block,
- img_bucket_path=img_bucket_path,
- table_as_image=table_as_image,
- formula_as_image=formula_as_image,
- no_rich_content=no_rich_content,
- prefer_markdown_table=prefer_markdown_table,
- )
- if para_text := (para_text or "").strip():
- para_texts.append(para_text)
- return para_texts
-
-
-def _block_to_markdown(
- para_block: Block,
- img_bucket_path: str = "",
- table_as_image: bool = False,
- formula_as_image: bool = False,
- no_rich_content: bool = False,
- prefer_markdown_table: bool = False,
-) -> str | None:
- para_type = para_block.type
- if para_type == BlockType.TEXT:
- return merge_para_text(para_block)
- if para_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- title_level = _get_title_level(para_block)
- return f"{'#' * title_level} {merge_para_text(para_block)}"
- if para_type == BlockType.INDEX:
- return merge_para_text(para_block)
- if para_type == BlockType.REF_TEXT:
- return merge_para_text(para_block)
- if para_type == BlockType.LIST:
- return merge_para_text(para_block)
- if para_type == RAW_PHONETIC:
- return merge_para_text(para_block)
- if para_type == BlockType.CODE:
- return merge_visual_para_text(para_block)
-
- if para_type == BlockType.EQUATION:
- if not formula_as_image:
- if (para_text := merge_para_text(para_block)).strip():
- return para_text
- return _build_image_link(para_block, ContentType.INTERLINE_EQUATION, img_bucket_path)
-
- if no_rich_content:
- return None
- if para_type == BlockType.IMAGE:
- return merge_visual_para_text(para_block, img_bucket_path)
- if para_type == BlockType.TABLE:
- if not table_as_image:
- if prefer_markdown_table:
- return _render_table_block_as_markdown_table(para_block, img_bucket_path)
- return merge_visual_para_text(para_block, img_bucket_path)
- return _build_image_link(para_block, ContentType.TABLE, img_bucket_path)
- if para_type == BlockType.CHART:
- return merge_visual_para_text(para_block, img_bucket_path)
- return None
-
-
-def _get_title_level(block: Block) -> int:
- title_level = getattr(block, "level", None)
- if title_level is None:
- title_level = 1
- if title_level > 6:
- title_level = 6
- elif title_level < 1:
- title_level = 0
- return title_level
-
-
-def _build_image_link(block: Block, target_span_type: str, img_bucket_path: str) -> str | None:
- for line in block.lines:
- for span in line.spans:
- if span.type != target_span_type or not span.image_path:
- continue
- if media_path := _build_media_path(img_bucket_path, span.image_path):
- return f"![]({media_path})"
- return None
-
-
-def _render_table_block_as_markdown_table(para_block: Block, img_bucket_path: str) -> str:
- for span in para_block.all_spans():
- if span.type != ContentType.TABLE or not span.content:
- continue
- return to_markdown_table(span.content)
- return merge_visual_para_text(para_block, img_bucket_path)
diff --git a/mineru/render/markdown_table.py b/mineru/render/markdown_table.py
deleted file mode 100644
index b35fd456..00000000
--- a/mineru/render/markdown_table.py
+++ /dev/null
@@ -1,292 +0,0 @@
-from __future__ import annotations
-
-import re
-from dataclasses import dataclass
-from typing import TypeVar
-
-from bs4 import BeautifulSoup
-from bs4.element import NavigableString, Tag
-
-_ALLOWED_INLINE_TAGS = {
- "a",
- "b",
- "br",
- "code",
- "em",
- "eq",
- "i",
- "s",
- "span",
- "strong",
- "sub",
- "sup",
- "u",
-}
-
-_COMPLEX_BLOCK_TAGS = {
- "blockquote",
- "div",
- "dl",
- "h1",
- "h2",
- "h3",
- "h4",
- "h5",
- "h6",
- "img",
- "li",
- "ol",
- "p",
- "pre",
- "table",
- "ul",
-}
-
-_MatrixCell = TypeVar("_MatrixCell")
-
-
-@dataclass(frozen=True)
-class _CellPlacement:
- text: str
- rowspan: int
- colspan: int
- is_header: bool
-
-
-def to_markdown_table(
- html: str,
- *,
- max_empty_ratio: float = 0.3,
- max_complex_span_count: int = 5,
-) -> str:
- """Convert a simple HTML table to a Markdown table.
-
- Falls back to the original HTML string when the table structure or cell
- content is too complex to render readably as Markdown.
- """
- raw_html = html.strip()
- if not raw_html:
- return raw_html
-
- soup = BeautifulSoup(raw_html, "html.parser")
- table = soup.find("table")
- if table is None:
- return raw_html
- if _has_nested_table(table):
- return raw_html
- if _has_merged_table_cells(table):
- return raw_html
-
- rows = table.find_all("tr")
- if not rows:
- return raw_html
-
- grid: list[list[str | None]] = []
- header_flags: list[list[bool]] = []
- span_count = 0
- has_rowspan = False
- has_colspan = False
-
- for row_idx, row in enumerate(rows):
- _ensure_row(grid, row_idx)
- _ensure_row(header_flags, row_idx)
-
- col_idx = 0
- cells = row.find_all(("th", "td"), recursive=False)
- for cell in cells:
- while col_idx < len(grid[row_idx]) and grid[row_idx][col_idx] is not None:
- col_idx += 1
-
- placement = _parse_cell(cell)
- if placement is None:
- return raw_html
-
- rowspan = placement.rowspan
- colspan = placement.colspan
- if rowspan > 1:
- has_rowspan = True
- span_count += rowspan - 1
- if colspan > 1:
- has_colspan = True
- span_count += colspan - 1
-
- for offset in range(colspan):
- _ensure_width(grid, row_idx, col_idx + offset + 1, fill_value=None)
- _ensure_width(header_flags, row_idx, col_idx + offset + 1, fill_value=False)
- grid[row_idx][col_idx + offset] = placement.text if offset == 0 else ""
- header_flags[row_idx][col_idx + offset] = placement.is_header
-
- for row_offset in range(1, rowspan):
- next_row_idx = row_idx + row_offset
- _ensure_row(grid, next_row_idx)
- _ensure_row(header_flags, next_row_idx)
- _ensure_width(grid, next_row_idx, col_idx + colspan, fill_value=None)
- _ensure_width(header_flags, next_row_idx, col_idx + colspan, fill_value=False)
- for offset in range(colspan):
- grid[next_row_idx][col_idx + offset] = ""
- header_flags[next_row_idx][col_idx + offset] = False
-
- col_idx += colspan
-
- width = max(len(row) for row in grid)
- normalized_rows: list[list[str]] = []
- normalized_headers: list[list[bool]] = []
- for row, flags in zip(grid, header_flags, strict=False):
- normalized_row = [(cell if cell is not None else "") for cell in row]
- normalized_row.extend([""] * (width - len(normalized_row)))
- normalized_rows.append(normalized_row)
-
- normalized_flag_row = list(flags)
- normalized_flag_row.extend([False] * (width - len(normalized_flag_row)))
- normalized_headers.append(normalized_flag_row)
-
- if not normalized_rows:
- return raw_html
-
- empty_ratio = _empty_ratio(normalized_rows)
- if has_rowspan and has_colspan and (span_count > max_complex_span_count or empty_ratio > max_empty_ratio):
- return raw_html
-
- header_index = _detect_header_row(table, normalized_headers)
- header = normalized_rows[header_index]
- body_rows = normalized_rows[:header_index] + normalized_rows[header_index + 1 :]
-
- markdown_lines = [
- _format_markdown_row(header),
- _format_markdown_row(["---"] * width),
- *[_format_markdown_row(row) for row in body_rows],
- ]
- return "\n".join(markdown_lines)
-
-
-def _has_nested_table(table: Tag) -> bool:
- return table.find("table") is not None
-
-
-def _has_merged_table_cells(table: Tag) -> bool:
- """检测合并单元格,Markdown 表格无法无损表达 rowspan/colspan。"""
- for cell in table.find_all(("th", "td")):
- if cell.has_attr("rowspan") or cell.has_attr("colspan"):
- return True
- return False
-
-
-def _parse_cell(cell: Tag) -> _CellPlacement | None:
- if _contains_complex_content(cell):
- return None
- text = _render_inline_children(cell).strip()
- text = _normalize_cell_text(text)
- return _CellPlacement(
- text=text,
- rowspan=_parse_positive_int(cell.get("rowspan")),
- colspan=_parse_positive_int(cell.get("colspan")),
- is_header=cell.name == "th",
- )
-
-
-def _contains_complex_content(cell: Tag) -> bool:
- for descendant in cell.descendants:
- if not isinstance(descendant, Tag):
- continue
- if descendant is cell:
- continue
- if descendant.name in _COMPLEX_BLOCK_TAGS:
- return True
- if descendant.name not in _ALLOWED_INLINE_TAGS:
- return True
- return False
-
-
-def _render_inline_children(node: Tag) -> str:
- parts: list[str] = []
- for child in node.children:
- if isinstance(child, NavigableString):
- parts.append(_escape_markdown_table_text(str(child)))
- continue
- if not isinstance(child, Tag):
- continue
- if child.name == "br":
- parts.append("<br>")
- elif child.name == "code":
- parts.append(f"`{_escape_markdown_table_text(_normalize_whitespace(child.get_text()))}`")
- elif child.name == "a":
- href = str(child.get("href", "")).strip()
- label = _escape_markdown_table_text(_normalize_whitespace(child.get_text()))
- parts.append(f"[{label}]({href})" if href else label)
- elif child.name in {"b", "strong"}:
- parts.append(f"**{_render_inline_children(child).strip()}**")
- elif child.name in {"em", "i"}:
- parts.append(f"*{_render_inline_children(child).strip()}*")
- elif child.name in {"s"}:
- parts.append(f"~~{_render_inline_children(child).strip()}~~")
- elif child.name == "u":
- parts.append(_render_inline_children(child))
- else:
- parts.append(_render_inline_children(child))
- return "".join(parts)
-
-
-def _normalize_cell_text(text: str) -> str:
- text = re.sub(r"[ \t\r\f\v]+", " ", text)
- text = re.sub(r" *<br> *", "<br>", text)
- return text.strip()
-
-
-def _escape_markdown_table_text(text: str) -> str:
- return text.replace("\\", "\\\\").replace("|", r"\|")
-
-
-def _normalize_whitespace(text: str) -> str:
- return re.sub(r"\s+", " ", text).strip()
-
-
-def _parse_positive_int(value: object) -> int:
- try:
- parsed = int(str(value))
- except (TypeError, ValueError):
- return 1
- return parsed if parsed > 0 else 1
-
-
-def _ensure_row(matrix: list[list[_MatrixCell]], row_idx: int) -> None:
- while len(matrix) <= row_idx:
- matrix.append([])
-
-
-def _ensure_width(
- matrix: list[list[_MatrixCell]],
- row_idx: int,
- width: int,
- *,
- fill_value: _MatrixCell,
-) -> None:
- _ensure_row(matrix, row_idx)
- while len(matrix[row_idx]) < width:
- matrix[row_idx].append(fill_value)
-
-
-def _empty_ratio(rows: list[list[str]]) -> float:
- total = sum(len(row) for row in rows)
- if total == 0:
- return 0.0
- empty = sum(1 for row in rows for cell in row if cell == "")
- return empty / total
-
-
-def _detect_header_row(table: Tag, header_flags: list[list[bool]]) -> int:
- thead = table.find("thead")
- if thead is not None:
- thead_rows = thead.find_all("tr", recursive=False)
- if thead_rows:
- return 0
- for idx, flags in enumerate(header_flags):
- if flags and all(flags):
- return idx
- return 0
-
-
-def _format_markdown_row(row: list[str]) -> str:
- return f"| {' | '.join(row)} |"
-
-
-__all__ = ["to_markdown_table"]
diff --git a/mineru/render/merge.py b/mineru/render/merge.py
deleted file mode 100644
index 0022f510..00000000
--- a/mineru/render/merge.py
+++ /dev/null
@@ -1,221 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-"""Unified paragraph-level text merging for Pipeline and VLM backends.
-
-Produces a single Markdown string from a Block's line/spans, handling
-language detection, CJK / western spacing, hyphen de-duplication, and
-Markdown escaping.
-"""
-
-from __future__ import annotations
-
-from ..backend.utils.char_utils import CJK_LANGS, full_to_half_exclude_marks, resolve_text_line_boundary
-from ..types import Block, BlockType, ContentType, Line, Span
-from ..utils.config_reader import get_latex_delimiter_config
-from ..utils.language import detect_lang
-
-_default_delimiters = {"display": {"left": "$$", "right": "$$"}, "inline": {"left": "$", "right": "$"}}
-_latex_config = get_latex_delimiter_config() or _default_delimiters
-
-inline_left = _latex_config["inline"]["left"]
-inline_right = _latex_config["inline"]["right"]
-display_left = _latex_config["display"]["left"]
-display_right = _latex_config["display"]["right"]
-
-del _default_delimiters, _latex_config
-
-
-# ------------------------------------------------------------------ #
-# Public API
-# ------------------------------------------------------------------ #
-
-
-def merge_para_text(para_block: Block) -> str:
- """Convert a block's lines/spans into a single Markdown string.
-
- Accepted block types:
- TEXT, TITLE, INDEX, ABSTRACT, REF_TEXT, LIST, INTERLINE_EQUATION, PHONETIC
- {IMAGE/TABLE/CHART/CODE)_(CAPTION/FOOTNOTE), CODE_BODY
-
- Handles fenced code blocks, Markdown escaping, and TEXT-block prefix
- escape automatically.
- """
- if _is_fenced_code_block(para_block):
- code_text = _merge_para_text(para_block, escape_markdown=False, list_line_break="\n")
- if not code_text:
- return ""
- code_text = "\n".join(line.rstrip() for line in code_text.split("\n"))
- guess_lang = para_block.guess_lang or "txt"
- return f"```{guess_lang}\n{code_text}\n```"
-
- if para_block.type == BlockType.LIST and len(para_block.blocks):
- # (VLM) list block
- list_text = ""
- for block in para_block.blocks:
- item_text = _merge_para_text(block)
- list_text += f"{item_text} \n"
- return list_text
-
- para_text = _merge_para_text(para_block)
- if para_block.type == BlockType.TEXT: # (VLM) list do not escape
- para_text = _escape_text_block_markdown_prefix(para_text)
- return para_text
-
-
-# ------------------------------------------------------------------ #
-# Internal helpers
-# ------------------------------------------------------------------ #
-
-import re # noqa: E402
-
-_TEXT_BLOCK_MD_PREFIX_RE = re.compile(r"^(?P<indent>[ \t]{0,3})(?P<marker>#{1,6}|[+-])(?=[ \t])")
-
-
-def _escape_text_block_markdown_prefix(content: str) -> str:
- """Escape a leading Markdown block marker in an assembled text block."""
- if not content:
- return content
- match = _TEXT_BLOCK_MD_PREFIX_RE.match(content)
- if not match:
- return content
- marker_start = match.start("marker")
- return f"{content[:marker_start]}\\{content[marker_start:]}"
-
-
-def _is_fenced_code_block(para_block: Block) -> bool:
- return para_block.type == BlockType.CODE_BODY and para_block.sub_type == BlockType.CODE
-
-
-def _normalize_text_content(content: str) -> str:
- return full_to_half_exclude_marks(content or "")
-
-
-def _collect_text_for_lang_detection(para_block: Block) -> str:
- parts: list[str] = []
- for line in para_block.lines:
- for span in line.spans:
- if span.type == ContentType.TEXT:
- parts.append(_normalize_text_content(span.content))
- return "".join(parts)
-
-
-def _line_prefix(line_idx: int, line: Line, list_line_break: str = " \n") -> str:
- if line_idx >= 1 and line._is_list_start:
- return list_line_break
- return ""
-
-
-_MARKDOWN_SPECIAL = frozenset({"*", "_", "`", "~", "$"})
-
-
-def _escape_conservative_markdown_text(content: str) -> str:
- """Escape plain-text characters that carry inline Markdown semantics."""
- if not content:
- return content
- escaped: list[str] = []
- backslashes = 0
- for char in content:
- if char == "\\":
- escaped.append(char)
- backslashes += 1
- continue
- if char in _MARKDOWN_SPECIAL and backslashes % 2 == 0:
- escaped.append("\\")
- escaped.append(char)
- backslashes = 0
- return "".join(escaped)
-
-
-def _render_span(span: Span, *, escape_markdown: bool = True) -> tuple[str, str] | None:
- span_type = span.type
- content = ""
-
- if span_type == ContentType.TEXT:
- content = _normalize_text_content(span.content) # (VLM) SKIP
- if escape_markdown:
- content = _escape_conservative_markdown_text(content)
- elif span_type == ContentType.INLINE_EQUATION:
- if span.content:
- content = f"{inline_left}{span.content}{inline_right}"
- elif span_type == ContentType.INTERLINE_EQUATION:
- if span.content:
- content = f"\n{display_left}\n{span.content}\n{display_right}\n"
- # (VLM) if not(formula_enable) use image link
- else:
- return None
-
- content = content.strip()
- if not content:
- return None
- return span_type, content
-
-
-def _next_line_starts_with_lowercase_text(para_block: Block, line_idx: int) -> bool:
- if line_idx + 1 >= len(para_block.lines):
- return False
- next_spans = para_block.lines[line_idx + 1].spans
- if not next_spans:
- return False
- first = next_spans[0]
- if first.type != ContentType.TEXT:
- return False
- first_content = _normalize_text_content(first.content)
- return bool(first_content) and first_content[0].islower()
-
-
-def _join_rendered_span(
- para_block: Block, block_lang: str, line: Line, line_idx: int, span_idx: int, span_type: str, content: str
-) -> tuple[str, str]:
- if span_type == ContentType.INTERLINE_EQUATION:
- return content, ""
-
- is_last_span = bool(span_idx == len(line.spans) - 1)
-
- # 物理行末的普通文本统一走共享边界规则;行内公式及同行 span 仍保留渲染器原有处理。
- if is_last_span and span_type == ContentType.TEXT:
- return resolve_text_line_boundary(
- content,
- block_language=block_lang,
- next_starts_with_lowercase=_next_line_starts_with_lowercase_text(para_block, line_idx),
- )
-
- # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
- if block_lang in CJK_LANGS:
- if is_last_span and span_type != ContentType.INLINE_EQUATION:
- return content, ""
- # (VLM) use _has_following_joinable_span()
- return content, " "
-
- if span_type not in (ContentType.TEXT, ContentType.INLINE_EQUATION):
- return content, ""
- # 西方文本语境下 content间需要空格分隔
- return content, " "
-
-
-# ------------------------------------------------------------------ #
-# Core merge
-# ------------------------------------------------------------------ #
-
-
-def _merge_para_text(para_block: Block, *, escape_markdown: bool = True, list_line_break: str = " \n") -> str:
- """Core paragraph rendering shared by Pipeline and VLM backends."""
- block_lang = detect_lang(_collect_text_for_lang_detection(para_block))
- para_parts: list[str] = []
- # (VLM) escape_markdown_text = para_block.type != BlockType.CODE_BODY
-
- for line_idx, line in enumerate(para_block.lines):
- # (PIPELINE ONLY)
- if prefix := _line_prefix(line_idx, line, list_line_break):
- para_parts.append(prefix)
-
- for span_idx, span in enumerate(line.spans):
- rendered = _render_span(span, escape_markdown=escape_markdown)
- if rendered is None:
- continue
-
- span_type, content = rendered
- content, suffix = _join_rendered_span(para_block, block_lang, line, line_idx, span_idx, span_type, content)
- para_parts.append(content)
- if suffix:
- para_parts.append(suffix)
-
- return "".join(para_parts).rstrip()
diff --git a/mineru/render/merge_visual.py b/mineru/render/merge_visual.py
deleted file mode 100644
index 49241bfd..00000000
--- a/mineru/render/merge_visual.py
+++ /dev/null
@@ -1,267 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from copy import deepcopy
-from html import escape, unescape
-from typing import Any
-
-from ..backend.utils.raw_block_types import RAW_ALGORITHM
-from ..types import Block, BlockType, ContentType
-from .merge import inline_left, inline_right, merge_para_text
-
-# --------------------------------------------------------------------------- #
-# Merge IMAGE / TABLE / CHART / CODE composite blocks into a single
-# Markdown string. Shared by Pipeline and VLM backends.
-# --------------------------------------------------------------------------- #
-
-
-def merge_visual_para_text(para_block: Block, img_bucket_path: str = "") -> str:
- rendered_segments: list[tuple[str, str]] = []
-
- for block in _blocks_in_index_order(para_block.blocks):
- render_block = _inherit_parent_code_render_metadata(block, para_block)
- rendered_segments.extend(_render_visual_block_segments(render_block, para_block, img_bucket_path))
-
- para_text = ""
- prev_kind: str | None = None
- for segment_text, segment_kind in rendered_segments:
- if para_text:
- para_text += _visual_block_separator(prev_kind, segment_kind)
- para_text += segment_text
- prev_kind = segment_kind
-
- return para_text
-
-
-# --------------------------------------------------------------------------- #
-# Internal helpers — sorted by dependency order
-# --------------------------------------------------------------------------- #
-
-import re # noqa: E402
-
-
-def _blocks_in_index_order(blocks: list[Block]) -> list[Block]:
- return [b for _, b in sorted(enumerate(blocks), key=lambda item: (item[1].index, item[0]))]
-
-
-def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> Block:
- # 本地 Hybrid 模型会把 code_body 的 sub_type/guess_lang 提升到父 code block。
- # markdown 渲染 code_body 时需要把这两个字段临时透传回来,但不能修改原始输入。
- if block.type != BlockType.CODE_BODY:
- return block
- if parent_block.type != BlockType.CODE:
- return block
-
- needs_sub_type = not block.sub_type and parent_block.sub_type
- needs_guess_lang = not block.guess_lang and parent_block.guess_lang
- if not needs_sub_type and not needs_guess_lang:
- return block
-
- render_block = deepcopy(block)
- if needs_sub_type:
- render_block.sub_type = parent_block.sub_type
- if needs_guess_lang:
- render_block.guess_lang = parent_block.guess_lang
- return render_block
-
-
-# -- HTML helpers ------------------------------------------------------------
-
-
-def _prefix_table_img_src(html: str, img_bucket_path: str) -> str:
- if not html or not img_bucket_path:
- return html
- return re.sub(
- r'src="(?!data:)([^"]+)"',
- lambda m: f'src="{img_bucket_path}/{m.group(1)}"',
- html,
- )
-
-
-def _replace_eq_tags_in_table_html(html: str) -> str:
- if not html:
- return html
- return re.sub(
- r"<eq>(.*?)</eq>",
- lambda m: f" {inline_left}{unescape(m.group(1))}{inline_right} ",
- html,
- flags=re.DOTALL,
- )
-
-
-def _format_embedded_html(html: str, img_bucket_path: str) -> str:
- return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_bucket_path))
-
-
-def _build_media_path(img_bucket_path: str, image_path: str) -> str:
- if not image_path:
- return ""
- if not img_bucket_path:
- return image_path
- return f"{img_bucket_path}/{image_path}"
-
-
-# -- Visual body / details ---------------------------------------------------
-
-
-def _build_visual_details_block(content: Any, summary: str) -> str:
- normalized = _normalize_visual_content(content)
- if not normalized:
- return ""
- return f"<details>\n<summary>{summary}</summary>\n\n{normalized}\n</details>"
-
-
-def _normalize_visual_content(content: Any) -> str:
- if isinstance(content, list):
- return "\n".join(str(item) for item in content if str(item).strip())
- if isinstance(content, str):
- return content.strip()
- return ""
-
-
-def _build_visual_body_segments(
- *, image_path: str, content: str, img_bucket_path: str, details_summary: str
-) -> list[tuple[str, str]]:
- segments: list[tuple[str, str]] = []
- media_path = _build_media_path(img_bucket_path, image_path)
- if media_path:
- segments.append((f"![]({media_path})", "markdown_line"))
- details = _build_visual_details_block(content, details_summary)
- if details:
- segments.append((details, "details_block"))
- return segments
-
-
-def _render_algorithm_code_html(block: Block) -> str:
- """将 algorithm code body 渲染为 HTML div,保留缩进并支持行内公式。"""
- rendered_lines: list[str] = []
- for line in block.lines:
- line_parts: list[str] = []
- previous_span_type: str | None = None
- for span in line.spans:
- if span.type == ContentType.TEXT:
- line_parts.append(escape(span.content or "", quote=False))
- if span.content:
- previous_span_type = span.type
- elif span.type == ContentType.INLINE_EQUATION and span.content:
- if (
- previous_span_type == ContentType.INLINE_EQUATION
- and line_parts
- and not line_parts[-1].endswith((" ", "\n", "\t"))
- ):
- line_parts.append(" ")
- line_parts.append(f"{inline_left}{escape(span.content, quote=False)}{inline_right}")
- previous_span_type = span.type
- rendered_lines.append("".join(line_parts).rstrip())
-
- content = "\n".join(rendered_lines).strip("\n")
- if not content.strip():
- return ""
- return (
- '<div class="mineru-algorithm" style="white-space: pre-wrap; font-family:monospace;">\n'
- f"{content}\n"
- "</div>"
- )
-
-
-# -- Per-block-type segment rendering ----------------------------------------
-
-
-def _render_visual_block_segments(block: Block, para_block: Block, img_bucket_path: str) -> list[tuple[str, str]]:
- # 将单个视觉子 block 渲染成一个或多个 segment。
- # 文本类子块统一输出 markdown_line;
- # table 的 html 输出为 html_block,供后续决定是否需要空行隔开。
-
- block_type = block.type
-
- if block_type == BlockType.CODE_BODY and block.sub_type == RAW_ALGORITHM:
- text = _render_algorithm_code_html(block)
- if text:
- return [(text, "html_block")]
- return []
-
- # text-like sub-blocks (caption / footnote / code body)
- if block_type in (
- BlockType.IMAGE_CAPTION,
- BlockType.IMAGE_FOOTNOTE,
- BlockType.TABLE_CAPTION,
- BlockType.TABLE_FOOTNOTE,
- BlockType.CODE_BODY,
- BlockType.CODE_CAPTION,
- BlockType.CODE_FOOTNOTE,
- BlockType.CHART_CAPTION,
- BlockType.CHART_FOOTNOTE,
- ):
- text = merge_para_text(block)
- if text.strip():
- return [(text, "markdown_line")]
- return []
-
- # IMAGE_BODY
- if block_type == BlockType.IMAGE_BODY:
- image_segments: list[tuple[str, str]] = []
- for line in block.lines:
- for span in line.spans:
- if span.type != ContentType.IMAGE:
- continue
- image_segments.extend(
- _build_visual_body_segments(
- image_path=span.image_path,
- content=span.content,
- img_bucket_path=img_bucket_path,
- details_summary=para_block.sub_type or "image content",
- )
- )
- return image_segments
-
- # CHART_BODY
- if block_type == BlockType.CHART_BODY:
- chart_segments: list[tuple[str, str]] = []
- for line in block.lines:
- for span in line.spans:
- if span.type != ContentType.CHART:
- continue
- chart_segments.extend(
- _build_visual_body_segments(
- image_path=span.image_path,
- content=span.content,
- img_bucket_path=img_bucket_path,
- details_summary=para_block.sub_type or "chart content",
- )
- )
- return chart_segments
-
- # TABLE_BODY
- if block_type == BlockType.TABLE_BODY:
- table_segments: list[tuple[str, str]] = []
- for line in block.lines:
- for span in line.spans:
- if span.type != ContentType.TABLE:
- continue
- 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"))
- return table_segments
-
- return []
-
-
-# -- Segment separator -------------------------------------------------------
-
-
-def _visual_block_separator(prev_kind: str | None, current_kind: str) -> str:
- # 根据前后 segment 类型决定分隔符:
- # 1. 普通 markdown 行之间用 hard break(" \\n")
- # 2. 进入 html block 前只换一行
- # 3. html block 后必须留空行,否则后续文本仍会被当作 html 块内容
- if prev_kind == "html_block":
- # Raw HTML blocks need a blank line after them, otherwise the following
- # markdown text is still treated as part of the HTML block.
- return "\n\n"
- if prev_kind == "details_block" or current_kind == "details_block":
- return "\n\n"
- if current_kind == "html_block":
- return "\n"
- return " \n"
diff --git a/mineru/render/office/__init__.py b/mineru/render/office/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/mineru/render/office/merge.py b/mineru/render/office/merge.py
deleted file mode 100644
index 1da49edc..00000000
--- a/mineru/render/office/merge.py
+++ /dev/null
@@ -1,949 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import unicodedata
-from collections.abc import Generator
-from dataclasses import dataclass, field
-from html import escape
-from typing import Any
-
-from ...backend.utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix
-from ...types import Block, BlockType, ContentType, Span
-from ...utils.config_reader import get_latex_delimiter_config
-
-latex_delimiters_config = get_latex_delimiter_config()
-
-default_delimiters = {"display": {"left": "$$", "right": "$$"}, "inline": {"left": "$", "right": "$"}}
-
-delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters
-
-display_left_delimiter = delimiters["display"]["left"]
-display_right_delimiter = delimiters["display"]["right"]
-inline_left_delimiter = delimiters["inline"]["left"]
-inline_right_delimiter = delimiters["inline"]["right"]
-
-OFFICE_INLINE_SYNTAX_HTML = "html"
-OFFICE_INLINE_SYNTAX_MARKDOWN = "markdown"
-OFFICE_MARKDOWN_STYLE_WRAPPERS = {
- frozenset({"bold"}): "**",
- frozenset({"italic"}): "*",
- frozenset({"strikethrough"}): "~~",
- frozenset({"bold", "italic"}): "***",
-}
-OFFICE_COMPLEX_HTML_STYLES = {
- "underline",
- "emphasis",
- "superscript",
- "subscript",
-}
-OFFICE_EMPHASIS_STYLE = "text-emphasis: dot; text-emphasis-position: under;"
-STYLE_WRAPPER_OPEN = {
- "emphasis": f'<span style="{OFFICE_EMPHASIS_STYLE}">',
- "strikethrough": "<s>",
- "italic": "<em>",
- "bold": "<strong>",
- "underline": "<u>",
- "superscript": "<sup>",
- "subscript": "<sub>",
-}
-STYLE_WRAPPER_CLOSE = {
- "emphasis": "</span>",
- "strikethrough": "</s>",
- "italic": "</em>",
- "bold": "</strong>",
- "underline": "</u>",
- "superscript": "</sup>",
- "subscript": "</sub>",
-}
-
-
-@dataclass
-class RenderedPart:
- """保存一个已渲染行内片段及其原始元数据,供段落拼接阶段使用。"""
-
- span_type: str
- rendered_content: str
- raw_content: str = ""
- style: list = field(default_factory=list)
- has_markdown_wrapper: bool = False
-
-
-@dataclass
-class StyleRangeToken:
- """保存 HTML 样式范围合并所需的片段内容和样式集合。"""
-
- content: str
- style: set[str] = field(default_factory=set)
-
-
-def _apply_markdown_style(content: str, style: list) -> str:
- """按可枚举 Markdown style key 渲染 wrapper,未知组合保持原文。"""
- if not style or not content:
- return content
-
- style_key = _get_markdown_style_key(style)
- wrapper = OFFICE_MARKDOWN_STYLE_WRAPPERS.get(style_key)
- if wrapper:
- return f"{wrapper}{content}{wrapper}"
- return content
-
-
-def _apply_html_style(content: str, style: list) -> str:
- """用 HTML 标签渲染 Office 行内样式,适配不宜使用 Markdown wrapper 的场景。"""
- if not style or not content:
- return content
-
- if "superscript" in style:
- content = f"<sup>{content}</sup>"
- elif "subscript" in style:
- content = f"<sub>{content}</sub>"
-
- if "underline" in style:
- content = f"<u>{content}</u>"
-
- if "bold" in style:
- content = f"<strong>{content}</strong>"
-
- if "italic" in style:
- content = f"<em>{content}</em>"
-
- if "strikethrough" in style:
- content = f"<s>{content}</s>"
-
- if "emphasis" in style:
- content = f'<span style="{OFFICE_EMPHASIS_STYLE}">{content}</span>'
-
- return content
-
-
-def _apply_configured_style(content: str, style: list, inline_syntax: str) -> str:
- """按 block 级 auto 选择出来的语法渲染行内样式。"""
- if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:
- return _apply_markdown_style(content, style)
- return _apply_html_style(content, style)
-
-
-def _render_link(text: str, url: str, inline_syntax: str) -> str:
- """按 block 级语法渲染链接,复杂 HTML block 内统一使用 <a>。"""
- if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:
- return f"[{text}]({url})"
- return f'<a href="{escape(url, quote=True)}">{text}</a>'
-
-
-def _escape_office_inline_text(content: str, inline_syntax: str) -> str:
- """根据当前 block 语法转义普通文本,HTML block 内同时避开标签和 Markdown delimiter。"""
- if not content:
- return content
- if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:
- return escape_conservative_markdown_text(content)
- return escape_conservative_markdown_text(escape(content, quote=False))
-
-
-def get_title_level(para_block: Block) -> int:
- title_level = getattr(para_block, "level", None)
- if title_level is None:
- title_level = 2
- return title_level
-
-
-def _make_rendered_part(
- span_type: str,
- rendered_content: str,
- raw_content: str = "",
- style: list[str] | None = None,
- has_markdown_wrapper: bool = False,
-) -> RenderedPart:
- """构造段落渲染中间片段,并保留 Markdown 边界补空格所需的原始信息。"""
- return RenderedPart(
- span_type=span_type,
- rendered_content=rendered_content,
- raw_content=raw_content,
- style=style or [],
- has_markdown_wrapper=has_markdown_wrapper,
- )
-
-
-def _get_first_non_whitespace_char(text: str) -> str | None:
- """返回文本中第一个非空白字符,用于 block 级 Markdown 风险判定。"""
- for ch in text:
- if not ch.isspace():
- return ch
- return None
-
-
-def _get_last_non_whitespace_char(text: str) -> str | None:
- """返回文本中最后一个非空白字符,用于 block 级 Markdown 风险判定。"""
- for ch in reversed(text):
- if not ch.isspace():
- return ch
- return None
-
-
-def _is_punctuation_or_symbol(ch: str) -> bool:
- """判断字符是否属于 Unicode 标点或符号类别。"""
- return unicodedata.category(ch).startswith(("P", "S"))
-
-
-def _is_boundary_text_char(ch: str) -> bool:
- """判断字符是否是会和 Markdown delimiter 紧贴产生歧义的普通文本字符。"""
- if ch.isspace():
- return False
- return not _is_punctuation_or_symbol(ch)
-
-
-def _needs_markdown_boundary_space(
- prev_part: RenderedPart,
- next_part: RenderedPart,
-) -> bool:
- """判断 Markdown wrapper 后是否需要补空格,避免标点结尾的 wrapper 无法被解析。"""
- if not prev_part.has_markdown_wrapper:
- return False
- if next_part.span_type in {
- ContentType.HYPERLINK,
- ContentType.INLINE_EQUATION,
- ContentType.INTERLINE_EQUATION,
- }:
- return False
-
- prev_raw = prev_part.raw_content
- next_raw = next_part.raw_content
- if not prev_raw.strip() or not next_raw.strip():
- return False
- if prev_raw[-1].isspace() or next_raw[0].isspace():
- return False
-
- prev_char = _get_last_non_whitespace_char(prev_raw)
- next_char = _get_first_non_whitespace_char(next_raw)
- if prev_char is None or next_char is None:
- return False
- if not _is_punctuation_or_symbol(prev_char):
- return False
- return _is_boundary_text_char(next_char)
-
-
-def _join_rendered_parts(parts: list[RenderedPart]) -> str:
- """按 Office 段落规则拼接行内片段,并为行内公式补必要空格。"""
- rendered_parts = []
- prev_part = None
-
- for i, part in enumerate(parts):
- span_type = part.span_type
- content = part.rendered_content
- is_last = i == len(parts) - 1
-
- if span_type == ContentType.INLINE_EQUATION:
- if rendered_parts and not rendered_parts[-1].endswith(" "):
- rendered_parts.append(" ")
- rendered_parts.append(content)
- if not is_last:
- rendered_parts.append(" ")
- else:
- if prev_part is not None and _needs_markdown_boundary_space(prev_part, part):
- rendered_parts.append(" ")
- rendered_parts.append(content)
-
- prev_part = part
-
- return "".join(rendered_parts)
-
-
-def _strip_text_block_markdown_edges(content: str) -> str:
- """去掉 Markdown 文本块首尾普通空白,避免段首缩进被渲染成代码块。"""
- if not content:
- return content
- return content.strip()
-
-
-def _get_visible_space_marker(style: list) -> str | None:
- """根据可见空格样式选择 Markdown marker,下划线优先于删除线。"""
- if not style:
- return None
- if "underline" in style:
- return "_"
- if "strikethrough" in style:
- return "-"
- return None
-
-
-def _is_ascii_space_only(content: str) -> bool:
- """判断文本是否只由普通 ASCII 空格组成。"""
- return bool(content) and all(char == " " for char in content)
-
-
-def _replace_ascii_spaces_with_marker(
- content: str,
- marker: str,
- inline_syntax: str,
-) -> str:
- """将普通 ASCII 空格替换为指定 marker,其他文本按当前 block 语法转义。"""
- rendered_parts = []
- text_buffer = []
-
- def flush_text_buffer() -> None:
- if text_buffer:
- rendered_parts.append(_escape_office_inline_text("".join(text_buffer), inline_syntax))
- text_buffer.clear()
-
- for char in content:
- if char == " ":
- flush_text_buffer()
- rendered_parts.append(marker)
- else:
- text_buffer.append(char)
-
- flush_text_buffer()
- return "".join(rendered_parts)
-
-
-def _render_text_with_edge_space_markers(
- content: str,
- marker: str,
- inline_syntax: str,
-) -> str:
- """渲染非空文本:只把首尾 ASCII 空格转成 marker,中间普通空格保持原样。"""
- leading_space_count = len(content) - len(content.lstrip(" "))
- trailing_space_count = len(content) - len(content.rstrip(" "))
- text_end = len(content) - trailing_space_count if trailing_space_count else len(content)
- core_text = content[leading_space_count:text_end]
- return marker * leading_space_count + _escape_office_inline_text(core_text, inline_syntax) + marker * trailing_space_count
-
-
-def _render_visible_space_marker_text(
- content: str,
- style: list,
- inline_syntax: str,
- render_style: list | None = None,
-) -> str:
- """渲染可见样式空格:纯空白用 marker,非空文本只处理边缘空格。"""
- marker = _get_visible_space_marker(style)
- render_style = style if render_style is None else render_style
- if marker is None:
- return _apply_configured_style(
- _escape_office_inline_text(content, inline_syntax),
- render_style or [],
- inline_syntax,
- )
-
- style = style or []
- if marker == "-" and not _is_ascii_space_only(content):
- return _apply_configured_style(
- _render_text_with_edge_space_markers(content, marker, inline_syntax),
- render_style,
- inline_syntax,
- )
-
- if _is_ascii_space_only(content):
- rendered_content = _replace_ascii_spaces_with_marker(
- content,
- marker,
- inline_syntax,
- )
- ignored_style = "underline" if marker == "_" else "strikethrough"
- render_style = [name for name in (render_style or []) if name != ignored_style]
- return _apply_configured_style(rendered_content, render_style, inline_syntax)
-
- rendered_content = _render_text_with_edge_space_markers(
- content,
- marker,
- inline_syntax,
- )
- return _apply_configured_style(rendered_content, render_style, inline_syntax)
-
-
-def _render_styled_inline_text(content: str, style: list, inline_syntax: str) -> str:
- """渲染行内文本内容,统一复用可见空格 marker 规则。"""
- if content and _get_visible_space_marker(style):
- return _render_visible_space_marker_text(content, style, inline_syntax)
-
- escaped_content = _escape_office_inline_text(content, inline_syntax)
- return _apply_configured_style(escaped_content, style, inline_syntax)
-
-
-def _escape_standalone_marker_rule(content: str) -> str:
- """独立一行全是 marker 时转义首个字符,避免被 Markdown 当作分隔线。"""
- if content and all(char == "_" for char in content):
- return f"\\{content}"
- if content and all(char == "-" for char in content):
- return f"\\{content}"
- return content
-
-
-def _append_text_part(
- parts: list[RenderedPart],
- original_content: str,
- span_style: list[str],
- inline_syntax: str,
- render_style: list[str] | None = None,
-) -> None:
- render_style = span_style if render_style is None else render_style
- if original_content and _get_visible_space_marker(span_style):
- parts.append(
- _make_rendered_part(
- ContentType.TEXT,
- _render_visible_space_marker_text(
- original_content,
- span_style,
- inline_syntax,
- render_style,
- ),
- raw_content=original_content,
- style=render_style,
- has_markdown_wrapper=_has_markdown_wrapper(render_style, inline_syntax),
- )
- )
- return
-
- escaped_content = _escape_office_inline_text(original_content, inline_syntax)
- content_stripped = escaped_content.strip()
- if content_stripped:
- styled = _apply_configured_style(
- content_stripped,
- render_style,
- inline_syntax,
- )
- leading = escaped_content[: len(escaped_content) - len(escaped_content.lstrip())]
- trailing = escaped_content[len(escaped_content.rstrip()) :]
- parts.append(
- _make_rendered_part(
- ContentType.TEXT,
- leading + styled + trailing,
- raw_content=original_content,
- style=render_style,
- has_markdown_wrapper=_has_markdown_wrapper(render_style, inline_syntax),
- )
- )
- elif original_content:
- visible_styles = {"underline", "strikethrough"}
- rendered_content = original_content
- if span_style and any(s in visible_styles for s in span_style):
- rendered_content = _apply_configured_style(
- _escape_office_inline_text(rendered_content, inline_syntax),
- render_style,
- inline_syntax,
- )
- parts.append(
- _make_rendered_part(
- ContentType.TEXT,
- rendered_content,
- raw_content=original_content,
- style=render_style,
- has_markdown_wrapper=_has_markdown_wrapper(render_style, inline_syntax),
- )
- )
-
-
-def _split_plain_blank_edges(
- text_spans: list[dict],
-) -> tuple[list[dict], list[dict], list[dict]]:
- """拆出首尾纯空白 span,避免把段首 emphasis-only 空格包进 HTML 外层后无法 trim。"""
- start = 0
- end = len(text_spans)
- while start < end and not str(text_spans[start].get("content", "")).strip():
- start += 1
- while end > start and not str(text_spans[end - 1].get("content", "")).strip():
- end -= 1
- return text_spans[:start], text_spans[start:end], text_spans[end:]
-
-
-def _get_markdown_style_key(
- style: list | tuple | set | None,
-) -> frozenset[str] | str | None:
- """返回可安全使用 Markdown 的样式 key;空样式返回 None,不支持返回空串。"""
- style_set = {name for name in (style or []) if name}
- if not style_set:
- return None
- if style_set & OFFICE_COMPLEX_HTML_STYLES:
- return ""
- style_key = frozenset(style_set)
- if style_key in OFFICE_MARKDOWN_STYLE_WRAPPERS:
- return style_key
- return ""
-
-
-def _is_simple_markdown_style(style: list | tuple | set | None) -> bool:
- """判断样式是否适合保留为简单 Markdown 输出。"""
- return _get_markdown_style_key(style) != ""
-
-
-def _has_markdown_wrapper(
- style: list | tuple | set | None,
- inline_syntax: str,
-) -> bool:
- """判断当前片段是否实际使用 Markdown wrapper,供拼接阶段补空格。"""
- if inline_syntax != OFFICE_INLINE_SYNTAX_MARKDOWN:
- return False
- return _get_markdown_style_key(style) in OFFICE_MARKDOWN_STYLE_WRAPPERS
-
-
-def _iter_para_inline_spans(para_block: Block) -> Generator[Span, None, None]:
- """按 block 原始顺序遍历行内 span,供 auto 语法判定复用。"""
- for line in para_block.lines:
- for span in line.spans:
- yield span
-
-
-def _hyperlink_requires_html(span: Span) -> bool:
- """判断 hyperlink 是否存在混合或复杂样式,需要整块切到 HTML。"""
- children = span._children
- if not children:
- return not _is_simple_markdown_style(span._style)
-
- child_style_keys = set()
- for child in children:
- if child.type != ContentType.TEXT:
- return True
- content = child.content
- if not content.strip():
- continue
- child_style = child._style
- child_style_key = _get_markdown_style_key(child_style)
- if child_style_key == "":
- return True
- child_style_keys.add(child_style_key)
-
- return len(child_style_keys) > 1
-
-
-def _iter_block_inline_units(para_block: Block) -> Generator[dict[str, Any], None, None]:
- """把 block 展开为线性文本单元,用于判断 Markdown 边界风险。"""
- if para_block.type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- section_number = para_block.section_number
- if para_block.is_numbered_style and section_number:
- yield {
- "span_type": ContentType.TEXT,
- "content": f"{section_number} ",
- "style": [],
- }
-
- for span in _iter_para_inline_spans(para_block):
- span_type = span.type
- if span_type == ContentType.TEXT:
- yield {
- "span_type": ContentType.TEXT,
- "content": span.content,
- "style": span._style,
- }
- elif span_type == ContentType.HYPERLINK:
- children = span._children
- if children:
- for child in children:
- if child.type != ContentType.TEXT:
- continue
- yield {
- "span_type": ContentType.HYPERLINK,
- "content": str(child.content),
- "style": child._style,
- }
- else:
- yield {
- "span_type": ContentType.HYPERLINK,
- "content": span.content,
- "style": span._style,
- }
- elif span_type in {ContentType.INLINE_EQUATION, ContentType.INTERLINE_EQUATION}:
- yield {
- "span_type": span_type,
- "content": span.content,
- "style": [],
- }
-
-
-def _select_block_inline_syntax(para_block: Block) -> str:
- """按 block 粒度选择 inline 输出语法:简单样式用 Markdown,复杂样式统一 HTML。"""
- units = list(_iter_block_inline_units(para_block))
- markdown_style_keys = set()
-
- for span in _iter_para_inline_spans(para_block):
- span_type = span.type
- if span_type == ContentType.HYPERLINK and _hyperlink_requires_html(span):
- return OFFICE_INLINE_SYNTAX_HTML
-
- for unit in units:
- content = unit.get("content", "")
- if not content:
- continue
- style_key = _get_markdown_style_key(unit.get("style"))
- if style_key == "":
- return OFFICE_INLINE_SYNTAX_HTML
- if style_key is not None:
- markdown_style_keys.add(style_key)
- if len(markdown_style_keys) > 1:
- return OFFICE_INLINE_SYNTAX_HTML
-
- return OFFICE_INLINE_SYNTAX_MARKDOWN
-
-
-def _append_style_range_token(
- tokens: list[StyleRangeToken],
- rendered_content: str,
- style: list[str] | set[str] | None,
-) -> None:
- """追加一个可参与 HTML 范围合并的文本 token,空内容不进入 wrapper diff。"""
- if not rendered_content:
- return
- tokens.append(
- StyleRangeToken(
- content=rendered_content,
- style=set(style or []),
- )
- )
-
-
-def _extend_style_range_tokens(
- tokens: list[StyleRangeToken],
- original_content: str,
- span_style: list[str],
- inline_syntax: str,
-) -> None:
- """把原始 text span 拆成 HTML 合并 token,并保留现有可见空格 marker 规则。"""
- if not original_content:
- return
-
- marker = _get_visible_space_marker(span_style)
- if marker:
- render_style = list(span_style or [])
- if marker == "-" and not _is_ascii_space_only(original_content):
- rendered_content = _render_text_with_edge_space_markers(
- original_content,
- marker,
- inline_syntax,
- )
- elif _is_ascii_space_only(original_content):
- rendered_content = _replace_ascii_spaces_with_marker(
- original_content,
- marker,
- inline_syntax,
- )
- ignored_style = "underline" if marker == "_" else "strikethrough"
- render_style = [name for name in render_style if name != ignored_style]
- else:
- rendered_content = _render_text_with_edge_space_markers(
- original_content,
- marker,
- inline_syntax,
- )
- _append_style_range_token(
- tokens,
- rendered_content,
- render_style,
- )
- return
-
- escaped_content = _escape_office_inline_text(original_content, inline_syntax)
- content_stripped = escaped_content.strip()
- if content_stripped:
- leading = escaped_content[: len(escaped_content) - len(escaped_content.lstrip())]
- trailing = escaped_content[len(escaped_content.rstrip()) :]
- if leading:
- _append_style_range_token(
- tokens,
- leading,
- [],
- )
- _append_style_range_token(
- tokens,
- content_stripped,
- span_style,
- )
- if trailing:
- _append_style_range_token(
- tokens,
- trailing,
- [],
- )
- else:
- _append_style_range_token(tokens, original_content, [])
-
-
-def _build_style_range_tokens(
- text_spans: list[dict],
- inline_syntax: str,
-) -> list[StyleRangeToken]:
- """将连续文本 span 标准化为 HTML token 序列,供统一 wrapper writer 渲染。"""
- tokens = []
- for span in text_spans:
- _extend_style_range_tokens(
- tokens,
- str(span.get("content", "")),
- span.get("style", []),
- inline_syntax,
- )
- return tokens
-
-
-def _style_range_stack(token: StyleRangeToken) -> list[str]:
- """按外到内顺序生成 HTML block 需要打开的 wrapper 栈。"""
- style = token.style
- stack = []
- if "emphasis" in style:
- stack.append("emphasis")
- if "strikethrough" in style:
- stack.append("strikethrough")
- if "italic" in style:
- stack.append("italic")
- if "bold" in style:
- stack.append("bold")
- if "underline" in style:
- stack.append("underline")
- if "superscript" in style:
- stack.append("superscript")
- elif "subscript" in style:
- stack.append("subscript")
- return stack
-
-
-def _style_wrapper_open(wrapper: str) -> str:
- """返回指定 wrapper 的打开标记。"""
- return STYLE_WRAPPER_OPEN.get(wrapper, "")
-
-
-def _style_wrapper_close(wrapper: str) -> str:
- """返回指定 wrapper 的关闭标记。"""
- return STYLE_WRAPPER_CLOSE.get(wrapper, "")
-
-
-def _common_stack_prefix_len(
- current_stack: list[str],
- next_stack: list[str],
-) -> int:
- """计算两个 wrapper 栈从外到内的共同前缀长度。"""
- prefix_len = 0
- for current, next_item in zip(current_stack, next_stack):
- if current != next_item:
- break
- prefix_len += 1
- return prefix_len
-
-
-def _render_style_range_tokens(tokens: list[StyleRangeToken]) -> str:
- """使用 HTML wrapper stack diff 渲染连续文本 token,合并可连续表达的共同样式。"""
- rendered_parts = []
- current_stack = []
-
- for token in tokens:
- next_stack = _style_range_stack(token)
- prefix_len = _common_stack_prefix_len(current_stack, next_stack)
-
- for wrapper in reversed(current_stack[prefix_len:]):
- rendered_parts.append(_style_wrapper_close(wrapper))
- for wrapper in next_stack[prefix_len:]:
- rendered_parts.append(_style_wrapper_open(wrapper))
-
- rendered_parts.append(token.content)
- current_stack = next_stack
-
- for wrapper in reversed(current_stack):
- rendered_parts.append(_style_wrapper_close(wrapper))
-
- return "".join(rendered_parts)
-
-
-def _append_markdown_grouped_text_parts(
- parts: list[RenderedPart],
- text_spans: list[dict[str, Any]],
-) -> None:
- """渲染简单 Markdown block,按可枚举 style key 合并相邻等价片段。"""
- pending_content = []
- pending_style = None
- pending_style_key = None
- has_pending = False
-
- def flush_pending() -> None:
- nonlocal pending_content, pending_style, pending_style_key, has_pending
- if pending_content:
- _append_text_part(
- parts,
- "".join(pending_content),
- list(pending_style or []),
- OFFICE_INLINE_SYNTAX_MARKDOWN,
- )
- pending_content = []
- pending_style = None
- pending_style_key = None
- has_pending = False
-
- for span in text_spans:
- span_style = tuple(span.get("style", []))
- span_style_key = _get_markdown_style_key(span_style)
- if not has_pending:
- pending_style = span_style
- pending_style_key = span_style_key
- has_pending = True
- if span_style_key != pending_style_key:
- flush_pending()
- pending_style = span_style
- pending_style_key = span_style_key
- has_pending = True
- pending_content.append(str(span.get("content", "")))
- flush_pending()
-
-
-def _append_style_grouped_text_parts(
- parts: list[RenderedPart],
- text_spans: list[dict[str, Any]],
- inline_syntax: str,
-) -> None:
- """按 block 语法渲染连续文本 span:简单 Markdown,复杂 HTML。"""
- if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:
- _append_markdown_grouped_text_parts(parts, text_spans)
- return
-
- leading_spans, core_spans, trailing_spans = _split_plain_blank_edges(text_spans)
- for span in leading_spans:
- _append_text_part(
- parts,
- span.get("content", ""),
- span.get("style", []),
- inline_syntax,
- )
-
- tokens = _build_style_range_tokens(core_spans, inline_syntax)
- if tokens:
- rendered_content = _render_style_range_tokens(tokens)
- parts.append(
- _make_rendered_part(
- ContentType.TEXT,
- rendered_content,
- )
- )
-
- for span in trailing_spans:
- _append_text_part(
- parts,
- span.get("content", ""),
- span.get("style", []),
- inline_syntax,
- )
-
-
-def _render_hyperlink_children_label(children: list[Span], inline_syntax: str) -> str:
- """渲染 hyperlink 的子文本片段,保留各自样式后再组成同一个链接 label。"""
- child_parts = []
- child_text_spans = []
- for child in children or []:
- if child.type != ContentType.TEXT:
- continue
- child_text_spans.append({"content": child.content, "style": child._style})
- _append_style_grouped_text_parts(child_parts, child_text_spans, inline_syntax)
- return _join_rendered_parts(child_parts).strip()
-
-
-def _append_hyperlink_part(
- parts: list[RenderedPart],
- original_content: str,
- span_style: list[str],
- inline_syntax: str,
- url: str = "",
- plain_text_only: bool = False,
- children: list[Span] | None = None,
-) -> None:
- """渲染 hyperlink 片段;HTML block 使用 <a>,Markdown block 使用 []()。"""
- if children:
- styled_text = _render_hyperlink_children_label(children, inline_syntax)
- if not styled_text:
- return
- rendered_content = styled_text if plain_text_only else _render_link(styled_text, url, inline_syntax)
- else:
- stripped_content = original_content.strip()
- if not stripped_content:
- return
-
- styled_text = _render_styled_inline_text(
- stripped_content,
- span_style,
- inline_syntax,
- )
- if plain_text_only:
- leading = original_content[: len(original_content) - len(original_content.lstrip())]
- trailing = original_content[len(original_content.rstrip()) :]
- rendered_content = leading + styled_text + trailing
- else:
- rendered_content = _render_link(styled_text, url, inline_syntax)
-
- parts.append(
- _make_rendered_part(
- ContentType.HYPERLINK,
- rendered_content,
- )
- )
-
-
-def merge_para_with_text(para_block: Block, escape_text_block_prefix: bool = True) -> str:
- """将 Office 段落 block 渲染为 Markdown/HTML 混合文本,按 block 自动选择行内语法。"""
- inline_syntax = _select_block_inline_syntax(para_block)
- parts = []
- text_span_buffer = []
-
- def flush_text_span_buffer() -> None:
- """遇到公式、超链接等边界时落盘连续文本 span,避免跨语义边界合并。"""
- if not text_span_buffer:
- return
- _append_style_grouped_text_parts(parts, text_span_buffer, inline_syntax)
- text_span_buffer.clear()
-
- if para_block.type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- if para_block.is_numbered_style:
- section_number = para_block.section_number
- if section_number:
- parts.append(
- _make_rendered_part(
- ContentType.TEXT,
- f"{section_number} ",
- )
- )
-
- for line in para_block.lines:
- for span in line.spans:
- span_type = span.type
- span_style = span._style
-
- if span_type == ContentType.TEXT:
- text_span_buffer.append(
- {
- "content": span.content,
- "style": span_style,
- }
- )
- elif span_type == ContentType.INLINE_EQUATION:
- flush_text_span_buffer()
- content = f"{inline_left_delimiter}{span.content}{inline_right_delimiter}"
- content = content.strip()
- if content:
- parts.append(
- _make_rendered_part(
- span_type,
- content,
- )
- )
- elif span_type == ContentType.INTERLINE_EQUATION:
- flush_text_span_buffer()
- content = f"\n{display_left_delimiter}\n{span.content}\n{display_right_delimiter}\n"
- content = content.strip()
- if content:
- parts.append(
- _make_rendered_part(
- span_type,
- content,
- )
- )
- elif span_type == ContentType.HYPERLINK:
- flush_text_span_buffer()
- _append_hyperlink_part(
- parts,
- span.content,
- span_style,
- inline_syntax,
- url=span._url,
- children=span._children,
- )
- else:
- flush_text_span_buffer()
-
- flush_text_span_buffer()
- para_text = _join_rendered_parts(parts)
- if para_block.type == BlockType.TEXT:
- para_text = _strip_text_block_markdown_edges(para_text)
- para_text = _escape_standalone_marker_rule(para_text)
- if escape_text_block_prefix:
- para_text = escape_text_block_markdown_prefix(para_text)
- return para_text
diff --git a/mineru/render/office/output.py b/mineru/render/office/output.py
deleted file mode 100644
index 18f4fb23..00000000
--- a/mineru/render/office/output.py
+++ /dev/null
@@ -1,731 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import re
-from collections.abc import Generator
-from typing import Any
-
-from ...types import Block, BlockType, ContentType, ContentTypeV2, Line, Span
-from ..markdown_table import to_markdown_table
-from .merge import (
- _append_hyperlink_part,
- _append_text_part,
- _apply_configured_style,
- _escape_office_inline_text,
- _join_rendered_parts,
- _make_rendered_part,
- _render_link,
- _select_block_inline_syntax,
- get_title_level,
- inline_left_delimiter,
- inline_right_delimiter,
- merge_para_with_text,
-)
-
-
-def _prefix_table_img_src(html: str, img_bucket_path: str) -> str:
- """给表格 HTML 内的本地图片 src 加上输出图片目录前缀。"""
- if not html or not img_bucket_path:
- return html
- return re.sub(
- r'src="(?!data:)([^"]+)"',
- lambda m: f'src="{img_bucket_path}/{m.group(1)}"',
- html,
- )
-
-
-def _replace_eq_tags_in_table_html(html: str) -> str:
- """把表格或图表 HTML 中的 <eq> 标签替换为当前配置的行内公式定界符。"""
- if not html:
- return html
- return re.sub(
- r"<eq>(.*?)</eq>",
- lambda m: f" {inline_left_delimiter}{m.group(1)}{inline_right_delimiter} ",
- html,
- flags=re.DOTALL,
- )
-
-
-def _format_embedded_html(html: str, img_bucket_path: str) -> str:
- """统一处理 Office 嵌入 HTML 的图片路径和行内公式标签。"""
- return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_bucket_path))
-
-
-def _build_media_path(img_bucket_path: str, image_path: str) -> str:
- """构造图片展示路径,空图片路径保持为空。"""
- if not image_path:
- return ""
- if not img_bucket_path:
- return image_path
- return f"{img_bucket_path}/{image_path}"
-
-
-def _get_ordered_list_start(list_block: Block) -> int:
- """读取有序列表起始编号,兼容旧版数据缺少 start 字段的情况。"""
- try:
- start = list_block.start
- if start is None:
- start = 1
- return int(start)
- except (TypeError, ValueError):
- return 1
-
-
-def _get_list_ilevel(list_block: Block) -> int:
- """安全读取 DOCX 列表原始 ilevel,异常值按顶层 0 处理。"""
- try:
- ilevel = list_block.ilevel
- if ilevel is None:
- ilevel = 0
- return int(ilevel)
- except (TypeError, ValueError):
- return 0
-
-
-def _get_relative_list_ilevel(list_block: Block, root_ilevel: int) -> int:
- """将 DOCX 原始 ilevel 转为当前列表树内的相对缩进层级。"""
- return max(_get_list_ilevel(list_block) - root_ilevel, 0)
-
-
-def _flatten_list_items(list_block: Block, root_ilevel: int | None = None) -> list[str]:
- """Recursively flatten nested list blocks into a list of prefixed item strings."""
- items = []
- if root_ilevel is None:
- root_ilevel = _get_list_ilevel(list_block)
- relative_ilevel = _get_relative_list_ilevel(list_block, root_ilevel)
- attribute = list_block._list_attribute or "unordered"
- indent = " " * relative_ilevel
- ordered_counter = _get_ordered_list_start(list_block)
-
- for block in list_block.blocks:
- if block.type in [BlockType.LIST, BlockType.INDEX]:
- items.extend(_flatten_list_items(block, root_ilevel))
- else:
- item_text = merge_para_with_text(block, escape_text_block_prefix=False)
- if item_text.strip():
- if attribute == "ordered":
- items.append(f"{indent}{ordered_counter}. {item_text}")
- ordered_counter += 1
- else:
- items.append(f"{indent}- {item_text}")
-
- return items
-
-
-def _flatten_structured_list_items(list_block: Block, root_ilevel: int | None = None) -> list[dict[str, Any]]:
- """递归展开 Office 嵌套列表,生成 structured_content list item 字典。"""
- items = []
- if root_ilevel is None:
- root_ilevel = _get_list_ilevel(list_block)
- relative_ilevel = _get_relative_list_ilevel(list_block, root_ilevel)
- attribute = list_block._list_attribute or "unordered"
- ordered_counter = _get_ordered_list_start(list_block)
-
- for block in list_block.blocks:
- if block.type in [BlockType.LIST, BlockType.INDEX]:
- items.extend(_flatten_structured_list_items(block, root_ilevel))
- else:
- item_content = merge_para_with_structured_spans(block)
- if item_content:
- if attribute == "ordered":
- prefix = f"{' ' * relative_ilevel}{ordered_counter}."
- ordered_counter += 1
- else:
- prefix = f"{' ' * relative_ilevel}-"
- item = {
- "item_type": "text",
- "ilevel": relative_ilevel,
- "prefix": prefix,
- "item_content": item_content,
- }
- anchor = block.anchor
- if isinstance(anchor, str) and anchor.strip():
- item["anchor"] = anchor.strip()
- items.append(item)
-
- return items
-
-
-def merge_list_to_markdown(list_block: Block) -> str:
- """Recursively convert a nested list block to markdown text."""
- return "\n".join(_flatten_list_items(list_block)) + "\n"
-
-
-def _collect_index_span_items(text_block: Block) -> list[tuple[str, str, list[str]]]:
- """按原始顺序收集目录叶子节点中的 span 三元组。"""
- span_items = []
- for line in text_block.lines:
- for span in line.spans:
- span_items.append((span.content, span.type, span._style))
- return span_items
-
-
-def _normalize_anchor(block: Block) -> str | None:
- """规范化 block 锚点,空值返回 None。"""
- anchor = block.anchor
- if not isinstance(anchor, str) or not anchor.strip():
- return None
- return anchor.strip()
-
-
-def _looks_like_index_page_token(token: str) -> bool:
- """判断目录 tab 后缀是否像页码,避免误删正文内容。"""
- token = token.strip()
- if not token:
- return False
- if len(token) > 12:
- return False
- if re.search(r"[\u4e00-\u9fff]", token):
- return False
- if re.fullmatch(r"\d+", token):
- return True
- if re.fullmatch(r"[ivxlcdm]+", token.lower()):
- return True
- if re.fullmatch(r"[a-zA-Z]", token):
- return True
- return False
-
-
-def _strip_index_page_tail(span_items: list[tuple[str, str, list[str]]]) -> list[tuple[str, str, list[str]]]:
- """去掉目录叶子末尾 tab+页码,并把剩余 tab 转成普通空格。"""
- last_tab_span_idx = -1
- for i, (content, span_type, _) in enumerate(span_items):
- if span_type != ContentType.INLINE_EQUATION and "\t" in content:
- last_tab_span_idx = i
-
- should_strip_page_tail = False
- if last_tab_span_idx != -1:
- last_tab_content = span_items[last_tab_span_idx][0]
- tab_tail = last_tab_content.rsplit("\t", 1)[1]
- should_strip_page_tail = _looks_like_index_page_token(tab_tail)
-
- stripped_span_items = []
- for i, (content, span_type, span_style) in enumerate(span_items):
- if span_type != ContentType.INLINE_EQUATION:
- if i == last_tab_span_idx and should_strip_page_tail:
- content = content.rsplit("\t", 1)[0]
- content = content.replace("\t", " ")
- stripped_span_items.append((content, span_type, span_style))
- return stripped_span_items
-
-
-def _get_uniform_index_style(span_items: list[tuple[str, str, list[str]]]) -> list[str] | None:
- """如果目录叶子所有非公式 span 样式完全一致,则返回统一样式。"""
- non_eq_styles = [
- tuple(span_style)
- for content, span_type, span_style in span_items
- if content and span_type != ContentType.INLINE_EQUATION
- ]
- if not non_eq_styles:
- return None
- first_style = non_eq_styles[0]
- if first_style and all(style == first_style for style in non_eq_styles):
- return list(first_style)
- return None
-
-
-def _render_uniform_index_item(
- span_items: list[tuple[str, str, list[str]]], uniform_style: list[str], inline_syntax: str
-) -> str:
- """用统一样式渲染目录叶子,避免同样式片段产生碎片化 marker。"""
- raw_parts = []
- for content, span_type, _span_style in span_items:
- if not content:
- continue
- if span_type == ContentType.INLINE_EQUATION:
- raw_parts.append(f"{inline_left_delimiter}{content}{inline_right_delimiter}")
- else:
- raw_parts.append(_escape_office_inline_text(content, inline_syntax))
- item_text = "".join(raw_parts).strip()
- if not item_text:
- return ""
- return _apply_configured_style(item_text, uniform_style, inline_syntax)
-
-
-def _render_mixed_index_item(span_items: list[tuple[str, str, list[str]]], inline_syntax: str) -> str:
- """逐 span 渲染目录叶子,超链接 span 在目录中仅保留可见文本。"""
- rendered_parts = []
- for content, span_type, span_style in span_items:
- if not content:
- continue
- if span_type == ContentType.INLINE_EQUATION:
- rendered_parts.append(
- _make_rendered_part(
- span_type,
- f"{inline_left_delimiter}{content}{inline_right_delimiter}",
- )
- )
- elif span_type == ContentType.HYPERLINK:
- _append_hyperlink_part(
- rendered_parts,
- content,
- span_style,
- inline_syntax,
- plain_text_only=True,
- )
- else:
- _append_text_part(
- rendered_parts,
- content,
- span_style,
- inline_syntax,
- )
- return _join_rendered_parts(rendered_parts).strip()
-
-
-def _render_index_leaf_item(text_block: Block, indent: str) -> str | None:
- """渲染单个目录叶子节点,并在有锚点时挂载内部链接。"""
- inline_syntax = _select_block_inline_syntax(text_block)
- span_items = _collect_index_span_items(text_block)
- if not span_items:
- return None
-
- span_items = _strip_index_page_tail(span_items)
- uniform_style = _get_uniform_index_style(span_items)
- if uniform_style:
- item_text = _render_uniform_index_item(
- span_items,
- uniform_style,
- inline_syntax,
- )
- else:
- item_text = _render_mixed_index_item(span_items, inline_syntax)
- if not item_text:
- return None
-
- anchor = _normalize_anchor(text_block)
- if anchor is not None:
- item_text = _render_link(item_text, f"#{anchor}", inline_syntax)
- return f"{indent}- {item_text}"
-
-
-def _flatten_index_items(index_block: Block) -> list[str]:
- """递归展平目录 block,保留目录锚点和目录项样式。"""
- items = []
- ilevel = index_block.ilevel
- if ilevel is None:
- ilevel = 0
- indent = " " * ilevel
- for child in index_block.blocks:
- if child.type == BlockType.INDEX:
- items.extend(_flatten_index_items(child))
- elif child.type == BlockType.TEXT:
- item_text = _render_index_leaf_item(child, indent)
- if item_text:
- items.append(item_text)
- return items
-
-
-def merge_index_to_markdown(index_block: Block) -> str:
- """Convert a nested index (TOC) block to markdown with hyperlinks."""
- return "\n".join(_flatten_index_items(index_block)) + "\n"
-
-
-def _iter_child_blocks(para_block: Block, block_type: str) -> Generator[Block, None, None]:
- """按原始顺序遍历指定类型的子 block。"""
- for block in para_block.blocks:
- if block.type == block_type:
- yield block
-
-
-def _iter_block_spans(block: Block) -> Generator[Span, None, None]:
- """按原始顺序遍历 block 下所有 span。"""
- for line in block.lines:
- for span in line.spans:
- yield span
-
-
-def _iter_body_spans(para_block: Block, body_type: str, span_type: str) -> Generator[Span, None, None]:
- """遍历视觉类 block 的 body span,统一 image/table/chart 的查找方式。"""
- for block in _iter_child_blocks(para_block, body_type):
- for span in _iter_block_spans(block):
- if span.type == span_type:
- yield span
-
-
-def _collect_caption_texts(para_block: Block, caption_type: str) -> list[str]:
- """收集 legacy markdown/content_list 使用的 caption 文本。"""
- return [merge_para_with_text(block) for block in _iter_child_blocks(para_block, caption_type)]
-
-
-def _collect_structured_caption(para_block: Block, caption_type: str) -> list[dict[str, Any]]:
- """收集 structured_content 使用的结构化 caption spans。"""
- caption_content = []
- for block in _iter_child_blocks(para_block, caption_type):
- caption_content.extend(merge_para_with_structured_spans(block))
- return caption_content
-
-
-def blocks_to_markdown(
- para_blocks: list[Block],
- img_bucket_path: str = "",
- no_rich_content: bool = False,
- prefer_markdown_table: bool = False,
-) -> list[str]:
- page_markdown = []
- for para_block in para_blocks:
- para_text = ""
- para_type = para_block.type
- if para_type in [BlockType.TEXT, BlockType.EQUATION]:
- para_text = merge_para_with_text(para_block)
- if para_type == BlockType.TEXT:
- bookmark_anchor = para_block.anchor
- if isinstance(bookmark_anchor, str) and bookmark_anchor.strip() and bookmark_anchor.strip().startswith("_Toc"):
- para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{para_text}'
- elif para_type == BlockType.LIST:
- para_text = merge_list_to_markdown(para_block)
- elif para_type == BlockType.INDEX:
- para_text = merge_index_to_markdown(para_block)
- elif para_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- title_level = get_title_level(para_block)
- title_text = merge_para_with_text(para_block)
- bookmark_anchor = para_block.anchor
- if isinstance(bookmark_anchor, str) and bookmark_anchor.strip():
- para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{"#" * title_level} {title_text}'
- else:
- para_text = f"{'#' * title_level} {title_text}"
- elif para_type == BlockType.IMAGE:
- if no_rich_content:
- continue
- for span in _iter_body_spans(para_block, BlockType.IMAGE_BODY, ContentType.IMAGE):
- if span:
- para_text += f"![]({img_bucket_path}/{span.image_path})"
- for caption_text in _collect_caption_texts(para_block, BlockType.IMAGE_CAPTION):
- para_text += " \n" + caption_text
-
- elif para_type == BlockType.TABLE:
- if no_rich_content:
- continue
- for span in _iter_body_spans(para_block, BlockType.TABLE_BODY, ContentType.TABLE):
- table_html = _format_embedded_html(span.content, img_bucket_path)
- if prefer_markdown_table:
- para_text += f"\n{to_markdown_table(table_html)}\n"
- else:
- para_text += f"\n{table_html}\n"
- for caption_text in _collect_caption_texts(para_block, BlockType.TABLE_CAPTION):
- para_text += " \n" + caption_text
- elif para_type == BlockType.CHART:
- if no_rich_content:
- continue
- image_path, chart_content = get_body_data(para_block)
- if chart_content:
- para_text += f"\n{_format_embedded_html(chart_content, img_bucket_path)}\n"
- elif image_path:
- para_text += f"![]({_build_media_path(img_bucket_path, image_path)})"
- else:
- continue
- for caption_text in _collect_caption_texts(para_block, BlockType.CHART_CAPTION):
- para_text += " \n" + caption_text
-
- if para_text.strip() != "":
- page_markdown.append(para_text.strip("\r\n"))
-
- return page_markdown
-
-
-def make_blocks_to_content_list(para_block: Block, img_bucket_path: str, page_idx: int | None) -> dict[str, Any]:
- para_type = para_block.type
- para_content: dict[str, Any] = {}
- if para_type in [
- BlockType.TEXT,
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.PAGE_FOOTNOTE,
- ]:
- para_content = {
- "type": para_type,
- "text": merge_para_with_text(para_block),
- }
- elif para_type == BlockType.LIST:
- para_content = {
- "type": para_type,
- "list_items": _flatten_list_items(para_block),
- }
- elif para_type == BlockType.INDEX:
- para_content = {
- "type": para_type,
- "list_items": _flatten_index_items(para_block),
- }
- elif para_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- title_level = get_title_level(para_block)
- para_content = {
- "type": ContentType.TEXT,
- "text": merge_para_with_text(para_block),
- }
- if title_level != 0:
- para_content["text_level"] = title_level
- elif para_type == BlockType.EQUATION:
- para_content = {
- "type": ContentType.EQUATION,
- "text": merge_para_with_text(para_block),
- "text_format": "latex",
- }
- elif para_type == BlockType.IMAGE:
- para_content = {"type": ContentType.IMAGE, "img_path": "", BlockType.IMAGE_CAPTION: []}
- for span in _iter_body_spans(
- para_block,
- BlockType.IMAGE_BODY,
- ContentType.IMAGE,
- ):
- if span.image_path:
- para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"
- para_content[BlockType.IMAGE_CAPTION].extend(_collect_caption_texts(para_block, BlockType.IMAGE_CAPTION))
- elif para_type == BlockType.TABLE:
- para_content = {"type": ContentType.TABLE, BlockType.TABLE_CAPTION: []}
- for span in _iter_body_spans(
- para_block,
- BlockType.TABLE_BODY,
- ContentType.TABLE,
- ):
- 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 = {
- "type": ContentType.CHART,
- "img_path": "",
- "content": "",
- BlockType.CHART_CAPTION: [],
- }
- for span in _iter_body_spans(para_block, BlockType.CHART_BODY, ContentType.CHART):
- para_content["img_path"] = _build_media_path(img_bucket_path, span.image_path)
- if span.content:
- para_content["content"] = _format_embedded_html(span.content, img_bucket_path)
- para_content[BlockType.CHART_CAPTION].extend(_collect_caption_texts(para_block, BlockType.CHART_CAPTION))
-
- para_content["page_idx"] = page_idx
- anchor = para_block.anchor
- if isinstance(anchor, str) and anchor.strip():
- para_content["anchor"] = anchor.strip()
-
- return para_content
-
-
-def block_to_structured_content(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
- """将 Office middle_json Block 转换为 structured_content 单项。"""
- para_type = para_block.type
- para_content: dict[str, Any] = {}
- if para_type in [
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.PAGE_FOOTNOTE,
- ]:
- if para_type == BlockType.HEADER:
- content_type = ContentTypeV2.PAGE_HEADER
- elif para_type == BlockType.FOOTER:
- content_type = ContentTypeV2.PAGE_FOOTER
- elif para_type == BlockType.PAGE_FOOTNOTE:
- content_type = ContentTypeV2.PAGE_FOOTNOTE
- else:
- raise ValueError(f"Unknown para_type: {para_type}")
- para_content = {
- "type": content_type,
- "content": {
- f"{content_type}_content": merge_para_with_structured_spans(para_block),
- },
- }
- elif para_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- title_level = get_title_level(para_block)
- if title_level != 0:
- para_content = {
- "type": ContentTypeV2.TITLE,
- "content": {"title_content": merge_para_with_structured_spans(para_block), "level": title_level},
- }
- else:
- para_content = {
- "type": ContentTypeV2.PARAGRAPH,
- "content": {
- "paragraph_content": merge_para_with_structured_spans(para_block),
- },
- }
- elif para_type in [
- BlockType.TEXT,
- ]:
- para_content = {
- "type": ContentTypeV2.PARAGRAPH,
- "content": {
- "paragraph_content": merge_para_with_structured_spans(para_block),
- },
- }
- elif para_type == BlockType.EQUATION:
- _, math_content = get_body_data(para_block)
- para_content = {
- "type": ContentTypeV2.EQUATION_INTERLINE,
- "content": {
- "math_content": math_content,
- "math_type": "latex",
- },
- }
- elif para_type == BlockType.IMAGE:
- image_path, _ = get_body_data(para_block)
- image_source = {
- "path": f"{img_bucket_path}/{image_path}",
- }
- para_content = {
- "type": ContentTypeV2.IMAGE,
- "content": {
- "image_source": image_source,
- "image_caption": _collect_structured_caption(
- para_block,
- BlockType.IMAGE_CAPTION,
- ),
- },
- }
- elif para_type == BlockType.TABLE:
- _, html = get_body_data(para_block)
- if html.count("<table") > 1:
- table_nest_level = 2
- else:
- table_nest_level = 1
- if "colspan" in html or "rowspan" in html or table_nest_level > 1:
- table_type = ContentTypeV2.TABLE_COMPLEX
- else:
- table_type = ContentTypeV2.TABLE_SIMPLE
-
- para_content = {
- "type": ContentTypeV2.TABLE,
- "content": {
- "table_caption": _collect_structured_caption(
- para_block,
- BlockType.TABLE_CAPTION,
- ),
- "html": _format_embedded_html(html, img_bucket_path),
- "table_type": table_type,
- "table_nest_level": table_nest_level,
- },
- }
- elif para_type == BlockType.CHART:
- image_path, chart_content = get_body_data(para_block)
- para_content = {
- "type": ContentTypeV2.CHART,
- "content": {
- "image_source": {
- "path": _build_media_path(img_bucket_path, image_path),
- },
- "content": _format_embedded_html(chart_content, img_bucket_path),
- "chart_caption": _collect_structured_caption(
- para_block,
- BlockType.CHART_CAPTION,
- ),
- },
- }
- elif para_type == BlockType.LIST:
- list_type = ContentTypeV2.LIST_TEXT
- attribute = para_block._list_attribute or "unordered"
- para_content = {
- "type": ContentTypeV2.LIST,
- "content": {
- "list_type": list_type,
- "attribute": attribute,
- "list_items": _flatten_structured_list_items(para_block),
- },
- }
- elif para_type == BlockType.INDEX:
- para_content = {
- "type": ContentTypeV2.INDEX,
- "content": {
- "list_type": ContentTypeV2.LIST_TEXT,
- "list_items": _flatten_structured_list_items(para_block),
- },
- }
-
- anchor = para_block.anchor
- if isinstance(anchor, str) and anchor.strip():
- para_content["anchor"] = anchor.strip()
-
- return para_content
-
-
-def get_body_data(para_block: Block) -> tuple[str, str]:
- """
- Extract image_path and body content from para_block
- Returns:
- - For IMAGE/EQUATION: (image_path, '')
- - For TABLE: (image_path, html)
- - For CHART: (image_path, content)
- - Default: ('', '')
- """
-
- def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
- for line in lines:
- for span in line.spans:
- span_type = span.type
- if span_type == ContentType.TABLE:
- return span.image_path, span.content
- elif span_type == ContentType.CHART:
- return span.image_path, span.content
- elif span_type == ContentType.IMAGE:
- return span.image_path, ""
- elif span_type == ContentType.INTERLINE_EQUATION:
- return span.image_path, span.content
- elif span_type == ContentType.TEXT:
- return "", span.content
- return "", ""
-
- # 处理嵌套的 blocks 结构
- if para_block.blocks:
- for block in para_block.blocks:
- block_type = block.type
- if block_type in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY, BlockType.CODE_BODY]:
- result = get_data_from_spans(block.lines)
- if result != ("", ""):
- return result
- if block_type == BlockType.CHART_BODY:
- return result
- return "", ""
-
- # 处理直接包含 lines 的结构
- return get_data_from_spans(para_block.lines)
-
-
-def _span_has_structured_content(span: Span, visible_styles: set[str]) -> bool:
- """判断 structured span 是否应保留,支持 hyperlink children 的可见空白样式。"""
- content = span.content
- span_style = span._style
- if content.strip():
- return True
- if content and span_style and any(s in visible_styles for s in span_style):
- return True
- for child in span._children:
- child_content = child.content
- child_style = child._style
- if child_content.strip():
- return True
- if child_content and child_style and any(s in visible_styles for s in child_style):
- return True
- return False
-
-
-def _render_structured_span(span: Span) -> dict[str, Any]:
- """显式渲染 Office structured 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_structured_span(child) for child in span._children]
- return rendered_span
-
-
-def merge_para_with_structured_spans(para_block: Block) -> list[dict[str, Any]]:
- """将 Office 段落转换为 structured_content spans,避免原地修改 middle_json。"""
- _visible_styles = {"underline", "strikethrough"}
- para_content: list[dict[str, Any]] = []
- if para_block.type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- section_number = para_block.section_number
- if section_number:
- # structured_content 保持结构化 spans,同时补上 middle_json 已生成的自动标题编号。
- para_content.append(
- {
- "type": ContentTypeV2.SPAN_TEXT,
- "content": f"{section_number} ",
- }
- )
- for line in para_block.lines:
- for span in line.spans:
- if _span_has_structured_content(span, _visible_styles):
- para_content.append(_render_structured_span(span))
- return para_content
diff --git a/mineru/render/structured_content.py b/mineru/render/structured_content.py
deleted file mode 100644
index 825da4f6..00000000
--- a/mineru/render/structured_content.py
+++ /dev/null
@@ -1,531 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from typing import Any
-
-from ..backend.utils.char_utils import CJK_LANGS, resolve_text_line_boundary
-from ..backend.utils.raw_block_types import RAW_ALGORITHM, RAW_PHONETIC
-from ..types import BBox, Block, BlockType, ContentType, ContentTypeV2, IntBBox, Line
-from ..utils.language import detect_lang
-from .markdown import _get_title_level
-from .merge import (
- _collect_text_for_lang_detection,
- _next_line_starts_with_lowercase_text,
- _normalize_text_content,
-)
-from .merge_visual import _build_media_path, _format_embedded_html, _normalize_visual_content
-
-
-def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list[Block]:
- """将连续参考文献块合并为临时父块,统一 content_list 与 structured_content 的列表输出。"""
- merged_blocks: list[Block] = []
- ref_group: list[Block] = []
-
- def flush_ref_group() -> None:
- """把当前连续 ref_text 分组写入结果,单个块保持原样避免无意义包装。"""
- nonlocal ref_group
- if not ref_group:
- return
- if len(ref_group) == 1:
- merged_blocks.append(ref_group[0])
- else:
- merged_blocks.append(
- Block(
- index=ref_group[0].index,
- type=BlockType.REF_TEXT,
- bbox=ref_group[0].bbox,
- blocks=list(ref_group),
- )
- )
- ref_group = []
-
- for para_block in para_blocks or []:
- if para_block.type == BlockType.REF_TEXT:
- ref_group.append(para_block)
- continue
-
- flush_ref_group()
- merged_blocks.append(para_block)
-
- flush_ref_group()
- return merged_blocks
-
-
-def block_to_structured_content(
- para_block: Block,
- img_bucket_path: str,
- page_size: tuple[int, int] | list[int] | None,
-) -> dict[str, Any] | None:
- """将 PDF middle_json Block 转换为 structured_content 单项。"""
- para_type = para_block.type
- para_content: dict[str, Any] | None = None
-
- if para_type in [
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.ASIDE_TEXT,
- BlockType.PAGE_NUMBER,
- BlockType.PAGE_FOOTNOTE,
- ]:
- content_type = _page_content_type(para_type)
- para_content = {
- "type": content_type,
- "content": {
- f"{content_type}_content": merge_para_with_structured_spans(para_block),
- },
- }
- elif para_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
- title_level = _get_title_level(para_block)
- if title_level != 0:
- para_content = {
- "type": ContentTypeV2.TITLE,
- "content": {
- "title_content": merge_para_with_structured_spans(para_block),
- "level": title_level,
- },
- }
- else:
- para_content = _paragraph_content(para_block)
- elif para_type in [BlockType.TEXT, RAW_PHONETIC]:
- para_content = _paragraph_content(para_block)
- elif para_type == BlockType.EQUATION:
- image_path, math_content = _get_body_data(para_block)
- para_content = {
- "type": ContentTypeV2.EQUATION_INTERLINE,
- "content": {
- "math_content": math_content,
- "math_type": "latex",
- "image_source": {"path": _build_media_path(img_bucket_path, image_path)},
- },
- }
- elif para_type == BlockType.IMAGE:
- para_content = _image_content(para_block, img_bucket_path)
- elif para_type == BlockType.TABLE:
- para_content = _table_content(para_block, img_bucket_path)
- elif para_type == BlockType.CHART:
- para_content = _chart_content(para_block, img_bucket_path)
- elif para_type == BlockType.CODE:
- para_content = _code_content(para_block)
- elif para_type == BlockType.REF_TEXT:
- para_content = _ref_text_content(para_block)
- elif para_type == BlockType.LIST:
- para_content = _list_content(para_block)
- elif para_type == BlockType.INDEX:
- para_content = _index_content(para_block)
-
- if not para_content:
- return None
-
- bbox = _build_bbox(para_block.bbox, page_size)
- if bbox:
- para_content["bbox"] = bbox
- return para_content
-
-
-def merge_para_with_structured_spans(para_block: Block) -> list[dict[str, Any]]:
- """将段落文本和行内公式转换为 structured_content span,且不修改原始 span。"""
- block_lang = detect_lang(_collect_text_for_lang_detection(para_block))
- para_content: list[dict[str, Any]] = []
- para_type = para_block.type
-
- for line_idx, line in enumerate(para_block.lines):
- for span_idx, span in enumerate(line.spans):
- span_type = span.type
-
- if span_type == ContentType.TEXT:
- content = _normalize_text_content(span.content)
- if not content.strip():
- continue
-
- output_type = ContentTypeV2.SPAN_PHONETIC if para_type == RAW_PHONETIC else ContentTypeV2.SPAN_TEXT
- rendered_content = _render_text_span_content(
- para_block,
- block_lang,
- line,
- line_idx,
- span_idx,
- content,
- )
- if para_content and para_content[-1]["type"] == output_type:
- para_content[-1]["content"] += rendered_content
- else:
- para_content.append(
- {
- "type": output_type,
- "content": rendered_content,
- }
- )
- elif span_type == ContentType.INLINE_EQUATION:
- content = span.content.strip()
- if content:
- para_content.append(
- {
- "type": ContentTypeV2.SPAN_EQUATION_INLINE,
- "content": content,
- }
- )
-
- if para_content and para_content[-1]["type"] in [
- ContentTypeV2.SPAN_TEXT,
- ContentTypeV2.SPAN_PHONETIC,
- ]:
- para_content[-1]["content"] = para_content[-1]["content"].rstrip()
-
- return para_content
-
-
-def _page_content_type(para_type: str) -> str:
- """将页面附属块类型映射到 structured_content 顶层类型。"""
- if para_type == BlockType.HEADER:
- return ContentTypeV2.PAGE_HEADER
- if para_type == BlockType.FOOTER:
- return ContentTypeV2.PAGE_FOOTER
- if para_type == BlockType.ASIDE_TEXT:
- return ContentTypeV2.PAGE_ASIDE_TEXT
- if para_type == BlockType.PAGE_NUMBER:
- return ContentTypeV2.PAGE_NUMBER
- if para_type == BlockType.PAGE_FOOTNOTE:
- return ContentTypeV2.PAGE_FOOTNOTE
- raise ValueError(f"Unknown para_type: {para_type}")
-
-
-def _paragraph_content(para_block: Block) -> dict[str, Any]:
- """构造普通段落 structured_content 项。"""
- return {
- "type": ContentTypeV2.PARAGRAPH,
- "content": {
- "paragraph_content": merge_para_with_structured_spans(para_block),
- },
- }
-
-
-def _image_content(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
- """构造图片 structured_content 项,保留 caption、footnote、sub_type 与视觉文本。"""
- image_caption: list[dict[str, Any]] = []
- image_footnote: list[dict[str, Any]] = []
- image_path, image_content = _get_body_data(para_block)
- for block in para_block.blocks:
- if block.type == BlockType.IMAGE_CAPTION:
- image_caption.extend(merge_para_with_structured_spans(block))
- if block.type == BlockType.IMAGE_FOOTNOTE:
- image_footnote.extend(merge_para_with_structured_spans(block))
- para_content: dict[str, Any] = {
- "type": ContentTypeV2.IMAGE,
- "content": {
- "image_source": {"path": _build_media_path(img_bucket_path, image_path)},
- "image_caption": image_caption,
- "image_footnote": image_footnote,
- },
- }
- if image_content or para_block.sub_type:
- para_content["content"]["content"] = image_content
- _apply_visual_sub_type(para_content, para_block)
- return para_content
-
-
-def _table_content(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
- """构造表格 structured_content 项,并计算简单/复杂表格标记。"""
- table_caption: list[dict[str, Any]] = []
- table_footnote: list[dict[str, Any]] = []
- image_path, html = _get_body_data(para_block)
- table_html = _format_embedded_html(html, img_bucket_path)
- table_nest_level = 2 if table_html.count("<table") > 1 else 1
- if "colspan" in table_html or "rowspan" in table_html or table_nest_level > 1:
- table_type = ContentTypeV2.TABLE_COMPLEX
- else:
- table_type = ContentTypeV2.TABLE_SIMPLE
- for block in para_block.blocks:
- if block.type == BlockType.TABLE_CAPTION:
- table_caption.extend(merge_para_with_structured_spans(block))
- if block.type == BlockType.TABLE_FOOTNOTE:
- table_footnote.extend(merge_para_with_structured_spans(block))
- return {
- "type": ContentTypeV2.TABLE,
- "content": {
- "image_source": {"path": _build_media_path(img_bucket_path, image_path)},
- "table_caption": table_caption,
- "table_footnote": table_footnote,
- "html": table_html,
- "table_type": table_type,
- "table_nest_level": table_nest_level,
- },
- }
-
-
-def _chart_content(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
- """构造图表 structured_content 项,兼容仅有截图或仅有 HTML 内容的情况。"""
- chart_caption: list[dict[str, Any]] = []
- chart_footnote: list[dict[str, Any]] = []
- image_path, chart_content = _get_body_data(para_block)
- for block in para_block.blocks:
- if block.type == BlockType.CHART_CAPTION:
- chart_caption.extend(merge_para_with_structured_spans(block))
- if block.type == BlockType.CHART_FOOTNOTE:
- chart_footnote.extend(merge_para_with_structured_spans(block))
- para_content = {
- "type": ContentTypeV2.CHART,
- "content": {
- "image_source": {
- "path": _build_media_path(img_bucket_path, image_path),
- },
- "content": chart_content if chart_content else "",
- "chart_caption": chart_caption,
- "chart_footnote": chart_footnote,
- },
- }
- _apply_visual_sub_type(para_content, para_block)
- return para_content
-
-
-def _code_content(para_block: Block) -> dict[str, Any]:
- """构造代码或算法 structured_content 项,统一保留 caption 与 footnote。"""
- code_caption: list[dict[str, Any]] = []
- code_footnote: list[dict[str, Any]] = []
- code_content: list[dict[str, Any]] = []
- for block in para_block.blocks:
- if block.type == BlockType.CODE_CAPTION:
- code_caption.extend(merge_para_with_structured_spans(block))
- if block.type == BlockType.CODE_FOOTNOTE:
- code_footnote.extend(merge_para_with_structured_spans(block))
- if block.type == BlockType.CODE_BODY:
- code_content = merge_para_with_structured_spans(block)
-
- sub_type = para_block.sub_type
- if sub_type == BlockType.CODE:
- return {
- "type": ContentTypeV2.CODE,
- "content": {
- "code_caption": code_caption,
- "code_content": code_content,
- "code_footnote": code_footnote,
- "code_language": para_block.guess_lang or "txt",
- },
- }
- if sub_type == RAW_ALGORITHM:
- return {
- "type": ContentTypeV2.ALGORITHM,
- "content": {
- "algorithm_caption": code_caption,
- "algorithm_content": code_content,
- "algorithm_footnote": code_footnote,
- },
- }
- raise ValueError(f"Unknown code sub_type: {sub_type}")
-
-
-def _ref_text_content(para_block: Block) -> dict[str, Any]:
- """构造参考文献列表项,支持已经合并的临时父 ref_text 块。"""
- list_items: list[dict[str, Any]] = []
- for block in _get_ref_text_item_blocks(para_block):
- item_content = merge_para_with_structured_spans(block)
- if item_content:
- list_items.append(
- {
- "item_type": "text",
- "item_content": item_content,
- }
- )
- return {
- "type": ContentTypeV2.LIST,
- "content": {
- "list_type": ContentTypeV2.LIST_REF,
- "list_items": list_items,
- },
- }
-
-
-def _list_content(para_block: Block) -> dict[str, Any]:
- """构造普通列表 structured_content 项,兼容子 block 列表和按行拆分列表。"""
- if para_block.sub_type:
- if para_block.sub_type == BlockType.REF_TEXT:
- list_type = ContentTypeV2.LIST_REF
- elif para_block.sub_type == BlockType.TEXT:
- list_type = ContentTypeV2.LIST_TEXT
- else:
- raise ValueError(f"Unknown list sub_type: {para_block.sub_type}")
- else:
- list_type = ContentTypeV2.LIST_TEXT
-
- list_items = _block_list_items(para_block)
- content: dict[str, Any] = {
- "list_type": list_type,
- "list_items": list_items,
- }
- if list_type == ContentTypeV2.LIST_TEXT:
- content["attribute"] = para_block._list_attribute or "unordered"
- return {
- "type": ContentTypeV2.LIST,
- "content": content,
- }
-
-
-def _index_content(para_block: Block) -> dict[str, Any]:
- """构造目录索引 structured_content 项。"""
- return {
- "type": ContentTypeV2.INDEX,
- "content": {
- "list_type": ContentTypeV2.LIST_TEXT,
- "list_items": _block_list_items(para_block),
- },
- }
-
-
-def _block_list_items(para_block: Block) -> list[dict[str, Any]]:
- """将列表容器中的子块或行拆分为 structured_content list_items。"""
- item_blocks = para_block.blocks if para_block.blocks else _split_list_item_blocks(para_block)
- list_items: list[dict[str, Any]] = []
- for block in item_blocks:
- item_content = merge_para_with_structured_spans(block)
- if item_content:
- list_items.append(
- {
- "item_type": "text",
- "item_content": item_content,
- }
- )
- return list_items
-
-
-def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:
- """将视觉块 sub_type 透传到 structured_content 顶层。"""
- sub_type = para_block.sub_type
- if sub_type:
- para_content["sub_type"] = sub_type
-
-
-def _build_bbox(para_bbox: BBox, page_size: tuple[int, int] | list[int] | None) -> IntBBox | None:
- """按千分位归一化 bbox,缺少页面尺寸时跳过 bbox 输出。"""
- if not para_bbox or not page_size:
- return None
- page_width, page_height = page_size
- if not page_width or not page_height:
- return None
- x0, y0, x1, y1 = para_bbox
- return [
- int(x0 * 1000 / page_width),
- int(y0 * 1000 / page_height),
- int(x1 * 1000 / page_width),
- int(y1 * 1000 / page_height),
- ]
-
-
-def _get_ref_text_item_blocks(para_block: Block) -> list[Block]:
- """返回参考文献列表项块,未合并时使用当前块作为单项。"""
- return para_block.blocks or [para_block]
-
-
-def _split_list_item_blocks(para_block: Block) -> list[Block]:
- """按 line._is_list_start 将单个列表块拆成临时列表项块。"""
- item_blocks = []
- current_lines = []
-
- for line_idx, line in enumerate(para_block.lines):
- if line_idx > 0 and line._is_list_start and current_lines:
- item_blocks.append(
- Block(
- index=para_block.index,
- type=BlockType.TEXT,
- bbox=para_block.bbox,
- lines=current_lines,
- )
- )
- current_lines = []
- current_lines.append(line)
-
- if current_lines:
- item_blocks.append(
- Block(
- index=para_block.index,
- type=BlockType.TEXT,
- bbox=para_block.bbox,
- lines=current_lines,
- )
- )
-
- return item_blocks
-
-
-def _get_body_data(para_block: Block) -> tuple[str, str]:
- """从视觉类 block 中提取图片路径和主体内容。"""
-
- def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
- """按 span 顺序读取第一个可渲染的视觉或文本载荷。"""
- for line in lines:
- for span in line.spans:
- span_type = span.type
- if span_type == ContentType.TABLE:
- return span.image_path, span.content
- if span_type == ContentType.CHART:
- return span.image_path, span.content
- if span_type == ContentType.IMAGE:
- return span.image_path, _normalize_visual_content(span.content)
- if span_type == ContentType.INTERLINE_EQUATION:
- return span.image_path, span.content
- if span_type == ContentType.TEXT:
- return "", span.content
- return "", ""
-
- if para_block.blocks:
- for block in para_block.blocks:
- block_type = block.type
- if block_type in [
- BlockType.IMAGE_BODY,
- BlockType.TABLE_BODY,
- BlockType.CHART_BODY,
- BlockType.CODE_BODY,
- ]:
- result = get_data_from_spans(block.lines)
- if result != ("", "") or block_type == BlockType.CHART_BODY:
- return result
- return "", ""
-
- return get_data_from_spans(para_block.lines)
-
-
-def _has_following_joinable_span(para_block: Block, line_idx: int, span_idx: int) -> bool:
- """判断当前 span 后面是否还有可拼接内容,避免多余尾随空格。"""
- for next_line_idx in range(line_idx, len(para_block.lines)):
- next_line = para_block.lines[next_line_idx]
- start_span_idx = span_idx + 1 if next_line_idx == line_idx else 0
- for next_span in next_line.spans[start_span_idx:]:
- next_span_type = next_span.type
- if next_span_type == ContentType.TEXT:
- if _normalize_text_content(next_span.content).strip():
- return True
- elif next_span_type == ContentType.INLINE_EQUATION:
- if str(next_span.content).strip():
- return True
- return False
-
-
-def _render_text_span_content(
- para_block: Block,
- block_lang: str,
- line: Line,
- line_idx: int,
- span_idx: int,
- content: str,
-) -> str:
- """按语言和跨行断词规则渲染 structured_content 文本 span 内容。"""
- is_last_span = span_idx == len(line.spans) - 1
- has_following_joinable_span = _has_following_joinable_span(para_block, line_idx, span_idx)
-
- # 物理行末文本与 Markdown/Hybrid 共用同一套空格和断词规则。
- if is_last_span:
- processed_content, separator = resolve_text_line_boundary(
- content,
- block_language=block_lang,
- next_starts_with_lowercase=_next_line_starts_with_lowercase_text(para_block, line_idx),
- )
- if has_following_joinable_span:
- return f"{processed_content}{separator}"
- return processed_content
-
- if block_lang in CJK_LANGS:
- if has_following_joinable_span and not is_last_span:
- return f"{content} "
- return content
-
- if has_following_joinable_span:
- return f"{content} "
- return content
diff --git a/mineru/render/union_make.py b/mineru/render/union_make.py
deleted file mode 100644
index 2f1e24f8..00000000
--- a/mineru/render/union_make.py
+++ /dev/null
@@ -1,159 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from typing import Any, Literal
-
-from ..types import PageInfo
-from .markdown import blocks_to_markdown
-from .office.output import blocks_to_markdown as office_blocks_to_markdown
-from .structured_content import block_to_structured_content, merge_adjacent_ref_text_blocks_for_content
-
-Backend = Literal["hybrid", "office"]
-
-
-def _backend_from_pages(pages: list[PageInfo]) -> Backend | None:
- """Infer backend from the first page. Returns ``None`` for empty input."""
- return pages[0]._backend if pages else None
-
-
-# ------------------------------------------------------------------ #
-# Per-backend dispatch helpers for Content-List modes
-# (Markdown rendering moved to ``render/markdown.py``).
-# ------------------------------------------------------------------ #
-
-
-def _dispatch_make_content_list(
- backend: Backend,
- para_block: Any,
- img_bucket_path: str,
- page_idx: int,
- page_size: Any,
-) -> Any:
- if backend == "office":
- from .office.output import make_blocks_to_content_list
-
- return make_blocks_to_content_list(para_block, img_bucket_path, page_idx)
-
- from .content_list import block_to_content_list
-
- item = block_to_content_list(para_block, img_bucket_path, page_idx, page_size)
- if item is None:
- return None
- return item.to_dict(skip_defaults=True)
-
-
-def _dispatch_block_to_structured_content(
- backend: Backend,
- para_block: Any,
- img_bucket_path: str,
- page_size: Any,
-) -> Any:
- if backend == "office":
- from .office.output import block_to_structured_content as office_block_to_structured_content
-
- return office_block_to_structured_content(para_block, img_bucket_path)
-
- return block_to_structured_content(para_block, img_bucket_path, page_size)
-
-
-def _get_merged_para_blocks(paras_of_layout: list, paras_of_discarded: list, backend: Backend) -> list:
- """Build the para-block list for Content-List modes.
-
- PDF backends merge adjacent ``ref_text`` blocks before rendering so both
- legacy content_list and structured_content expose references as a list.
- """
- if backend != "office":
- return merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))
- return (paras_of_layout or []) + (paras_of_discarded or [])
-
-
-# ------------------------------------------------------------------ #
-# Public renderer functions
-# ------------------------------------------------------------------ #
-
-
-def render_markdown(
- pdf_info: list[PageInfo],
- img_bucket_path: str = "",
- *,
- formula_enable: bool = True, # TODO
- table_enable: bool = True, # TODO
- prefer_markdown_table: bool = False,
- no_rich_content: bool = False,
- add_markers: bool = False,
-) -> str:
- """Render pages to a single Markdown string.
-
- If *add_markers* is True, each page is prefixed with ``<!-- page N of M -->``.
- """
- backend = _backend_from_pages(pdf_info)
- total = len(pdf_info)
- output_md: list[str] = []
- if backend == "office":
- for page_info in pdf_info:
- page_md = office_blocks_to_markdown(
- para_blocks=page_info.para_blocks,
- img_bucket_path=img_bucket_path,
- no_rich_content=no_rich_content,
- prefer_markdown_table=prefer_markdown_table,
- )
- if add_markers:
- page_num = page_info.page_idx + 1
- output_md.append(f"<!-- page {page_num} of {total} -->")
- output_md.extend(page_md)
- else: # PDF
- for page_info in pdf_info:
- page_md = blocks_to_markdown(
- para_blocks=page_info.para_blocks,
- img_bucket_path=img_bucket_path,
- table_as_image=not table_enable,
- formula_as_image=not formula_enable,
- no_rich_content=no_rich_content,
- prefer_markdown_table=prefer_markdown_table,
- )
- if add_markers:
- page_num = page_info.page_idx + 1
- output_md.append(f"<!-- page {page_num} of {total} -->")
- output_md.extend(page_md)
- return "\n\n".join(output_md)
-
-
-def render_content_list(
- pdf_info: list[PageInfo],
- img_bucket_path: str = "",
-) -> list[dict[str, Any]]:
- """Render pages to a flat Content List (V1)."""
- backend = _backend_from_pages(pdf_info)
- if backend is None:
- return []
- output_items: list[dict[str, Any]] = []
- for page_info in pdf_info:
- para_blocks = _get_merged_para_blocks(page_info.para_blocks, page_info.discarded_blocks, backend)
- if not para_blocks:
- continue
- for para_block in para_blocks:
- item = _dispatch_make_content_list(backend, para_block, img_bucket_path, page_info.page_idx, page_info.page_size)
- if item:
- output_items.append(item)
- return output_items
-
-
-def render_structured_content(
- pdf_info: list[PageInfo],
- img_bucket_path: str = "",
-) -> list[list[dict[str, Any]]]:
- """Render pages to per-page Structured Content."""
- backend = _backend_from_pages(pdf_info)
- if backend is None:
- return []
- output_lists: list[list[dict[str, Any]]] = []
- for page_info in pdf_info:
- para_blocks = _get_merged_para_blocks(page_info.para_blocks, page_info.discarded_blocks, backend)
- page_contents: list[dict[str, Any]] = []
- if para_blocks:
- for para_block in para_blocks:
- item = _dispatch_block_to_structured_content(backend, para_block, img_bucket_path, page_info.page_size)
- if item:
- page_contents.append(item)
- output_lists.append(page_contents)
- return output_lists
diff --git a/mineru/render/utils/__init__.py b/mineru/render/utils/__init__.py
new file mode 100644
index 00000000..f64ba567
--- /dev/null
+++ b/mineru/render/utils/__init__.py
@@ -0,0 +1 @@
+# Copyright (c) Opendatalab. All rights reserved.
\ No newline at end of file
diff --git a/mineru/backend/utils/markdown_utils.py b/mineru/render/utils/markdown_utils.py
similarity index 100%
rename from mineru/backend/utils/markdown_utils.py
rename to mineru/render/utils/markdown_utils.py
diff --git a/mineru/render/writer.py b/mineru/render/writer.py
deleted file mode 100644
index 01c24385..00000000
--- a/mineru/render/writer.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import os
-from abc import ABC, abstractmethod
-
-
-class DataWriter(ABC):
- @abstractmethod
- def write(self, path: str, data: bytes) -> None:
- """Write the data to the file.
-
- Args:
- path (str): the target file where to write
- data (bytes): the data want to write
- """
- pass
-
- def write_string(self, path: str, data: str) -> None:
- """Write the data to file, the data will be encoded to bytes.
-
- Args:
- path (str): the target file where to write
- data (str): the data want to write
- """
-
- def safe_encode(data: str, method: str):
- try:
- bit_data = data.encode(encoding=method, errors="replace")
- return bit_data, True
- except: # noqa
- return None, False
-
- for method in ["utf-8", "ascii"]:
- bit_data, flag = safe_encode(data, method)
- if flag:
- self.write(path, bit_data)
- break
-
-
-class FileBasedDataWriter(DataWriter):
- def __init__(self, parent_dir: str = "") -> None:
- """Initialized with parent_dir.
-
- Args:
- parent_dir (str, optional): the parent directory that may be used within methods. Defaults to ''.
- """
- self._parent_dir = parent_dir
-
- def write(self, path: str, data: bytes) -> None:
- """Write file with data.
-
- Args:
- path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
- data (bytes): the data want to write
- """
- fn_path = path
- if not os.path.isabs(fn_path) and len(self._parent_dir) > 0:
- fn_path = os.path.join(self._parent_dir, path)
-
- if not os.path.exists(os.path.dirname(fn_path)) and os.path.dirname(fn_path) != "":
- os.makedirs(os.path.dirname(fn_path), exist_ok=True)
-
- with open(fn_path, "wb") as f:
- f.write(data)
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index 42bb54cd..1ced73cd 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -10,7 +10,7 @@ import pytest
from PIL import Image, ImageDraw
from mineru.backend import analyze
-from mineru.backend.utils.raw_block_types import RAW_CAPTION, RAW_FOOTNOTE, RAW_PHONETIC
+from mineru.backend.utils.raw_block_types import RAW_ALGORITHM, RAW_CAPTION, RAW_FOOTNOTE, RAW_PHONETIC
from mineru.types import BlockType, MiddleJson
@@ -597,6 +597,100 @@ def test_normalize_pdf_model_list_updates_in_place() -> None:
)
+ "block_type",
+ [
+ BlockType.TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.ASIDE_TEXT,
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.PAGE_FOOTNOTE,
+ BlockType.REF_TEXT,
+ BlockType.LIST,
+ BlockType.INDEX,
+ RAW_CAPTION,
+ RAW_FOOTNOTE,
+ RAW_PHONETIC,
+ ],
+)
+def test_normalize_pdf_model_list_converts_full_width_alphanumeric_for_textual_blocks(
+ block_type: str,
+) -> None:
+ """验证 PDF 自然语言块统一转换全角字母和数字,同时保留全角标点。"""
+ model_list = [[{
+ "type": block_type,
+ "content": "Az0,。!?()",
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
+ }]]
+
+ analyze._normalize_pdf_model_list(model_list)
+
+ assert model_list[0][0]["content"] == "Az0,。!?()"
+ expected_type = BlockType.TEXT if block_type == RAW_PHONETIC else block_type
+ assert model_list[0][0]["type"] == expected_type
+
+
+def test_normalize_pdf_model_list_preserves_inline_formulas_during_full_width_cleanup() -> None:
+ """验证两种行内公式片段不参与全角转换,普通正文仍正常清洗。"""
+ model_list = [[{
+ "type": BlockType.TEXT,
+ "content": "前A1 \\(F2+x\\) 中B3 <eq>C4+y</eq> 后D5",
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
+ }]]
+
+ analyze._normalize_pdf_model_list(model_list)
+
+ assert model_list[0][0]["content"] == "前A1 <eq>F2+x</eq> 中B3 <eq>C4+y</eq> 后D5"
+
+
+ ("content", "expected"),
+ [
+ ("前A1 \\(F2 后B3", "前A1 \\(F2 后B3"),
+ ("前A1 <eq>F2 后B3", "前A1 <eq>F2 后B3"),
+ ],
+)
+def test_normalize_pdf_model_list_preserves_content_after_unclosed_inline_formula(
+ content: str,
+ expected: str,
+) -> None:
+ """验证未闭合公式从起始符到文本末尾均保持原样,避免误清洗公式内容。"""
+ model_list = [[{
+ "type": BlockType.TEXT,
+ "content": content,
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
+ }]]
+
+ analyze._normalize_pdf_model_list(model_list)
+
+ assert model_list[0][0]["content"] == expected
+
+
+ "block_type",
+ [
+ BlockType.TABLE,
+ BlockType.CODE,
+ RAW_ALGORITHM,
+ BlockType.EQUATION,
+ BlockType.FORMULA_NUMBER,
+ BlockType.IMAGE,
+ BlockType.CHART,
+ "unknown",
+ ],
+)
+def test_normalize_pdf_model_list_skips_non_natural_language_content(block_type: str) -> None:
+ """验证表格、代码、公式、视觉主体和未知类型不执行自然语言全角清洗。"""
+ model_list = [[{"type": block_type, "content": "Az0,。!?()"}]]
+
+ analyze._normalize_pdf_model_list(model_list)
+
+ assert model_list[0][0]["content"] == "Az0,。!?()"
+
+
def test_normalize_pdf_model_list_converts_phonetic_and_cleans_equation() -> None:
"""验证 phonetic 转公开类型,同时 equation 保持类型并清理展示分隔符。"""
model_list = [[