Skip to content

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

feat: introduce RefTextBlock and enhance text continuation logic for reference texts

myhloli218e05d218ce
diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.md
index 9f5c28a1..ad1bd550 100644
--- a/docs/next/middle-json/current-medium.md
+++ b/docs/next/middle-json/current-medium.md
@@ -89,7 +89,7 @@ text
| 模型 | `content` | 专属字段 |
|------|-----------|----------|
| `TextBlock` | `str` | `continues_prev`;不允许 `anchor` |
-| `RefTextBlock` | `str` | 不允许 `continues_prev` |
+| `RefTextBlock` | `str` | `continues_prev`;不允许 `anchor` |
| `DocTitleBlock` | `str` | `anchor`、必填 `level=1` |
| `ParagraphTitleBlock` | `str` | `anchor`、必填 `level>=2` |
| `PageAuxTextBlock` | `str` | 共享页眉、页脚、页码、边栏和页脚注释结构 |
@@ -101,9 +101,14 @@ text
| `*AnnotationBlock` | `str` | 每个视觉家族共享 caption/footnote 结构 |
| 其它叶子 block | `str` | 仅各自声明的字段 |
+`TextBlock` 与 `RefTextBlock` 共同继承 `ContinuableTextBlockBase`。PDF 分析阶段
+两者都必须具有合法的临时 `lines`,该字段只参与续段计算,不进入严格 Middle JSON。
+`ref_text` 复用正文的终止符和几何规则,但不要求续段首行或首列顶起始边界,
+也不因续段以数字或大写字符开头而拒绝合并。
+
`CodeBlock(sub_type="code")` 必须有非空 `guess_lang`;
`sub_type="algorithm"` 禁止 `guess_lang`。`continues_prev` 只允许出现在页面
-顶层 `text/list/table`,任何嵌套项即使显式写成 null 也会被拒绝。
+顶层 `text/ref_text/list/table`,任何嵌套项即使显式写成 null 也会被拒绝。
`merge_prev`、`is_numbered_style` 和 `section_number` 均不属于公开模型。
标题使用全局文档层级:文档标题固定为一级,所有段落标题从二级开始。
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 5bdb5228..4a0c192d 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -28,7 +28,7 @@ backend 参数或旧 `Line/Span` renderer。渲染过程基于深拷贝,不修
`MarkdownRenderMode.DEFAULT`:
- 隐藏 `header/footer/page_number/aside_text/page_footnote`。
-- 合并页内和跨页 `text.continues_prev`。
+- 合并页内和跨页 `text/ref_text.continues_prev`;ref_text 可跨过页面辅助块查找前序 ref_text。
- 合并页内和跨页 `list.continues_prev`;ref list 可跨过页面辅助块查找前序列表。
- 只合并跨页 `table.continues_prev`。
- 页面之间不输出分割线。
@@ -36,13 +36,14 @@ backend 参数或旧 `Line/Span` renderer。渲染过程基于深拷贝,不修
`MarkdownRenderMode.FULL`:
- 展示全部顶层 block。
-- 只合并页内 `text/list.continues_prev`。
-- 不合并跨页 text/list/table。
+- 只合并页内 `text/ref_text/list.continues_prev`。
+- 不合并跨页 text/ref_text/list/table。
- 每两个相邻 `PageInfo` 之间输出 `---`,空白页边界同样保留。
text 合并允许跨越任意其他 block,后一个 text 的内容被吸收到前一个 text,
-后块不再在原位置输出。ref list 只跨过页面辅助块,其他语义块仍会阻断列表链;
-普通 list 仍要求物理相邻。table 只接受跨页合并;失败时保留两张原表。
+后块不再在原位置输出。ref_text 与 ref list 都只跨过页面辅助块,其他语义块
+仍会分别阻断文本链和列表链;两种参考文献标记互不混用。普通 list 仍要求
+物理相邻。table 只接受跨页合并;失败时保留两张原表。
## Block 规则
diff --git a/mineru/backend/analysis/pdf/constants.py b/mineru/backend/analysis/pdf/constants.py
index 9b76729d..3aa4d3e3 100644
--- a/mineru/backend/analysis/pdf/constants.py
+++ b/mineru/backend/analysis/pdf/constants.py
@@ -29,6 +29,7 @@ TITLE_BLOCK_TYPES = {
CODE_CONTENT_BLOCK_TYPES = {BlockType.CODE, RAW_ALGORITHM}
LINE_METADATA_BLOCK_TYPES = {
BlockType.TEXT,
+ BlockType.REF_TEXT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
RAW_CAPTION,
@@ -133,11 +134,5 @@ NOT_EXTRACT_TYPES = {
RAW_PHONETIC,
}
VLM_TXT_DET_TYPE = NOT_EXTRACT_TYPES
-VLM_OCR_DET_TYPE = {
- BlockType.TEXT,
- BlockType.DOC_TITLE,
- BlockType.PARAGRAPH_TITLE,
- RAW_CAPTION,
- RAW_FOOTNOTE,
-}
+VLM_OCR_DET_TYPE = set(LINE_METADATA_BLOCK_TYPES)
_LOW_TXT_VISUAL_RUN_ANGLES = (0.0, 90.0, 180.0, 270.0)
diff --git a/mineru/backend/postprocess/paragraphs.py b/mineru/backend/postprocess/paragraphs.py
index 735875ee..9a6c65af 100644
--- a/mineru/backend/postprocess/paragraphs.py
+++ b/mineru/backend/postprocess/paragraphs.py
@@ -24,6 +24,7 @@ TEXT_MERGE_TRANSPARENT_TYPES = {
BlockType.CODE,
*PAGE_AUXILIARY_BLOCK_TYPES,
}
+CONTINUABLE_TEXT_BLOCK_TYPES = {BlockType.TEXT, BlockType.REF_TEXT}
VERTICAL_LINE_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2
VERTICAL_LINE_IN_BLOCK_THRESHOLD = 0.8
SINGLE_LINE_LOOKAHEAD_LIMIT = 5
@@ -46,7 +47,7 @@ def merge_para_text_blocks(pages: list[dict[str, Any]]) -> None:
for block in blocks:
if isinstance(block, dict):
_clear_nested_continues_prev(block)
- if block.get("type") != BlockType.TEXT:
+ if block.get("type") not in CONTINUABLE_TEXT_BLOCK_TYPES:
block.pop("continues_prev", None)
page_idx = page_info.get("page_idx")
@@ -59,26 +60,36 @@ def merge_para_text_blocks(pages: list[dict[str, Any]]) -> None:
for current_index in range(len(ordered_blocks) - 1, -1, -1):
current_page_idx, _, current_block = ordered_blocks[current_index]
current_type = current_block.get("type")
- if current_type == BlockType.TEXT:
+ if current_type in CONTINUABLE_TEXT_BLOCK_TYPES:
# 已清理过 lines 的结果视为 finalize 完成,保留其既有标记以支持幂等调用。
if "lines" not in current_block:
continue
current_block.pop("continues_prev", None)
- previous_block = _find_previous_text_block(ordered_blocks, current_index)
+ is_ref_text = current_type == BlockType.REF_TEXT
+ previous_block = (
+ _find_previous_ref_text_block(ordered_blocks, current_index)
+ if is_ref_text
+ else _find_previous_text_block(ordered_blocks, current_index)
+ )
if previous_block is None:
continue
previous_page_idx, _, previous_text_block = previous_block
if not _is_same_or_consecutive_page(current_page_idx, previous_page_idx):
continue
- if can_auto_merge_text_blocks(
- current_block,
- previous_text_block,
- ) or _can_auto_merge_multiline_to_single_line(
+ can_merge = (
+ can_auto_merge_ref_text_blocks(current_block, previous_text_block)
+ if is_ref_text
+ else can_auto_merge_text_blocks(current_block, previous_text_block)
+ )
+ if can_merge or _can_auto_merge_multiline_to_single_line(
current_block,
previous_text_block,
ordered_blocks=ordered_blocks,
current_index=current_index,
current_page_idx=current_page_idx,
+ current_type=current_type,
+ require_current_leading_edge=not is_ref_text,
+ reject_digit_or_uppercase_start=not is_ref_text,
):
current_block["continues_prev"] = True
elif current_type == BlockType.LIST:
@@ -104,6 +115,32 @@ def merge_para_text_blocks(pages: list[dict[str, Any]]) -> None:
def can_auto_merge_text_blocks(current_block: BlockDict, previous_block: BlockDict) -> bool:
"""按文本首尾、行方向和几何关系判断两个 dict text block 是否可连续。"""
+ return _can_auto_merge_continuable_text_blocks(
+ current_block,
+ previous_block,
+ require_current_leading_edge=True,
+ reject_digit_or_uppercase_start=True,
+ )
+
+
+def can_auto_merge_ref_text_blocks(current_block: BlockDict, previous_block: BlockDict) -> bool:
+ """按正文规则判断 ref_text,放宽当前起始边界及数字或大写字符开头限制。"""
+ return _can_auto_merge_continuable_text_blocks(
+ current_block,
+ previous_block,
+ require_current_leading_edge=False,
+ reject_digit_or_uppercase_start=False,
+ )
+
+
+def _can_auto_merge_continuable_text_blocks(
+ current_block: BlockDict,
+ previous_block: BlockDict,
+ *,
+ require_current_leading_edge: bool,
+ reject_digit_or_uppercase_start: bool,
+) -> bool:
+ """复用正文与参考文献的公共文本边界、方向及几何续接规则。"""
current_metric_lines = _metric_line_bboxes(current_block)
previous_metric_lines = _metric_line_bboxes(previous_block)
if not current_metric_lines or not previous_metric_lines:
@@ -118,6 +155,12 @@ def can_auto_merge_text_blocks(current_block: BlockDict, previous_block: BlockDi
previous_content = _normalized_text_content(previous_block)
if not current_content or not previous_content:
return False
+ if not _has_mergeable_text_boundary(
+ current_content,
+ previous_content,
+ reject_digit_or_uppercase_start=reject_digit_or_uppercase_start,
+ ):
+ return False
current_is_vertical = _is_vertical_text_block_by_lines(current_metric_lines)
previous_is_vertical = _is_vertical_text_block_by_lines(previous_metric_lines)
@@ -131,6 +174,7 @@ def can_auto_merge_text_blocks(current_block: BlockDict, previous_block: BlockDi
previous_bbox,
current_metric_lines,
previous_metric_lines,
+ require_current_leading_edge=require_current_leading_edge,
)
return _can_auto_merge_horizontal_text_blocks(
current_content,
@@ -139,6 +183,7 @@ def can_auto_merge_text_blocks(current_block: BlockDict, previous_block: BlockDi
previous_bbox,
current_metric_lines,
previous_metric_lines,
+ require_current_leading_edge=require_current_leading_edge,
)
@@ -160,6 +205,22 @@ def _find_previous_text_block(
return None
+def _find_previous_ref_text_block(
+ ordered_blocks: list[OrderedBlock],
+ current_index: int,
+) -> OrderedBlock | None:
+ """跳过页面辅助块查找前一个 ref_text,其他语义块保持阻断。"""
+ for previous_index in range(current_index - 1, -1, -1):
+ previous_block = ordered_blocks[previous_index][2]
+ previous_type = previous_block.get("type")
+ if previous_type in PAGE_AUXILIARY_BLOCK_TYPES:
+ continue
+ if previous_type == BlockType.REF_TEXT:
+ return ordered_blocks[previous_index]
+ return None
+ return None
+
+
def _find_previous_ref_text_list_block(
ordered_blocks: list[OrderedBlock],
current_index: int,
@@ -264,10 +325,17 @@ def _is_vertical_text_block_by_lines(line_bboxes: list[CalculationBBox]) -> bool
return vertical_line_count / len(line_bboxes) > VERTICAL_LINE_IN_BLOCK_THRESHOLD
-def _has_mergeable_text_boundary(current_content: str, previous_content: str) -> bool:
+def _has_mergeable_text_boundary(
+ current_content: str,
+ previous_content: str,
+ *,
+ reject_digit_or_uppercase_start: bool,
+) -> bool:
"""使用前块结尾和后块开头字符排除明显的新段落边界。"""
if previous_content.endswith(LINE_STOP_FLAG):
return False
+ if not reject_digit_or_uppercase_start:
+ return True
first_char = current_content[0]
return not first_char.isdigit() and not first_char.isupper()
@@ -277,18 +345,20 @@ def _collect_following_same_orientation_lines(
current_index: int,
*,
current_page_idx: int,
+ current_type: str,
is_vertical: bool,
) -> list[CalculationBBox]:
- """在当前页向后读取至多五条同方向正文行,语义屏障或非法文本会终止读取。"""
+ """在当前页向后读取至多五条同类型同方向行,语义屏障或非法文本会终止读取。"""
following_lines: list[CalculationBBox] = []
+ transparent_types = (
+ TEXT_MERGE_TRANSPARENT_TYPES if current_type == BlockType.TEXT else PAGE_AUXILIARY_BLOCK_TYPES
+ )
for page_idx, _, block in ordered_blocks[current_index + 1 :]:
if page_idx != current_page_idx:
break
block_type = block.get("type")
- if block_type in TEXT_MERGE_BARRIER_TYPES:
- break
- if block_type != BlockType.TEXT:
- if block_type in TEXT_MERGE_TRANSPARENT_TYPES:
+ if block_type != current_type:
+ if block_type in transparent_types:
continue
break
@@ -355,6 +425,9 @@ def _can_auto_merge_multiline_to_single_line(
ordered_blocks: list[OrderedBlock],
current_index: int,
current_page_idx: int,
+ current_type: str,
+ require_current_leading_edge: bool,
+ reject_digit_or_uppercase_start: bool,
) -> bool:
"""用后续五行或列补足单行主轴尺寸,再复用原横排或竖排连接规则。"""
current_lines = _metric_line_bboxes(current_block)
@@ -369,6 +442,7 @@ def _can_auto_merge_multiline_to_single_line(
ordered_blocks,
current_index,
current_page_idx=current_page_idx,
+ current_type=current_type,
is_vertical=current_is_vertical,
)
aligned_lines = _aligned_following_lines(
@@ -385,6 +459,12 @@ def _can_auto_merge_multiline_to_single_line(
previous_content = _normalized_text_content(previous_block)
if current_bbox is None or previous_bbox is None or not current_content or not previous_content:
return False
+ if not _has_mergeable_text_boundary(
+ current_content,
+ previous_content,
+ reject_digit_or_uppercase_start=reject_digit_or_uppercase_start,
+ ):
+ return False
virtual_current_line = _virtual_single_line_bbox(
current_lines[0],
@@ -399,6 +479,7 @@ def _can_auto_merge_multiline_to_single_line(
previous_bbox,
[virtual_current_line],
previous_lines,
+ require_current_leading_edge=require_current_leading_edge,
)
return _can_auto_merge_horizontal_text_blocks(
current_content,
@@ -407,6 +488,7 @@ def _can_auto_merge_multiline_to_single_line(
previous_bbox,
[virtual_current_line],
previous_lines,
+ require_current_leading_edge=require_current_leading_edge,
)
@@ -417,6 +499,8 @@ def _can_auto_merge_horizontal_text_blocks(
previous_bbox: CalculationBBox,
current_lines: list[CalculationBBox],
previous_lines: list[CalculationBBox],
+ *,
+ require_current_leading_edge: bool,
) -> bool:
"""使用横排段落的首行、末行、宽度和 block 相交规则判断是否连续。"""
first_line = current_lines[0]
@@ -428,13 +512,10 @@ def _can_auto_merge_horizontal_text_blocks(
current_lines_bbox = _bbox_union(current_lines)
previous_lines_bbox = _bbox_union(previous_lines)
- if abs(current_lines_bbox[0] - first_line[0]) >= first_line_height / 2:
+ if require_current_leading_edge and abs(current_lines_bbox[0] - first_line[0]) >= first_line_height / 2:
return False
if abs(previous_lines_bbox[2] - last_line[2]) >= last_line_height:
return False
- if not _has_mergeable_text_boundary(current_content, previous_content):
- return False
-
current_width = current_lines_bbox[2] - current_lines_bbox[0]
previous_width = previous_lines_bbox[2] - previous_lines_bbox[0]
min_width = min(current_width, previous_width)
@@ -452,6 +533,8 @@ def _can_auto_merge_vertical_text_blocks(
previous_bbox: CalculationBBox,
current_lines: list[CalculationBBox],
previous_lines: list[CalculationBBox],
+ *,
+ require_current_leading_edge: bool,
) -> bool:
"""使用竖排段落的首列、末列、高度和 block 相交规则判断是否连续。"""
first_line = current_lines[0]
@@ -463,13 +546,10 @@ def _can_auto_merge_vertical_text_blocks(
current_lines_bbox = _bbox_union(current_lines)
previous_lines_bbox = _bbox_union(previous_lines)
- if abs(current_lines_bbox[1] - first_line[1]) >= first_line_width / 2:
+ if require_current_leading_edge and abs(current_lines_bbox[1] - first_line[1]) >= first_line_width / 2:
return False
if abs(previous_lines_bbox[3] - last_line[3]) >= last_line_width:
return False
- if not _has_mergeable_text_boundary(current_content, previous_content):
- return False
-
current_height = current_lines_bbox[3] - current_lines_bbox[1]
previous_height = previous_lines_bbox[3] - previous_lines_bbox[1]
min_height = min(current_height, previous_height)
@@ -479,7 +559,7 @@ def _can_auto_merge_vertical_text_blocks(
def _clear_nested_continues_prev(block: BlockDict) -> None:
- """递归清理子块旧标记,顶层 text 标记由是否仍有 lines 决定是否重算。"""
+ """递归清理子块旧标记,顶层 text/ref_text 标记由是否仍有 lines 决定是否重算。"""
content = block.get("content")
if not isinstance(content, list):
return
diff --git a/mineru/model/flash/native_pdf/pipeline.py b/mineru/model/flash/native_pdf/pipeline.py
index e69d412b..70531b7a 100644
--- a/mineru/model/flash/native_pdf/pipeline.py
+++ b/mineru/model/flash/native_pdf/pipeline.py
@@ -101,6 +101,7 @@ from .visual_annotations import _classify_and_bind_visual_annotations
_TEXT_SEMANTIC_TYPES = {
"doc_title",
"paragraph_title",
+ "ref_text",
"header",
"footer",
"page_number",
@@ -115,6 +116,7 @@ _TEXT_SEMANTIC_TYPES = {
_OUTPUT_BLOCK_TYPES = {"text", "table", "image", "equation", "code"} | _TEXT_SEMANTIC_TYPES
_LINE_METADATA_OUTPUT_TYPES = {
"text",
+ "ref_text",
"doc_title",
"paragraph_title",
"caption",
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index 542732c4..95bd3162 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -123,7 +123,8 @@ def _render_planned_block(
content = render_joined_inline_contents(planned.text_contents or [block.content], delimiters)
return escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
if isinstance(block, RefTextBlock):
- return escape_standalone_marker_rule(render_inline_content(block.content, delimiters))
+ content = render_joined_inline_contents(planned.text_contents or [block.content], delimiters)
+ return escape_standalone_marker_rule(content)
if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
return _render_title(block, delimiters)
if isinstance(block, PageAuxTextBlock):
diff --git a/mineru/render/utils/logical_blocks.py b/mineru/render/utils/logical_blocks.py
index 4cf65452..b09b964d 100644
--- a/mineru/render/utils/logical_blocks.py
+++ b/mineru/render/utils/logical_blocks.py
@@ -7,7 +7,17 @@ from dataclasses import dataclass, field
from enum import Enum
from mineru.backend.postprocess.table_merge import merge_table_content
-from mineru.types import PAGE_AUXILIARY_BLOCK_TYPES, BlockType, ListBlock, MiddleJson, PageBlock, TableBlock, TextBlock
+from mineru.types import (
+ PAGE_AUXILIARY_BLOCK_TYPES,
+ BlockType,
+ ContinuableTextBlockBase,
+ ListBlock,
+ MiddleJson,
+ PageBlock,
+ RefTextBlock,
+ TableBlock,
+ TextBlock,
+)
class MarkdownRenderMode(str, Enum):
@@ -35,7 +45,7 @@ def build_render_plan(middle_json: MiddleJson, mode: MarkdownRenderMode) -> list
PlannedBlock(
page_idx=page.page_idx,
block=block,
- text_contents=[block.content] if isinstance(block, TextBlock) else [],
+ text_contents=[block.content] if isinstance(block, ContinuableTextBlockBase) else [],
)
for block in page.blocks
]
@@ -52,7 +62,11 @@ def build_render_plan(middle_json: MiddleJson, mode: MarkdownRenderMode) -> list
def _merge_continued_text_blocks(blocks: list[PlannedBlock], mode: MarkdownRenderMode) -> None:
"""把 continues_prev 文本吸收到最近的前序文本逻辑块。"""
for current_index, current in enumerate(blocks):
- if current.removed or not isinstance(current.block, TextBlock) or current.block.continues_prev is not True:
+ if (
+ current.removed
+ or not isinstance(current.block, ContinuableTextBlockBase)
+ or current.block.continues_prev is not True
+ ):
continue
previous = _find_previous_planned_text(blocks, current_index)
if previous is None:
@@ -65,7 +79,23 @@ def _merge_continued_text_blocks(blocks: list[PlannedBlock], mode: MarkdownRende
def _find_previous_planned_text(blocks: list[PlannedBlock], current_index: int) -> PlannedBlock | None:
- """跨越任意类型查找最近且仍参与输出的前序文本。"""
+ """按 text/ref_text 各自的透明块规则查找仍参与输出的前序同类文本。"""
+ current = blocks[current_index]
+ if isinstance(current.block, RefTextBlock):
+ previous_index = current_index - 1
+ while previous_index >= 0:
+ candidate = blocks[previous_index]
+ if candidate.block.type in PAGE_AUXILIARY_BLOCK_TYPES:
+ previous_index -= 1
+ continue
+ if not isinstance(candidate.block, RefTextBlock):
+ return None
+ if not candidate.removed:
+ return candidate
+ previous_index -= 1
+ return None
+ if not isinstance(current.block, TextBlock):
+ return None
for candidate in reversed(blocks[:current_index]):
if not candidate.removed and isinstance(candidate.block, TextBlock):
return candidate
diff --git a/mineru/types.py b/mineru/types.py
index a9e4f77f..adf5b677 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -376,12 +376,17 @@ class StringContentBlock(BlockBase):
content: str
-class TextBlock(StringContentBlock):
- type: Literal[BlockType.TEXT]
+class ContinuableTextBlockBase(StringContentBlock):
+ """正文与参考文献共享的跨块续接结构。"""
+
continues_prev: bool | None = None
-class RefTextBlock(StringContentBlock):
+class TextBlock(ContinuableTextBlockBase):
+ type: Literal[BlockType.TEXT]
+
+
+class RefTextBlock(ContinuableTextBlockBase):
type: Literal[BlockType.REF_TEXT]
diff --git a/tests/unittest/test_flash_pdf_line_metadata.py b/tests/unittest/test_flash_pdf_line_metadata.py
index dcb37702..aba938a9 100644
--- a/tests/unittest/test_flash_pdf_line_metadata.py
+++ b/tests/unittest/test_flash_pdf_line_metadata.py
@@ -7,12 +7,12 @@ from mineru.model.flash.native_pdf import pipeline
@pytest.mark.parametrize(
"block_type",
- ["text", "doc_title", "paragraph_title", "caption", "footnote"],
+ ["text", "ref_text", "doc_title", "paragraph_title", "caption", "footnote"],
)
def test_output_normalization_exposes_lines_for_pdf_text_types(
block_type: str,
) -> None:
- """验证五类 PDF 文本块会按原阅读顺序公开归一化行框。"""
+ """验证 Flash 对包括 ref_text 在内的 PDF 文本块公开归一化行框。"""
block = pipeline._normalize_output_block(
{
@@ -64,6 +64,7 @@ def test_output_normalization_restores_rotated_line_bbox_to_page(
assert block["lines"] == [{"bbox": expected_bbox}]
[email protected]("block_type", ["text", "ref_text"])
@pytest.mark.parametrize(
"local_line_bboxes",
[
@@ -74,13 +75,14 @@ def test_output_normalization_restores_rotated_line_bbox_to_page(
],
)
def test_output_normalization_fails_closed_for_invalid_line_bboxes(
+ block_type: str,
local_line_bboxes: object,
) -> None:
- """验证内部行框缺失、为空或任一非法时输出空 lines。"""
+ """验证 text/ref_text 内部行框缺失、为空或任一非法时输出空 lines。"""
block = pipeline._normalize_output_block(
{
- "type": "text",
+ "type": block_type,
"bbox": (10.0, 20.0, 40.0, 50.0),
"angle": 0,
"content": "value",
diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.py
index 69c67489..d56249b1 100644
--- a/tests/unittest/test_flash_pdf_pipeline.py
+++ b/tests/unittest/test_flash_pdf_pipeline.py
@@ -249,6 +249,7 @@ def test_native_pdf_domain_modules_do_not_import_each_other() -> None:
[
"doc_title",
"paragraph_title",
+ "ref_text",
"header",
"footer",
"page_number",
diff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.py
index dfe115b0..86a8c251 100644
--- a/tests/unittest/test_markdown_render.py
+++ b/tests/unittest/test_markdown_render.py
@@ -100,6 +100,16 @@ def _list(
)
+def _ref_text(index: int, content: str, *, continues_prev: bool | None = None) -> RefTextBlock:
+ """构造可携带续段标记的顶层参考文献文本块。"""
+ return RefTextBlock(
+ type="ref_text",
+ index=index,
+ content=content,
+ continues_prev=continues_prev,
+ )
+
+
def test_render_modes_filter_merge_and_preserve_input() -> None:
"""验证两种模式的过滤、页内/跨页合并、分页线及无副作用。"""
middle = _middle(
@@ -162,6 +172,57 @@ def test_text_continuation_handles_hyphen_and_cjk_boundaries() -> None:
assert render_markdown(cjk) == "中文继续"
+def test_ref_text_continuation_skips_page_auxiliary_blocks_by_mode() -> None:
+ """验证 ref_text 默认跨页合并,FULL 只合并页内链且不修改输入。"""
+ middle = _middle(
+ _page(
+ 0,
+ _ref_text(0, "inter-"),
+ PageAuxTextBlock(type="page_footnote", index=1, content="NOTE"),
+ ),
+ _page(
+ 1,
+ PageAuxTextBlock(type="header", index=0, content="HEADER"),
+ _ref_text(1, "national", continues_prev=True),
+ _ref_text(2, "continuation", continues_prev=True),
+ ),
+ )
+ original = deepcopy(middle)
+
+ assert render_markdown(middle) == "international continuation"
+ assert render_markdown(middle, mode=MarkdownRenderMode.FULL) == (
+ "inter-\n\nNOTE\n\n---\n\nHEADER\n\nnational continuation"
+ )
+ assert middle == original
+
+
+def test_ref_text_continuation_keeps_semantic_barrier() -> None:
+ """验证手工标记也不能让 ref_text 跨过正文等语义块。"""
+ middle = _middle(
+ _page(
+ 0,
+ _ref_text(0, "first"),
+ TextBlock(type="text", index=1, content="separator"),
+ _ref_text(2, "second", continues_prev=True),
+ )
+ )
+
+ assert render_markdown(middle) == "first\n\nseparator\n\nsecond"
+
+
+def test_ref_text_continuation_reuses_url_boundary_joining() -> None:
+ """验证 ref_text 续段复用正文的跨块 URL 连接规则。"""
+ middle = _middle(
+ _page(
+ 0,
+ _ref_text(0, "See https://doi.o"),
+ _ref_text(1, "rg/10.1016/example", continues_prev=True),
+ )
+ )
+
+ assert render_markdown(middle) == "See https://doi.org/10.1016/example"
+
+
def test_list_continuation_merges_same_page_in_both_modes_without_mutating_input() -> None:
"""验证同页同子类型列表在两种模式下拼接,且不污染原始 MiddleJson。"""
middle = _middle(
diff --git a/tests/unittest/test_middle_json_block_models.py b/tests/unittest/test_middle_json_block_models.py
index 730550c1..ad058273 100644
--- a/tests/unittest/test_middle_json_block_models.py
+++ b/tests/unittest/test_middle_json_block_models.py
@@ -19,6 +19,7 @@ from mineru.types import (
ChartAnnotationBlock,
CodeAnnotationBlock,
CodeBlock,
+ ContinuableTextBlockBase,
EquationBlock,
ImageAnnotationBlock,
ListBlock,
@@ -26,6 +27,7 @@ from mineru.types import (
PageAuxTextBlock,
PageBlockTypes,
PageInfo,
+ RefTextBlock,
TableAnnotationBlock,
TextBlock,
parse_block,
@@ -184,12 +186,19 @@ def test_formula_number_is_rejected_by_middle_json_boundary_and_schema() -> None
)
-def test_cross_type_fields_and_unknown_fields_are_rejected() -> None:
- """验证 Text/RefText 的专属字段边界与 extra forbid。"""
+def test_continuable_text_models_share_marker_and_reject_unknown_fields() -> None:
+ """验证 Text/RefText 共用续接基类,同时继续执行严格字段校验。"""
+ text = parse_block({"type": "text", "content": "x", "continues_prev": True})
+ ref_text = parse_block({"type": "ref_text", "content": "r", "continues_prev": True})
+
+ assert isinstance(text, ContinuableTextBlockBase)
+ assert isinstance(ref_text, RefTextBlock)
+ assert isinstance(ref_text, ContinuableTextBlockBase)
+ assert set(TextBlock.model_fields) == set(RefTextBlock.model_fields)
+ assert text.continues_prev is True
+ assert ref_text.continues_prev is True
with pytest.raises(ValidationError):
parse_block({"type": "text", "content": "x", "anchor": "a"})
- with pytest.raises(ValidationError):
- parse_block({"type": "ref_text", "content": "x", "continues_prev": True})
with pytest.raises(ValidationError):
parse_block({"type": "text", "content": "x", "unknown": 1})
@@ -402,22 +411,10 @@ def test_page_info_accepts_all_page_root_discriminators() -> None:
assert page.blocks[0].type == block_type
-def test_nested_continues_prev_is_rejected_by_page_tree() -> None:
- """验证 continues_prev 只能出现在页面顶层 text/list/table。"""
- with pytest.raises(ValidationError, match="nested"):
- PageInfo.model_validate(
- {
- "page_idx": 0,
- "blocks": [
- {
- "type": "list",
- "index": 0,
- "content": [{"type": "text", "content": "x", "continues_prev": True}],
- }
- ],
- }
- )
-
[email protected]("child_type", [BlockType.TEXT, BlockType.REF_TEXT])
[email protected]("continues_prev", [True, None])
+def test_nested_continues_prev_is_rejected_by_page_tree(child_type: str, continues_prev: bool | None) -> None:
+ """验证 continues_prev 只能出现在页面顶层 text/ref_text/list/table。"""
with pytest.raises(ValidationError, match="nested"):
PageInfo.model_validate(
{
@@ -426,7 +423,7 @@ def test_nested_continues_prev_is_rejected_by_page_tree() -> None:
{
"type": "list",
"index": 0,
- "content": [{"type": "text", "content": "x", "continues_prev": None}],
+ "content": [{"type": child_type, "content": "x", "continues_prev": continues_prev}],
}
],
}
diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.py
index f74ebb26..c96c3d1a 100644
--- a/tests/unittest/test_pdf_analyze_block_content.py
+++ b/tests/unittest/test_pdf_analyze_block_content.py
@@ -275,16 +275,18 @@ def test_xhigh_vlm_blocks_normalize_visual_annotation_types() -> None:
]
-def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:
- """验证五类 PDF 文本块统一保留公开的归一化 lines。"""
+def test_six_pdf_text_types_keep_normalized_line_metadata() -> None:
+ """验证包括 ref_text 在内的六类 PDF 文本块统一保留归一化 lines。"""
assert constants.LINE_METADATA_BLOCK_TYPES == {
BlockType.TEXT,
+ BlockType.REF_TEXT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
RAW_CAPTION,
RAW_FOOTNOTE,
}
text_block = {"type": BlockType.TEXT, "content": "text"}
+ ref_text_block = {"type": BlockType.REF_TEXT, "content": "reference"}
doc_title_block = {"type": BlockType.DOC_TITLE, "content": "doc title"}
paragraph_title_block = {
"type": BlockType.PARAGRAPH_TITLE,
@@ -299,6 +301,7 @@ def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:
}
page_blocks = [
text_block,
+ ref_text_block,
doc_title_block,
paragraph_title_block,
caption_block,
@@ -310,16 +313,18 @@ def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:
page_blocks,
{
0: _build_text_lines("text"),
- 1: _build_text_lines("doc title"),
- 2: _build_text_lines("paragraph title"),
- 3: _build_text_lines("caption line 1", "caption line 2"),
- 4: _build_text_lines("footnote"),
- 5: _build_text_lines("x=1"),
+ 1: _build_text_lines("reference"),
+ 2: _build_text_lines("doc title"),
+ 3: _build_text_lines("paragraph title"),
+ 4: _build_text_lines("caption line 1", "caption line 2"),
+ 5: _build_text_lines("footnote"),
+ 6: _build_text_lines("x=1"),
},
(200.0, 100.0),
)
assert text_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
+ assert ref_text_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
assert doc_title_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
assert paragraph_title_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
assert caption_block["lines"] == [
@@ -331,10 +336,10 @@ def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:
@pytest.mark.parametrize("effort", ["high", "xhigh"])
-def test_high_ocr_detects_lines_for_all_five_pdf_text_types(
+def test_high_ocr_detects_lines_for_all_six_pdf_text_types(
effort: str,
) -> None:
- """验证 High/XHigh OCR 对标题、正文、caption 和 footnote 都执行行检测。"""
+ """验证 High/XHigh OCR 对 ref_text 和其余行框文本类型都执行行检测。"""
ocr_det_type, mfr_enabled = ocr._build_ocr_det_type_and_mfr_enable(
"ocr",
@@ -345,6 +350,13 @@ def test_high_ocr_detects_lines_for_all_five_pdf_text_types(
assert mfr_enabled is False
+def test_all_hybrid_text_routes_collect_ref_text_lines() -> None:
+ """验证 Low/Medium 与 High/XHigh 的 TXT/OCR 路由都包含 ref_text。"""
+ assert BlockType.REF_TEXT in constants.PIPELINE_DET_TYPE
+ assert BlockType.REF_TEXT in constants.VLM_TXT_DET_TYPE
+ assert BlockType.REF_TEXT in constants.VLM_OCR_DET_TYPE
+
+
def test_window_post_ocr_batches_all_pages_once() -> None:
"""验证窗口内多页待识别 span 合并为一次 OCR-rec,并按原顺序回填。"""
page_block_lines_list, spans = _build_post_ocr_page_block_lines((11, 12), (21, 22))
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index 66a62c63..5256bbde 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -1035,6 +1035,7 @@ def test_normalize_pdf_model_list_rejects_unclassified_vlm_title() -> None:
"block_type",
[
BlockType.TEXT,
+ BlockType.REF_TEXT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
RAW_CAPTION,
@@ -1059,11 +1060,11 @@ def test_normalize_pdf_model_list_rejects_unclassified_vlm_title() -> None:
],
],
)
-def test_normalize_pdf_model_list_removes_five_text_types_with_invalid_lines(
+def test_normalize_pdf_model_list_removes_six_text_types_with_invalid_lines(
block_type: str,
invalid_lines: object,
) -> None:
- """验证五类文本块只要任一行框非法就按 fail-closed 规则删除。"""
+ """验证包括 ref_text 在内的六类文本块遇到非法行框时按 fail-closed 规则删除。"""
model_list = [[{"type": block_type, "content": "valid", "lines": invalid_lines}]]
@@ -1076,6 +1077,7 @@ def test_normalize_pdf_model_list_removes_five_text_types_with_invalid_lines(
"block_type",
[
BlockType.TEXT,
+ BlockType.REF_TEXT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
RAW_CAPTION,
@@ -1083,11 +1085,11 @@ def test_normalize_pdf_model_list_removes_five_text_types_with_invalid_lines(
],
)
@pytest.mark.parametrize("invalid_content", [None, "", " ", ["not a string"]])
-def test_normalize_pdf_model_list_removes_five_text_types_with_empty_content(
+def test_normalize_pdf_model_list_removes_six_text_types_with_empty_content(
block_type: str,
invalid_content: object,
) -> None:
- """验证五类文本块即使行框有效,正文为空或非字符串时仍会删除。"""
+ """验证包括 ref_text 在内的六类文本块即使行框有效,正文无效时仍会删除。"""
model_list = [
[
diff --git a/tests/unittest/test_postprocess_pages.py b/tests/unittest/test_postprocess_pages.py
index 5e74f9ef..8275d4b8 100644
--- a/tests/unittest/test_postprocess_pages.py
+++ b/tests/unittest/test_postprocess_pages.py
@@ -12,6 +12,7 @@ from mineru.types import (
ListBlock,
PageInfo,
ParagraphTitleBlock,
+ RefTextBlock,
TableBlock,
TextBlock,
)
@@ -399,6 +400,33 @@ def test_pdf_continuation_is_typed_and_line_metadata_is_removed() -> None:
assert all("lines" not in type(block).model_fields for block in page.blocks)
+def test_pdf_ref_text_continuation_is_typed_and_line_metadata_is_removed() -> None:
+ """验证 ref_text 续段标记越过 raw 边界,严格对象不保留临时 lines。"""
+ model_list = [
+ [
+ {
+ "type": "ref_text",
+ "bbox": [0.1, 0.1, 0.9, 0.3],
+ "content": "previous continuation",
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.15]}, {"bbox": [0.1, 0.2, 0.9, 0.25]}],
+ },
+ {
+ "type": "ref_text",
+ "bbox": [0.1, 0.25, 0.9, 0.45],
+ "content": "current continuation",
+ "lines": [{"bbox": [0.2, 0.25, 0.9, 0.3]}, {"bbox": [0.1, 0.35, 0.9, 0.4]}],
+ },
+ ]
+ ]
+
+ page = model_list_to_pages(model_list)[0]
+
+ assert all(isinstance(block, RefTextBlock) for block in page.blocks)
+ assert page.blocks[0].continues_prev is None
+ assert page.blocks[1].continues_prev is True
+ assert all("lines" not in type(block).model_fields for block in page.blocks)
+
+
def test_pdf_detection_scans_past_empty_first_page() -> None:
"""验证整份文档 bbox 判定不会把 PDF 空白首页误认为 Office。"""
pages = model_list_to_pages(
diff --git a/tests/unittest/test_postprocess_paragraphs.py b/tests/unittest/test_postprocess_paragraphs.py
index 8347e02d..fe2354a0 100644
--- a/tests/unittest/test_postprocess_paragraphs.py
+++ b/tests/unittest/test_postprocess_paragraphs.py
@@ -4,7 +4,11 @@ from copy import deepcopy
import pytest
-from mineru.backend.postprocess.paragraphs import can_auto_merge_text_blocks, merge_para_text_blocks
+from mineru.backend.postprocess.paragraphs import (
+ can_auto_merge_ref_text_blocks,
+ can_auto_merge_text_blocks,
+ merge_para_text_blocks,
+)
from mineru.types import BlockType
@@ -13,11 +17,13 @@ def _text_block(
content: str,
bbox: list[float],
line_bboxes: list[list[float]],
+ *,
+ block_type: str = BlockType.TEXT,
) -> dict:
- """构造使用归一化 block/line bbox 的 dict text block。"""
+ """构造使用归一化 block/line bbox 的 dict text/ref_text block。"""
return {
"index": index,
- "type": BlockType.TEXT,
+ "type": block_type,
"bbox": list(bbox),
"content": content,
"lines": [{"bbox": list(line_bbox)} for line_bbox in line_bboxes],
@@ -64,6 +70,15 @@ def _horizontal_pair() -> tuple[dict, dict]:
return previous_block, current_block
+def _ref_text_horizontal_pair() -> tuple[dict, dict]:
+ """构造首行缩进但其余规则满足续接条件的 ref_text 块对。"""
+ previous_block, current_block = _horizontal_pair()
+ previous_block["type"] = BlockType.REF_TEXT
+ current_block["type"] = BlockType.REF_TEXT
+ current_block["lines"][0]["bbox"][0] = 0.2
+ return previous_block, current_block
+
+
def _horizontal_multiline_block(
index: int,
content: str,
@@ -691,6 +706,233 @@ def test_merge_para_text_blocks_supports_vertical_but_rejects_mixed_orientation(
assert "continues_prev" not in current_horizontal
+def test_ref_text_rule_relaxes_leading_edge_and_initial_character() -> None:
+ """验证 ref_text 放宽当前起始边界以及数字或大写字符开头限制。"""
+ previous_block, current_block = _ref_text_horizontal_pair()
+ assert can_auto_merge_ref_text_blocks(current_block, previous_block)
+ assert not can_auto_merge_text_blocks(current_block, previous_block)
+
+ previous_block, current_block = _ref_text_horizontal_pair()
+ previous_block["content"] = "finished."
+ assert not can_auto_merge_ref_text_blocks(current_block, previous_block)
+
+ previous_block, current_block = _ref_text_horizontal_pair()
+ current_block["content"] = "Uppercase"
+ assert can_auto_merge_ref_text_blocks(current_block, previous_block)
+ assert not can_auto_merge_text_blocks(current_block, previous_block)
+
+ previous_block, current_block = _ref_text_horizontal_pair()
+ current_block["content"] = "1470–1480, Beijing, China."
+ assert can_auto_merge_ref_text_blocks(current_block, previous_block)
+ assert not can_auto_merge_text_blocks(current_block, previous_block)
+
+ previous_block, current_block = _ref_text_horizontal_pair()
+ previous_block["lines"][-1]["bbox"][2] = 0.7
+ assert not can_auto_merge_ref_text_blocks(current_block, previous_block)
+
+ previous_block, current_block = _ref_text_horizontal_pair()
+ for line in current_block["lines"]:
+ line["bbox"][2] = 0.4
+ assert not can_auto_merge_ref_text_blocks(current_block, previous_block)
+
+ previous_block, current_block = _ref_text_horizontal_pair()
+ previous_block["lines"] = previous_block["lines"][:1]
+ current_block["lines"] = current_block["lines"][:1]
+ assert not can_auto_merge_ref_text_blocks(current_block, previous_block)
+
+ previous_block, current_block = _ref_text_horizontal_pair()
+ current_block["bbox"][1] = 0.31
+ assert not can_auto_merge_ref_text_blocks(current_block, previous_block)
+
+ previous_vertical, current_vertical = _vertical_pair()
+ previous_vertical["type"] = BlockType.REF_TEXT
+ current_vertical["type"] = BlockType.REF_TEXT
+ current_vertical["lines"][0]["bbox"][1] = 0.2
+ assert can_auto_merge_ref_text_blocks(current_vertical, previous_vertical)
+ assert not can_auto_merge_text_blocks(current_vertical, previous_vertical)
+
+
+def test_merge_para_text_blocks_marks_indented_ref_text_without_moving_content() -> None:
+ """验证页内 ref_text 只在后块写标记,并保留内容与 bbox。"""
+ previous_block, current_block = _ref_text_horizontal_pair()
+ pages = [{"page_idx": 0, "blocks": [previous_block, current_block]}]
+ original_contents = [previous_block["content"], current_block["content"]]
+ original_bboxes = deepcopy([previous_block["bbox"], current_block["bbox"]])
+
+ merge_para_text_blocks(pages)
+
+ assert "continues_prev" not in previous_block
+ assert current_block["continues_prev"] is True
+ assert [previous_block["content"], current_block["content"]] == original_contents
+ assert [previous_block["bbox"], current_block["bbox"]] == original_bboxes
+ assert "lines" not in previous_block
+ assert "lines" not in current_block
+
+ first_result = deepcopy(pages)
+ merge_para_text_blocks(pages)
+ assert pages == first_result
+
+
+def test_merge_para_text_blocks_marks_numeric_reference_page_range() -> None:
+ """验证数字页码范围开头的 ref_text 可以续接前一条未结束参考文献。"""
+ previous_block, current_block = _ref_text_horizontal_pair()
+ previous_block["content"] = "Proceedings of the conference, pages"
+ current_block["content"] = "1470–1480, Beijing, China."
+ pages = [{"page_idx": 0, "blocks": [previous_block, current_block]}]
+
+ merge_para_text_blocks(pages)
+
+ assert current_block["continues_prev"] is True
+
+
+ ("page_indices", "expected_continuation"),
+ [((0, 1), True), ((0, 2), False), ((2, 1), False)],
+)
+def test_merge_para_text_blocks_requires_consecutive_ref_text_pages(
+ page_indices: tuple[int, int],
+ expected_continuation: bool,
+) -> None:
+ """验证 ref_text 仅允许从同一阅读链的前一连续页续接。"""
+ previous_block, current_block = _ref_text_horizontal_pair()
+ pages = [
+ {"page_idx": page_indices[0], "blocks": [previous_block]},
+ {"page_idx": page_indices[1], "blocks": [current_block]},
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert current_block.get("continues_prev", False) is expected_continuation
+
+
+def test_merge_para_text_blocks_skips_page_auxiliary_blocks_between_ref_text() -> None:
+ """验证跨页 ref_text 会跳过全部页面辅助块查找前序 ref_text。"""
+ previous_block, current_block = _ref_text_horizontal_pair()
+ current_block["index"] = 3
+ pages = [
+ {
+ "page_idx": 8,
+ "blocks": [
+ previous_block,
+ {"index": 1, "type": BlockType.FOOTER, "content": "footer"},
+ {"index": 2, "type": BlockType.PAGE_FOOTNOTE, "content": "page footnote"},
+ ],
+ },
+ {
+ "page_idx": 9,
+ "blocks": [
+ {"index": 0, "type": BlockType.HEADER, "content": "header"},
+ {"index": 1, "type": BlockType.PAGE_NUMBER, "content": "9"},
+ {"index": 2, "type": BlockType.ASIDE_TEXT, "content": "aside"},
+ current_block,
+ ],
+ },
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert current_block["continues_prev"] is True
+
+
+ "barrier_type",
+ [BlockType.TEXT, BlockType.PARAGRAPH_TITLE, BlockType.IMAGE, BlockType.TABLE, BlockType.LIST],
+)
+def test_merge_para_text_blocks_keeps_semantic_barriers_between_ref_text(barrier_type: str) -> None:
+ """验证 ref_text 不能跨越页面辅助类型之外的语义块。"""
+ previous_block, current_block = _ref_text_horizontal_pair()
+ current_block["index"] = 2
+ barrier = {
+ "index": 1,
+ "type": barrier_type,
+ "content": [] if barrier_type == BlockType.LIST else "barrier",
+ }
+ pages = [{"page_idx": 0, "blocks": [previous_block, barrier, current_block]}]
+
+ merge_para_text_blocks(pages)
+
+ assert "continues_prev" not in current_block
+
+
+ ("following_type", "expected_continuation"),
+ [(BlockType.REF_TEXT, True), (BlockType.TEXT, False)],
+)
+def test_ref_text_single_line_lookahead_uses_only_same_type(
+ following_type: str,
+ expected_continuation: bool,
+) -> None:
+ """验证 ref_text 单行只使用当前页后续 ref_text 补足虚拟栏宽。"""
+ previous_block = _horizontal_multiline_block(
+ 0,
+ "unfinished",
+ left=0.55,
+ right=0.9,
+ top=0.5,
+ line_count=4,
+ )
+ current_block = _horizontal_single_line_block(0, "tail.", left=0.1, right=0.22, top=0.1)
+ following_block = _horizontal_multiline_block(
+ 2,
+ "following reference.",
+ left=0.1,
+ right=0.45,
+ top=0.2,
+ )
+ previous_block["type"] = BlockType.REF_TEXT
+ current_block["type"] = BlockType.REF_TEXT
+ following_block["type"] = following_type
+ pages = [
+ {"page_idx": 0, "blocks": [previous_block]},
+ {
+ "page_idx": 1,
+ "blocks": [
+ current_block,
+ {"index": 1, "type": BlockType.PAGE_NUMBER, "content": "2"},
+ following_block,
+ ],
+ },
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert current_block.get("continues_prev", False) is expected_continuation
+
+
+def test_ref_list_and_ref_text_store_independent_continuation_markers() -> None:
+ """验证 xhigh 风格结果中的 ref list 与顶层 ref_text 分别保存续接标记。"""
+ previous_list = _list_block(0, "ref one")
+ current_list = _list_block(1, "ref two")
+ previous_ref_text, current_ref_text = _ref_text_horizontal_pair()
+ previous_ref_text["index"] = 2
+ current_ref_text["index"] = 3
+ pages = [
+ {
+ "page_idx": 0,
+ "blocks": [
+ previous_list,
+ {"index": 1, "type": BlockType.PAGE_FOOTNOTE, "content": "note"},
+ ],
+ },
+ {
+ "page_idx": 1,
+ "blocks": [
+ {"index": 0, "type": BlockType.HEADER, "content": "header"},
+ current_list,
+ previous_ref_text,
+ current_ref_text,
+ ],
+ },
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert current_list["continues_prev"] is True
+ assert current_ref_text["continues_prev"] is True
+ assert "continues_prev" not in previous_list
+ assert "continues_prev" not in previous_ref_text
+
+
def test_merge_para_text_blocks_marks_adjacent_ref_lists_without_moving_items() -> None:
"""验证连续页的相邻参考文献 list 只增加标记,不搬运列表子项。"""
previous_list = {