Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: enhance table merging functionality by refining cross-page detection and improving metadata handling
myhlolic0165ac4929c
diff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.mdindex f5e67219..cd26f425 100644--- a/docs/en/usage/cli_tools.md+++ b/docs/en/usage/cli_tools.md@@ -114,10 +114,6 @@ Here are the environment variables and their descriptions:* Default is `false`, can be set to `true` via environment variable to enable Chinese formula parsing optimization.* Only effective for local Hybrid model execution.-- `MINERU_TABLE_MERGE_ENABLE`:- * Used to enable table merging functionality- * Default is `true`, can be set to `false` via environment variable to disable table merging functionality.-- `MINERU_PDF_RENDER_TIMEOUT`:* Used to set the timeout (in seconds) for rendering PDFs to images.* Default is `300` seconds; you can set a different value via an environment variable to adjust the rendering timeout.diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.mdindex 8c3538d3..cc190f52 100644--- a/docs/zh/usage/cli_tools.md+++ b/docs/zh/usage/cli_tools.md@@ -105,10 +105,6 @@ MinerU命令行工具的某些参数存在相同功能的环境变量配置,* 默认为`false`,可通过环境变量设置为`true`来启用中文公式解析优化。* 仅对本地 Hybrid 模型执行生效。-- `MINERU_TABLE_MERGE_ENABLE`:- * 用于启用表格合并功能- * 默认为`true`,可通过环境变量设置为`false`来禁用表格合并功能。-- `MINERU_PDF_RENDER_TIMEOUT`:* 用于设置将PDF渲染为图片的超时时间(秒)* 默认为`300`秒,可通过环境变量设置为其他值以调整渲染图片的超时时间。diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex df562381..78bb6216 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -2718,14 +2718,15 @@ if __name__ == "__main__":# os.path.join(project_root, "demo", "office_docs", "docx_01.docx"),# os.path.join(project_root, "demo", "pdfs", "NPU_开发环境部署_参考指南.pdf"),# "/Users/myhloli/pdf/png/2407.00079v4_origi-10.pdf",- os.path.join(project_root, "demo", "pdfs", "demo1.pdf"),+ "/Users/myhloli/pdf/跨页表格/跨页单元格3.pdf",+ # os.path.join(project_root, "demo", "pdfs", "demo1.pdf"),]for file_path in demo_file_paths:file_bytes = read_fn(file_path)file_suffix = os.path.splitext(file_path)[1].lstrip(".").lower()file_suffix = "pdf"- middle_json, model_list = doc_analyze(file_bytes, effort="xhigh", file_suffix=file_suffix)+ middle_json, model_list = doc_analyze(file_bytes, effort="high", file_suffix=file_suffix)model_json = json.dumps(model_list, ensure_ascii=False, indent=4)logger.info(f"file_path: {file_path}")logger.info(f"middle_json: {middle_json}")diff --git a/mineru/backend/model_list_to_midlle_json.py b/mineru/backend/model_list_to_midlle_json.pyindex 6cc4a52a..8bd780ad 100644--- a/mineru/backend/model_list_to_midlle_json.py+++ b/mineru/backend/model_list_to_midlle_json.py@@ -4,6 +4,7 @@ from typing import Anyfrom mineru.backend.magic_model import MagicModelfrom mineru.backend.utils.para_block_utils import merge_para_text_blocks+from mineru.backend.utils.table_merge import merge_tabledef blocks_to_page_info(@@ -48,4 +49,5 @@ def model_list_to_pages()if has_bbox_block:merge_para_text_blocks(pages)+ merge_table(pages)return pagesdiff --git a/mineru/backend/pdf/model_output_to_middle_json.py b/mineru/backend/pdf/model_output_to_middle_json.pyindex d2d9ec6b..d3734f46 100644--- a/mineru/backend/pdf/model_output_to_middle_json.py+++ b/mineru/backend/pdf/model_output_to_middle_json.py@@ -13,10 +13,10 @@ from ..utils.para_block_utils import (build_para_blocks_from_preproc,cleanup_internal_para_block_metadata,)-from ..utils.runtime_utils import cross_page_table_mergefrom ..utils.visual_span_utils import cut_visual_spans_in_blocksfrom .magic_model import MagicModel+def blocks_to_page_info(page_model_list: list[dict[str, Any]],image_dict: dict[str, Any],@@ -90,8 +90,6 @@ def finalize_middle_json_from_preproc(pages: list[PageInfo], effort: str = DEFAUbuild_para_blocks_from_preproc(pages)# 段落延续标记已在统一 model_list_to_pages dict 路径完成,此处不再重复处理。- cross_page_table_merge(pages)-apply_title_leveling_to_pdf_info(pages)cleanup_internal_para_block_metadata(pages)diff --git a/mineru/backend/utils/runtime_utils.py b/mineru/backend/utils/runtime_utils.pyindex 8556a401..f93cfdf4 100644--- a/mineru/backend/utils/runtime_utils.py+++ b/mineru/backend/utils/runtime_utils.py@@ -1,34 +1,9 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations-import osimport timefrom typing import Any-from loguru import logger--from ...types import PageInfo-from .table_merge import merge_table---def cross_page_table_merge(pdf_info: list[PageInfo]) -> None:- """Merge tables that span across multiple pages in a PDF document.-- Args:- pdf_info (list[PageInfo]): A list of dictionaries containing information about each page in the PDF.-- Returns:- None- """- is_merge_table = os.getenv("MINERU_TABLE_MERGE_ENABLE", "true")- if is_merge_table.lower() in ["true", "1", "yes"]:- merge_table(pdf_info)- elif is_merge_table.lower() in ["false", "0", "no"]:- pass- else:- logger.warning(f"unknown MINERU_TABLE_MERGE_ENABLE config: {is_merge_table}, pass")- pass-def exclude_progress_bar_idle_time(progress_bar: Any, idle_since: float | None, now: float | None = None) -> float | None:"""Exclude non-processing idle time from a reused tqdm progress bar."""diff --git a/mineru/backend/utils/table_merge.py b/mineru/backend/utils/table_merge.pyindex 91428cbd..083f2909 100644--- a/mineru/backend/utils/table_merge.py+++ b/mineru/backend/utils/table_merge.py@@ -1,19 +1,35 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations+import mathfrom copy import deepcopyfrom dataclasses import dataclass-from typing import Any+from typing import Any, TypeAliasfrom bs4 import BeautifulSoup, Tag-from ...render.merge import merge_para_text-from ...types import BBox, Block, BlockType, PageInfo, Span+from ...types import BlockTypefrom .char_utils import full_to_halffrom .table_continuation import is_table_continuation_textMAX_HEADER_ROWS = 5+# 页边界扫描时可忽略的版面噪声块;其余非表格块都会阻断跨页关系。+TABLE_BOUNDARY_IGNORED_TYPES = {+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.PAGE_FOOTNOTE,+ BlockType.ASIDE_TEXT,+ BlockType.HEADER_IMAGE,+ BlockType.FOOTER_IMAGE,+ BlockType.DISCARDED,+}++BlockDict: TypeAlias = dict[str, Any]+PageInfoDict: TypeAlias = dict[str, Any]+CalculationBBox: TypeAlias = tuple[int, int, int, int]+@dataclassclass RowMetrics:@@ -54,8 +70,8 @@ class RowScanResult:@dataclassclass TableMergeState:- owner_block: Block- body_span: Span+ owner_block: BlockDict | None+ body_block: BlockDict | Nonesoup: Anytbody: Anyrows: list[Any]@@ -69,22 +85,26 @@ class TableMergeState:def _colspan(cell: Any) -> int:+ """读取 HTML 单元格 colspan,非法值交由上层安全降级。"""val = cell.get("colspan", "1")assert isinstance(val, str)return int(val)def _rowspan(cell: Any) -> int:+ """读取 HTML 单元格 rowspan,非法值交由上层安全降级。"""val = cell.get("rowspan", "1")assert isinstance(val, str)return int(val)def _normalize_cell_text(cell: Tag) -> str:+ """生成表头匹配使用的半角无空白文本。"""return "".join(full_to_half(cell.get_text()).split())def _display_cell_text(cell: Tag) -> str:+ """生成保留内部空白的半角展示文本。"""return full_to_half(cell.get_text().strip())@@ -158,6 +178,7 @@ def _scan_rows(rows: list[Tag], initial_occupied: dict[int, set[int]] | None = Ndef _build_row_signature(row: Tag, effective_cols: int) -> RowSignature:+ """构建表头检测使用的行结构与文本签名。"""cells = row.find_all(["td", "th"])return RowSignature(effective_cols=effective_cols,@@ -171,6 +192,7 @@ def _build_row_signature(row: Tag, effective_cols: int) -> RowSignature:def _build_front_cache(rows: list[Tag], max_header_rows: int = MAX_HEADER_ROWS) -> tuple[list[RowSignature], dict[int, RowMetrics]]:+ """缓存表格前部表头签名和首批数据行指标。"""front_limit = min(len(rows), max_header_rows + 1)front_rows = rows[:front_limit]front_scan = _scan_rows(front_rows)@@ -183,40 +205,72 @@ def _build_front_cache(return front_header_info, front_first_data_row_metrics-def _find_table_body_block(table_block: Block) -> Block | None:- """查找 table block 中的主体子块。"""- for block in table_block.blocks:- if block.type == BlockType.TABLE_BODY:+def _bbox_for_calculation(bbox: Any) -> CalculationBBox | None:+ """复制归一化 bbox 并放大为千分位整数,原始字段保持不变。"""+ if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:+ return None+ if any(isinstance(value, bool) or not isinstance(value, (int, float)) for value in bbox):+ return None++ values = tuple(float(value) for value in bbox)+ if not all(math.isfinite(value) and 0 <= value <= 1 for value in values):+ return None++ x0, y0, x1, y1 = (int(round(value * 1000)) for value in values)+ if x1 <= x0 or y1 <= y0:+ return None+ return x0, y0, x1, y1+++def _table_children(table_block: BlockDict) -> list[BlockDict]:+ """读取 table 根块下的合法 dict 子块。"""+ content = table_block.get("content")+ if not isinstance(content, list):+ return []+ return [block for block in content if isinstance(block, dict)]+++def _find_table_body_block(table_block: BlockDict) -> BlockDict | None:+ """查找 dict table block 中的主体子块。"""+ for block in _table_children(table_block):+ if block.get("type") == BlockType.TABLE_BODY:return blockreturn None-def _build_post_body_child_index(table_block: Block, offset: int) -> int | None:- """为跨页搬运到上一页表格的子块生成表体后的安全 index。"""+def _build_post_body_child_index(table_block: BlockDict, offset: int) -> int | None:+ """为复制到前表的 footnote 生成表体后的安全 index。"""body_block = _find_table_body_block(table_block)if body_block is None:return None- body_index = body_block.index- return body_index + offset+ body_index = body_block.get("index")+ if not isinstance(body_index, int):+ return None+ child_indices = [block.get("index") for block in _table_children(table_block) if isinstance(block.get("index"), int)]+ return max([body_index, *child_indices]) + offset-def _find_table_body_span(table_block: Block) -> Span | None:- body_block = _find_table_body_block(table_block)- if body_block and body_block.lines and body_block.lines[0].spans:- return body_block.lines[0].spans[0]- return None+def _block_text(block: BlockDict) -> str:+ """递归读取 dict block 的文本内容,供续表标记判断使用。"""+ content = block.get("content")+ if isinstance(content, str):+ return content+ if not isinstance(content, list):+ return ""+ return "".join(_block_text(child) for child in content if isinstance(child, dict))-def _is_continuation_caption(caption_block: Block) -> bool:- """判断 caption 文本是否带有续表标记。"""- return is_table_continuation_text(merge_para_text(caption_block))+def _is_continuation_caption(caption_block: BlockDict) -> bool:+ """判断 dict caption 文本是否带有续表标记。"""+ return is_table_continuation_text(_block_text(caption_block))-def _is_post_table_non_continuation_caption(table_block: Block, caption_block: Block) -> bool:++def _is_post_table_non_continuation_caption(table_block: BlockDict, caption_block: BlockDict) -> bool:"""判断 caption 是否是误挂到表格下方的新段落标题。这类 caption 位于 table body 下方,且不含续表标记;它不应作为- 当前表的新标题阻断跨页合并,后续会被恢复成独立 text block。+ 当前表的新标题阻断跨页关系判断。"""if _is_continuation_caption(caption_block):return False@@ -225,46 +279,16 @@ def _is_post_table_non_continuation_caption(table_block: Block, caption_block: Bif body_block is None:return False- body_bbox = body_block.bbox- caption_bbox = caption_block.bbox- if not body_bbox or not caption_bbox:+ body_bbox = _bbox_for_calculation(body_block.get("bbox"))+ caption_bbox = _bbox_for_calculation(caption_block.get("bbox"))+ if body_bbox is None or caption_bbox is None:return Falsereturn caption_bbox[1] >= body_bbox[3]-def _get_post_table_caption_blocks(table_block: Block) -> list[Block]:- """收集当前表格下方、需要恢复为普通文本的非续表 caption。"""- return [- block- for block in table_block.blocks- if block.type == BlockType.TABLE_CAPTION and _is_post_table_non_continuation_caption(table_block, block)- ]---def _restore_post_table_captions_as_text(page_info: PageInfo, table_block: Block, caption_blocks: list[Block]) -> None:- """将误挂到表格下方的 caption 迁回当前页,作为独立 text block 输出。"""- if not caption_blocks:- return-- para_blocks = page_info.para_blocks- try:- insert_idx = para_blocks.index(table_block) + 1- except ValueError:- return-- restored_blocks = []- for caption_block in caption_blocks:- text_block = deepcopy(caption_block)- text_block.type = BlockType.TEXT- restored_blocks.append(text_block)-- para_blocks[insert_idx:insert_idx] = restored_blocks- restored_caption_ids = {id(block) for block in caption_blocks}- table_block.blocks = [block for block in table_block.blocks if id(block) not in restored_caption_ids]--def _refresh_table_state_metrics(state: TableMergeState) -> None:+ """HTML 结构调整后重新计算表格状态指标。"""scan = _scan_rows(state.rows)state.row_effective_cols = scan.row_effective_colsstate.total_cols = scan.total_cols@@ -280,7 +304,7 @@ def build_table_state_from_html("""从原始 HTML 构建 TableMergeState,不依赖 MinerU block 结构。供外部工具(如 mineru-vl-utils)调用,用于跨页表格结构检测。- 返回的 state 仅可用于 can_merge_by_structure(),不可传入 can_merge_tables()。+ 返回的 state 供 HTML-only 结构 helper 使用,不包含 MinerU block 所有者。"""if not html:return None@@ -288,15 +312,23 @@ def build_table_state_from_html(soup = BeautifulSoup(html, "html.parser")tbody = soup.find("tbody") or soup.find("table")rows = soup.find_all("tr")- if not rows:+ if tbody is None or not rows:return None- scan = _scan_rows(rows)- front_header_info, front_first_data_row_metrics = _build_front_cache(rows, max_header_rows=max_header_rows)+ try:+ scan = _scan_rows(rows)+ front_header_info, front_first_data_row_metrics = _build_front_cache(+ rows,+ max_header_rows=max_header_rows,+ )+ except (AssertionError, TypeError, ValueError):+ return None+ if scan.total_cols <= 0 or scan.last_nonempty_row_metrics is None:+ return Nonereturn TableMergeState(- owner_block={},- body_span={},+ owner_block=None,+ body_block=None,soup=soup,tbody=tbody,rows=rows,@@ -309,24 +341,30 @@ def build_table_state_from_html()-def _build_table_state(table_block: Block, max_header_rows: int = MAX_HEADER_ROWS) -> TableMergeState | None:- body_span = _find_table_body_span(table_block)- if body_span is None:+def _build_table_state(table_block: BlockDict, max_header_rows: int = MAX_HEADER_ROWS) -> TableMergeState | None:+ """从 dict table block 构建结构缓存,非法主体安全返回空。"""+ body_block = _find_table_body_block(table_block)+ if body_block is None:return None- html = body_span.content- if not html:+ html = body_block.get("content")+ if not isinstance(html, str) or not html:return Nonesoup = BeautifulSoup(html, "html.parser")tbody = soup.find("tbody") or soup.find("table")rows = soup.find_all("tr")+ if tbody is None or not rows:+ return None+scan = _scan_rows(rows)+ if scan.total_cols <= 0 or scan.last_nonempty_row_metrics is None:+ return Nonefront_header_info, front_first_data_row_metrics = _build_front_cache(rows, max_header_rows=max_header_rows)return TableMergeState(owner_block=table_block,- body_span=body_span,+ body_block=body_block,soup=soup,tbody=tbody,rows=rows,@@ -340,24 +378,32 @@ def _build_table_state(table_block: Block, max_header_rows: int = MAX_HEADER_ROWdef _get_or_create_table_state(- table_block: Block,+ table_block: BlockDict,state_cache: dict[int, TableMergeState],max_header_rows: int = MAX_HEADER_ROWS,) -> TableMergeState | None:+ """按 table dict 对象身份复用 HTML 结构扫描结果。"""cache_key = id(table_block)state = state_cache.get(cache_key)if state is not None:return state- state = _build_table_state(table_block, max_header_rows=max_header_rows)+ try:+ state = _build_table_state(table_block, max_header_rows=max_header_rows)+ except (AssertionError, TypeError, ValueError):+ return Noneif state is not None:state_cache[cache_key] = statereturn state-def _serialize_table_state_html(state: TableMergeState) -> None:- state.body_span.content = str(state.soup)+def _serialize_table_state_html(state: TableMergeState) -> bool:+ """将合并后的 BeautifulSoup 写回克隆表体,缺失表体时返回失败。"""+ if state.body_block is None:+ return False+ state.body_block["content"] = str(state.soup)state.dirty = False+ return Truedef calculate_table_total_columns(soup: BeautifulSoup) -> int:@@ -660,21 +706,30 @@ def _expand_header_count_by_rowspan(rows: list[Tag], header_count: int) -> int:def can_merge_by_structure(current_state: TableMergeState,previous_state: TableMergeState,- current_bbox: BBox | None = None,- previous_bbox: BBox | None = None,+ current_bbox: Any = None,+ previous_bbox: Any = None,) -> bool:"""仅基于表格结构判断是否可合并(不检查 caption/footnote)。供外部工具调用,忽略 caption 和 footnote 检查。"""- if current_bbox is not None and previous_bbox is not None:- x0_t1, _, x1_t1, _ = current_bbox- x0_t2, _, x1_t2, _ = previous_bbox- table1_width = x1_t1 - x0_t1- table2_width = x1_t2 - x0_t2- if table1_width > 0 and table2_width > 0:- if abs(table1_width - table2_width) / min(table1_width, table2_width) >= 0.1:- return False+ if (+ current_bbox is not None+ and previous_bbox is not None+ and not _table_widths_are_compatible(+ current_bbox,+ previous_bbox,+ )+ ):+ return False++ if (+ previous_state.total_cols <= 0+ or current_state.total_cols <= 0+ or previous_state.last_data_row_metrics is None+ or current_state.last_data_row_metrics is None+ ):+ return Falseif previous_state.total_cols == current_state.total_cols:return True@@ -682,19 +737,31 @@ def can_merge_by_structure(return check_rows_match(previous_state, current_state)+def _table_widths_are_compatible(current_bbox: Any, previous_bbox: Any) -> bool:+ """使用千分位 bbox 判断两张表的宽度相对差是否小于百分之十。"""+ current_calc_bbox = _bbox_for_calculation(current_bbox)+ previous_calc_bbox = _bbox_for_calculation(previous_bbox)+ if current_calc_bbox is None or previous_calc_bbox is None:+ return False++ current_width = current_calc_bbox[2] - current_calc_bbox[0]+ previous_width = previous_calc_bbox[2] - previous_calc_bbox[0]+ min_width = min(current_width, previous_width)+ return min_width > 0 and abs(current_width - previous_width) / min_width < 0.1++def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeState) -> bool:- """判断两个表格是否可以合并."""+ """根据 dict 表格的辅助文本、宽度和 HTML 结构判断是否可合并。"""current_table_block = current_state.owner_blockprevious_table_block = previous_state.owner_block- if not isinstance(previous_table_block, Block) or not isinstance(current_table_block, Block):- raise ValueError(- "can_merge_tables() requires owner_block to be a Block instance. "- "For HTML-only states from build_table_state_from_html(), use can_merge_by_structure() instead."- )+ if not isinstance(previous_table_block, dict) or not isinstance(current_table_block, dict):+ return False- footnote_count = sum(1 for block in previous_table_block.blocks if block.type == BlockType.TABLE_FOOTNOTE)- caption_blocks = [block for block in current_table_block.blocks if block.type == BlockType.TABLE_CAPTION]+ previous_children = _table_children(previous_table_block)+ current_children = _table_children(current_table_block)+ footnote_count = sum(1 for block in previous_children if block.get("type") == BlockType.TABLE_FOOTNOTE)+ caption_blocks = [block for block in current_children if block.get("type") == BlockType.TABLE_CAPTION]merge_caption_blocks = [block for block in caption_blocks if not _is_post_table_non_continuation_caption(current_table_block, block)]@@ -709,18 +776,10 @@ def can_merge_tables(current_state: TableMergeState, previous_state: TableMergeSelif footnote_count > 0:return False- x0_t1, _, x1_t1, _ = current_table_block.bbox- x0_t2, _, x1_t2, _ = previous_table_block.bbox- table1_width = x1_t1 - x0_t1- table2_width = x1_t2 - x0_t2-- if abs(table1_width - table2_width) / min(table1_width, table2_width) >= 0.1:+ if not _table_widths_are_compatible(current_table_block.get("bbox"), previous_table_block.get("bbox")):return False- if previous_state.total_cols == current_state.total_cols:- return True-- return check_rows_match(previous_state, current_state)+ return can_merge_by_structure(current_state, previous_state)def check_rows_match(previous_state: TableMergeState, current_state: TableMergeState) -> bool:@@ -746,6 +805,7 @@ def check_rows_match(previous_state: TableMergeState, current_state: TableMergeSdef check_row_columns_match(row1: Tag, row2: Tag) -> bool:+ """判断两行显式单元格数量与 colspan 结构是否一致。"""cells1 = row1.find_all(["td", "th"])cells2 = row2.find_all(["td", "th"])if len(cells1) != len(cells2):@@ -925,7 +985,7 @@ def _apply_cell_merge(previous_state: TableMergeState,current_state: TableMergeState,header_count: int,-) -> None:+) -> bool:"""应用 cell_merge 语义合并。当 cell_merge 中的值为 1 时,将下表第一数据行对应单元格的内容@@ -936,19 +996,19 @@ def _apply_cell_merge(两个表格中可能因 rowspan 而具有不同 <td> 元素数量的行。元数据仅从当前页 table body 读取,不依赖外层 table block。"""- current_body_block = _find_table_body_block(current_state.owner_block)- if current_body_block is None:- return+ current_body_block = current_state.body_block+ if not isinstance(current_body_block, dict):+ return False- cell_merge = current_body_block._cell_merge- if not cell_merge:- return+ cell_merge = current_body_block.get("cell_merge")+ if not isinstance(cell_merge, list) or not cell_merge:+ return Falserows2 = current_state.rowsif header_count >= len(rows2):- return+ return Falseif not previous_state.rows:- return+ return Falsefirst_data_row = rows2[header_count]last_row = previous_state.rows[-1]@@ -1007,19 +1067,23 @@ def _apply_cell_merge(if first_data_row in rows2:rows2.remove(first_data_row)+ return bool(transferred_pairs)+-def perform_table_merge(+def _perform_table_content_merge(previous_state: TableMergeState,current_state: TableMergeState,- previous_table_block: Block,- wait_merge_table_footnotes: list[Block],-) -> None:- """执行表格合并操作."""+ previous_table_block: BlockDict,+ current_table_block: BlockDict,+) -> bool:+ """在两个克隆表格上执行 HTML、单元格和 footnote 的内容合并。"""header_count, _, _ = detect_table_headers(previous_state, current_state)header_count = _expand_header_count_by_rowspan(current_state.rows, header_count)rows1 = previous_state.rowsrows2 = current_state.rows+ if not rows1 or header_count >= len(rows2):+ return Falseprevious_adjusted = False@@ -1065,17 +1129,22 @@ def perform_table_merge(if previous_adjusted:_refresh_table_state_metrics(previous_state)- _apply_cell_merge(previous_state, current_state, header_count)+ cell_merge_applied = _apply_cell_merge(previous_state, current_state, header_count)appended_rows = rows2[header_count:]append_start_idx = len(previous_state.rows)merged_rows = []- if previous_state.tbody and current_state.tbody:- for row in appended_rows:- row.extract()- previous_state.tbody.append(row)- merged_rows.append(row)+ if previous_state.tbody is None or current_state.tbody is None:+ return False++ for row in appended_rows:+ row.extract()+ previous_state.tbody.append(row)+ merged_rows.append(row)++ if not merged_rows and not cell_merge_applied:+ return Falseprevious_state.rows.extend(merged_rows)@@ -1091,69 +1160,152 @@ def perform_table_merge(previous_state.last_data_row_metrics = appended_scan.last_nonempty_row_metricsprevious_state.tail_occupied = appended_scan.tail_occupied- previous_table_block.blocks = [block for block in previous_table_block.blocks if block.type != BlockType.TABLE_FOOTNOTE]- for footnote_offset, table_footnote in enumerate(wait_merge_table_footnotes, start=1):+ previous_content = previous_table_block.get("content")+ if not isinstance(previous_content, list):+ return False++ previous_table_block["content"] = [+ block for block in previous_content if not isinstance(block, dict) or block.get("type") != BlockType.TABLE_FOOTNOTE+ ]+ current_footnotes = [+ block for block in _table_children(current_table_block) if block.get("type") == BlockType.TABLE_FOOTNOTE+ ]+ footnote_base_index = _build_post_body_child_index(previous_table_block, 0)+ for footnote_offset, table_footnote in enumerate(current_footnotes, start=1):temp_table_footnote = deepcopy(table_footnote)- temp_table_footnote._cross_page = True- post_body_index = _build_post_body_child_index(previous_table_block, footnote_offset)- if post_body_index is None:- temp_table_footnote.index = 0+ temp_table_footnote.pop("_cross_page", None)+ if footnote_base_index is None:+ temp_table_footnote["index"] = 0else:- temp_table_footnote.index = post_body_index- previous_table_block.blocks.append(temp_table_footnote)+ temp_table_footnote["index"] = footnote_base_index + footnote_offset+ previous_table_block["content"].append(temp_table_footnote)previous_state.dirty = True+ return _serialize_table_state_html(previous_state)-def merge_table(page_info_list: list[PageInfo]) -> None:- """合并跨页表格."""- state_cache: dict[int, TableMergeState] = {}- merged_away_blocks: set[int] = set()+def merge_table_content(previous_table: BlockDict, current_table: BlockDict) -> BlockDict | None:+ """纯函数式合并两张跨页表格的内容,失败时返回 ``None``。- for page_idx in range(len(page_info_list) - 1, -1, -1):- if page_idx == 0:+ 两个输入都会先深拷贝;返回块保留前表外层信息,只改克隆表体 HTML+ 并用当前表 footnote 替换前表 footnote,不会修改任何输入对象。+ """+ if (+ not isinstance(previous_table, dict)+ or not isinstance(current_table, dict)+ or previous_table.get("type") != BlockType.TABLE+ or current_table.get("type") != BlockType.TABLE+ ):+ return None++ previous_clone = deepcopy(previous_table)+ current_clone = deepcopy(current_table)+ try:+ previous_state = _build_table_state(previous_clone)+ current_state = _build_table_state(current_clone)+ if previous_state is None or current_state is None:+ return None+ if not can_merge_tables(current_state, previous_state):+ return None+ if not _perform_table_content_merge(+ previous_state,+ current_state,+ previous_clone,+ current_clone,+ ):+ return None+ except (AssertionError, TypeError, ValueError):+ return None++ return previous_clone+++def _clear_table_continuation_marker(table_block: BlockDict) -> None:+ """递归清除 table 根块及其子块中过期的 ``continues_prev``。"""+ table_block.pop("continues_prev", None)+ content = table_block.get("content")+ if not isinstance(content, list):+ return+ for child in content:+ if isinstance(child, dict):+ child.pop("continues_prev", None)+ _clear_nested_continuation_markers(child)+++def _clear_nested_continuation_markers(block: BlockDict) -> None:+ """清除表格子树中的旧延续标记,避免标记落到嵌套子块。"""+ content = block.get("content")+ if not isinstance(content, list):+ return+ for child in content:+ if isinstance(child, dict):+ child.pop("continues_prev", None)+ _clear_nested_continuation_markers(child)+++def _find_boundary_table(blocks: list[Any], *, from_end: bool) -> BlockDict | None:+ """从页边界扫描 table;噪声块可跳过,其他语义块立即阻断。"""+ ordered_blocks = reversed(blocks) if from_end else iter(blocks)+ for block in ordered_blocks:+ if not isinstance(block, dict):+ return None+ block_type = block.get("type")+ if block_type in TABLE_BOUNDARY_IGNORED_TYPES:+ continue+ if block_type == BlockType.TABLE:+ return block+ return None+ return None+++def _is_consecutive_page_pair(previous_page: PageInfoDict, current_page: PageInfoDict) -> bool:+ """按显式零基 page_idx 判断页面在文档中是否严格连续。"""+ previous_page_idx = previous_page.get("page_idx")+ current_page_idx = current_page.get("page_idx")+ return type(previous_page_idx) is int and type(current_page_idx) is int and current_page_idx == previous_page_idx + 1+++def merge_table(page_info_list: list[PageInfoDict]) -> None:+ """倒序识别连续页边界表格,并只在后表写入延续标记。"""+ if not isinstance(page_info_list, list):+ return++ for page_info in page_info_list:+ if not isinstance(page_info, dict):continue+ blocks = page_info.get("blocks")+ if not isinstance(blocks, list):+ continue+ for block in blocks:+ if isinstance(block, dict) and block.get("type") == BlockType.TABLE:+ _clear_table_continuation_marker(block)- page_info = page_info_list[page_idx]- previous_page_info = page_info_list[page_idx - 1]+ state_cache: dict[int, TableMergeState] = {}- if not (page_info.para_blocks and page_info.para_blocks[0].type == BlockType.TABLE):+ for page_position in range(len(page_info_list) - 1, 0, -1):+ current_page = page_info_list[page_position]+ previous_page = page_info_list[page_position - 1]+ if not isinstance(current_page, dict) or not isinstance(previous_page, dict):+ continue+ if not _is_consecutive_page_pair(previous_page, current_page):continue- if not (previous_page_info.para_blocks and previous_page_info.para_blocks[-1].type == BlockType.TABLE):+ current_blocks = current_page.get("blocks")+ previous_blocks = previous_page.get("blocks")+ if not isinstance(current_blocks, list) or not isinstance(previous_blocks, list):continue- current_table_block = page_info.para_blocks[0]- previous_table_block = previous_page_info.para_blocks[-1]+ current_table_block = _find_boundary_table(current_blocks, from_end=False)+ previous_table_block = _find_boundary_table(previous_blocks, from_end=True)+ if current_table_block is None or previous_table_block is None:+ continuecurrent_state = _get_or_create_table_state(current_table_block, state_cache)previous_state = _get_or_create_table_state(previous_table_block, state_cache)if current_state is None or previous_state is None:continue- post_table_caption_blocks = _get_post_table_caption_blocks(current_table_block)- wait_merge_table_footnotes = [block for block in current_table_block.blocks if block.type == BlockType.TABLE_FOOTNOTE]-if not can_merge_tables(current_state, previous_state):continue- perform_table_merge(- previous_state,- current_state,- previous_table_block,- wait_merge_table_footnotes,- )- _restore_post_table_captions_as_text(- page_info,- current_table_block,- post_table_caption_blocks,- )-- merged_away_blocks.add(id(current_table_block))- for block in current_table_block.blocks:- block.lines = []- block._lines_deleted = True-- for state in state_cache.values():- if state.dirty and id(state.owner_block) not in merged_away_blocks:- _serialize_table_state_html(state)+ current_table_block["continues_prev"] = Truediff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.pyindex 46cf4945..f0694c17 100644--- a/mineru/model/vlm/runtime.py+++ b/mineru/model/vlm/runtime.py@@ -243,7 +243,7 @@ class ModelSingleton:retry_backoff_factor=retry_backoff_factor,enable_table_formula_eq_wrap=True,image_analysis=True,- enable_cross_page_table_merge=False,+ enable_cross_page_table_merge=True,)predictor._mineru_runtime_handles = {"backend": backend,diff --git a/tests/unittest/test_model_list_to_midlle_json.py b/tests/unittest/test_model_list_to_midlle_json.pyindex 8447441f..03633793 100644--- a/tests/unittest/test_model_list_to_midlle_json.py+++ b/tests/unittest/test_model_list_to_midlle_json.py@@ -238,3 +238,50 @@ def test_model_list_to_pages_detects_pdf_after_empty_first_page() -> None:assert pages[0] == {"blocks": [], "page_idx": 0}assert "lines" not in pages[1]["blocks"][0]+++def test_model_list_to_pages_marks_only_later_boundary_table() -> None:+ """验证 PDF 统一入口只给连续页的后表写入 continues_prev。"""+ previous_html = "<table><tr><td>A</td><td>B</td></tr></table>"+ current_html = "<table><tr><td>C</td><td>D</td></tr></table>"+ model_list = [+ [+ {"type": BlockType.HEADER, "bbox": [0.1, 0.01, 0.9, 0.03], "content": "header"},+ {"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.85], "content": previous_html},+ {"type": BlockType.PAGE_NUMBER, "bbox": [0.45, 0.95, 0.55, 0.98], "content": "1"},+ ],+ [+ {"type": BlockType.HEADER, "bbox": [0.1, 0.01, 0.9, 0.03], "content": "header"},+ {"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.85], "content": current_html},+ {"type": BlockType.PAGE_NUMBER, "bbox": [0.45, 0.95, 0.55, 0.98], "content": "2"},+ ],+ ]+ original_model_list = deepcopy(model_list)++ pages = model_list_to_pages(model_list)++ previous_table = next(block for block in pages[0]["blocks"] if block["type"] == BlockType.TABLE)+ current_table = next(block for block in pages[1]["blocks"] if block["type"] == BlockType.TABLE)+ previous_body = next(block for block in previous_table["content"] if block["type"] == BlockType.TABLE_BODY)+ current_body = next(block for block in current_table["content"] if block["type"] == BlockType.TABLE_BODY)+ assert "continues_prev" not in previous_table+ assert current_table["continues_prev"] is True+ assert "continues_prev" not in current_body+ assert previous_body["content"] == previous_html+ assert current_body["content"] == current_html+ assert previous_table["bbox"] == [0.1, 0.1, 0.9, 0.85]+ assert current_table["bbox"] == [0.1, 0.1, 0.9, 0.85]+ assert model_list == original_model_list+++def test_model_list_to_pages_does_not_mark_table_across_page_index_gap() -> None:+ """验证统一入口会把 page_index_map 跳页传递给跨页表格判断。"""+ model_list = [+ [{"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.85], "content": "<table><tr><td>A</td></tr></table>"}],+ [{"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.85], "content": "<table><tr><td>B</td></tr></table>"}],+ ]++ pages = model_list_to_pages(model_list, page_index_map=[0, 2])++ current_table = next(block for block in pages[1]["blocks"] if block["type"] == BlockType.TABLE)+ assert "continues_prev" not in current_tablediff --git a/tests/unittest/test_table_merge.py b/tests/unittest/test_table_merge.pynew file mode 100644index 00000000..488b542c--- /dev/null+++ b/tests/unittest/test_table_merge.py@@ -0,0 +1,396 @@+from __future__ import annotations++from copy import deepcopy+from typing import Any++import pytest+from bs4 import BeautifulSoup++from mineru.backend.utils.table_merge import merge_table, merge_table_content+from mineru.types import BlockType+++DEFAULT_HTML = "<table><tr><td>A</td><td>B</td></tr></table>"+++def _table_body(+ html: str = DEFAULT_HTML,+ *,+ index: int = 0,+ bbox: list[float] | None = None,+ cell_merge: list[int] | None = None,+) -> dict[str, Any]:+ """构造归一化 bbox 的 table body 测试块。"""+ body: dict[str, Any] = {+ "type": BlockType.TABLE_BODY,+ "index": index,+ "bbox": deepcopy(bbox or [0.1, 0.1, 0.9, 0.9]),+ "content": html,+ }+ if cell_merge is not None:+ body["cell_merge"] = cell_merge+ return body+++def _caption(+ text: str,+ *,+ index: int = 0,+ bbox: list[float] | None = None,+) -> dict[str, Any]:+ """构造 table caption 测试块。"""+ return {+ "type": BlockType.TABLE_CAPTION,+ "index": index,+ "bbox": deepcopy(bbox or [0.1, 0.05, 0.9, 0.08]),+ "content": text,+ }+++def _footnote(text: str, *, index: int = 1) -> dict[str, Any]:+ """构造 table footnote 测试块。"""+ return {+ "type": BlockType.TABLE_FOOTNOTE,+ "index": index,+ "bbox": [0.1, 0.91, 0.9, 0.95],+ "content": text,+ }+++def _table(+ index: int,+ html: str = DEFAULT_HTML,+ *,+ bbox: list[float] | None = None,+ children: list[dict[str, Any]] | None = None,+ cell_merge: list[int] | None = None,+) -> dict[str, Any]:+ """构造两层 dict table 测试块。"""+ table_bbox = deepcopy(bbox or [0.1, 0.1, 0.9, 0.9])+ body = _table_body(+ html,+ index=index,+ bbox=table_bbox,+ cell_merge=cell_merge,+ )+ return {+ "type": BlockType.TABLE,+ "index": index,+ "bbox": table_bbox,+ "content": children if children is not None else [body],+ }+++def _page(page_idx: int, blocks: list[dict[str, Any]]) -> dict[str, Any]:+ """构造 model_list_to_pages 输出契约的页面。"""+ return {"page_idx": page_idx, "blocks": blocks}+++def _noise(block_type: str) -> dict[str, Any]:+ """构造页边界可忽略的噪声块。"""+ return {+ "type": block_type,+ "index": 99,+ "bbox": [0.1, 0.01, 0.9, 0.03],+ "content": "noise",+ }+++def _merged_soup(table: dict[str, Any]) -> BeautifulSoup:+ """读取合并结果中的 table body HTML。"""+ body = next(child for child in table["content"] if child["type"] == BlockType.TABLE_BODY)+ return BeautifulSoup(body["content"], "html.parser")+++def _row_texts(table: dict[str, Any]) -> list[list[str]]:+ """提取合并 HTML 的逐行单元格文本。"""+ return [[cell.get_text() for cell in row.find_all(["td", "th"])] for row in _merged_soup(table).find_all("tr")]+++def test_merge_table_marks_reverse_multi_page_chain_and_cleans_stale_markers() -> None:+ """验证多页链倒序识别,并清理根块及子块的过期标记。"""+ tables = [_table(index) for index in range(3)]+ tables[0]["continues_prev"] = True+ tables[0]["content"][0]["continues_prev"] = True+ pages = [_page(index, [table]) for index, table in enumerate(tables)]++ merge_table(pages)++ assert "continues_prev" not in tables[0]+ assert "continues_prev" not in tables[0]["content"][0]+ assert tables[1]["continues_prev"] is True+ assert tables[2]["continues_prev"] is True++ merge_table(pages)+ assert tables[1]["continues_prev"] is True+ assert tables[2]["continues_prev"] is True++[email protected]("page_indices", [(0, 2), (2, 1)])+def test_merge_table_requires_consecutive_increasing_page_indices(+ page_indices: tuple[int, int],+) -> None:+ """验证跳页和逆序 page_idx 都不会建立跨页关系。"""+ previous_table = _table(0)+ current_table = _table(1)++ merge_table(+ [+ _page(page_indices[0], [previous_table]),+ _page(page_indices[1], [current_table]),+ ]+ )++ assert "continues_prev" not in current_table+++ "block_type",+ [+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.PAGE_FOOTNOTE,+ BlockType.ASIDE_TEXT,+ BlockType.HEADER_IMAGE,+ BlockType.FOOTER_IMAGE,+ BlockType.DISCARDED,+ ],+)+def test_merge_table_skips_boundary_noise(block_type: str) -> None:+ """验证指定页眉页脚类块不会阻断边界 table 扫描。"""+ previous_table = _table(0)+ current_table = _table(1)+ pages = [+ _page(0, [previous_table, _noise(block_type)]),+ _page(1, [_noise(block_type), current_table]),+ ]++ merge_table(pages)++ assert current_table["continues_prev"] is True++[email protected]("barrier_side", ["previous", "current"])+def test_merge_table_is_blocked_by_boundary_semantic_block(barrier_side: str) -> None:+ """验证普通正文位于页边界时会阻断 table 关系。"""+ previous_table = _table(0)+ current_table = _table(1)+ text = _noise(BlockType.TEXT)+ previous_blocks = [previous_table, text] if barrier_side == "previous" else [previous_table]+ current_blocks = [text, current_table] if barrier_side == "current" else [current_table]++ merge_table([_page(0, previous_blocks), _page(1, current_blocks)])++ assert "continues_prev" not in current_table+++ ("previous_footnotes", "current_caption", "expected"),+ [+ (0, None, True),+ (0, "Table 1", False),+ (0, "Table 1 (continued)", True),+ (1, None, False),+ (1, "Table 1 (continued)", True),+ (2, "Table 1 (continued)", False),+ ],+)+def test_merge_table_applies_caption_and_footnote_rules(+ previous_footnotes: int,+ current_caption: str | None,+ expected: bool,+) -> None:+ """验证续表 caption 与前表 footnote 的组合规则。"""+ previous_children = [_table_body()]+ previous_children.extend(_footnote(f"old-{index}", index=index + 1) for index in range(previous_footnotes))+ current_children = [_table_body(index=1)]+ if current_caption is not None:+ current_children.insert(0, _caption(current_caption))+ previous_table = _table(0, children=previous_children)+ current_table = _table(1, children=current_children)++ merge_table([_page(0, [previous_table]), _page(1, [current_table])])++ assert current_table.get("continues_prev", False) is expected+++def test_post_table_non_continuation_caption_does_not_block_merge() -> None:+ """验证 table body 下方的非续表 caption 不参与阻断判断。"""+ current_children = [+ _table_body(index=1, bbox=[0.1, 0.1, 0.9, 0.7]),+ _caption("Next section", index=2, bbox=[0.1, 0.75, 0.9, 0.8]),+ ]+ current_table = _table(1, children=current_children)++ merge_table([_page(0, [_table(0)]), _page(1, [current_table])])++ assert current_table["continues_prev"] is True+++def test_merge_table_enforces_strict_ten_percent_width_threshold() -> None:+ """验证宽度差恰好百分之十时拒绝,小于阈值时接受。"""+ previous_table = _table(0, bbox=[0.1, 0.1, 0.9, 0.9])+ exact_threshold = _table(1, bbox=[0.06, 0.1, 0.94, 0.9])+ pages = [_page(0, [previous_table]), _page(1, [exact_threshold])]++ merge_table(pages)+ assert "continues_prev" not in exact_threshold++ exact_threshold["bbox"] = [0.08, 0.1, 0.92, 0.9]+ exact_threshold["content"][0]["bbox"] = [0.08, 0.1, 0.92, 0.9]+ merge_table(pages)+ assert exact_threshold["continues_prev"] is True+++def test_merge_table_uses_boundary_row_metrics_when_total_columns_differ() -> None:+ """验证总列数不同后按边界行 effective/actual/渲染段数回退判断。"""+ matching_previous = _table(+ 0,+ "<table><tr><td colspan='3'>H</td></tr><tr><td>A</td><td>B</td></tr></table>",+ )+ matching_current = _table(1, "<table><tr><td>C</td><td>D</td></tr></table>")+ merge_table([_page(0, [matching_previous]), _page(1, [matching_current])])+ assert matching_current["continues_prev"] is True++ mismatching_previous = _table(+ 0,+ "<table><tr><td colspan='4'>H</td></tr><tr><td colspan='2'>A</td><td>B</td></tr></table>",+ )+ mismatching_current = _table(1, "<table><tr><td colspan='2'>C</td></tr></table>")+ merge_table([_page(0, [mismatching_previous]), _page(1, [mismatching_current])])+ assert "continues_prev" not in mismatching_current+++ "current_table",+ [+ _table(1, bbox=[10.0, 10.0, 90.0, 90.0]),+ {"type": BlockType.TABLE, "index": 1, "bbox": [0.1, 0.1, 0.9, 0.9], "content": []},+ _table(1, "<table></table>"),+ _table(1, "<table><tr><td colspan='bad'>X</td></tr></table>"),+ ],+)+def test_merge_table_safely_skips_invalid_bbox_body_or_html(current_table: dict[str, Any]) -> None:+ """验证非法 bbox、table body 和 HTML 均安全降级。"""+ current_table = deepcopy(current_table)+ merge_table([_page(0, [_table(0)]), _page(1, [current_table])])+ assert "continues_prev" not in current_table+++def test_merge_table_only_changes_markers_and_preserves_normalized_bboxes() -> None:+ """验证千分位计算不会回写 bbox,检测也不修改任何表格内容。"""+ previous_table = _table(0)+ current_table = _table(1)+ pages = [_page(0, [previous_table]), _page(1, [current_table])]+ original_pages = deepcopy(pages)++ merge_table(pages)++ assert current_table.pop("continues_prev") is True+ assert pages == original_pages+++def test_merge_table_content_removes_repeated_rowspan_header_and_appends_data() -> None:+ """验证重复表头按 rowspan 覆盖范围删除,并追加当前数据行。"""+ previous_html = (+ "<table><tr><th rowspan='2'>H1</th><th>H2</th></tr><tr><th>H3</th></tr><tr><td>A</td><td>B</td></tr></table>"+ )+ current_html = "<table><tr><th rowspan='2'>H1</th><th>H2</th></tr><tr><th>H3</th></tr><tr><td>C</td><td>D</td></tr></table>"++ merged = merge_table_content(_table(0, previous_html), _table(1, current_html))++ assert merged is not None+ assert _row_texts(merged) == [["H1", "H2"], ["H3"], ["A", "B"], ["C", "D"]]+++def test_merge_table_content_repairs_colspan_on_narrower_current_rows() -> None:+ """验证较窄的当前页数据行会补齐末单元格 colspan。"""+ previous = _table(0, "<table><tr><td>A</td><td colspan='2'>B</td></tr></table>")+ current = _table(1, "<table><tr><td>C</td><td>D</td></tr></table>")++ merged = merge_table_content(previous, current)++ assert merged is not None+ appended_cells = _merged_soup(merged).find_all("tr")[-1].find_all(["td", "th"])+ assert [cell.get_text() for cell in appended_cells] == ["C", "D"]+ assert appended_cells[-1]["colspan"] == "2"+++def test_merge_table_content_clips_overlapped_blank_rowspan_placeholder() -> None:+ """验证当前页重复空白 rowspan 占位会按上页剩余跨度裁剪。"""+ previous = _table(0, "<table><tr><td rowspan='2'>A</td><td>X</td></tr></table>")+ current = _table(+ 1,+ "<table><tr><td rowspan='2'></td><td>Y</td></tr><tr><td>Z</td></tr></table>",+ )++ merged = merge_table_content(previous, current)++ assert merged is not None+ assert _row_texts(merged) == [["A", "X"], ["Y"], ["", "Z"]]+ moved_blank_cell = _merged_soup(merged).find_all("tr")[-1].find_all(["td", "th"])[0]+ assert "rowspan" not in moved_blank_cell.attrs+++def test_merge_table_content_replaces_footnote_and_preserves_previous_payloads() -> None:+ """验证纯合并保留前表载荷、忽略当前 caption,并替换 footnote。"""+ previous_body = _table_body(+ "<table><tr><th>H</th></tr><tr><td>A</td></tr></table>",+ index=5,+ )+ previous_body["image_base64"] = "previous-image"+ previous = _table(+ 5,+ children=[_caption("Original caption", index=4), previous_body, _footnote("old", index=6)],+ )+ previous["image_base64"] = "outer-image"+ current = _table(+ 8,+ children=[+ _caption("Table 1 (continued)", index=7),+ _table_body("<table><tr><th>H</th></tr><tr><td>B</td></tr></table>", index=8),+ {**_footnote("new", index=9), "_cross_page": True},+ ],+ )+ previous_original = deepcopy(previous)+ current_original = deepcopy(current)++ merged = merge_table_content(previous, current)++ assert merged is not None+ assert previous == previous_original+ assert current == current_original+ assert merged["index"] == previous["index"]+ assert merged["bbox"] == previous["bbox"]+ assert merged["image_base64"] == "outer-image"+ merged_body = next(child for child in merged["content"] if child["type"] == BlockType.TABLE_BODY)+ assert merged_body["image_base64"] == "previous-image"+ assert _row_texts(merged) == [["H"], ["A"], ["B"]]+ captions = [child["content"] for child in merged["content"] if child["type"] == BlockType.TABLE_CAPTION]+ footnotes = [child for child in merged["content"] if child["type"] == BlockType.TABLE_FOOTNOTE]+ assert captions == ["Original caption"]+ assert [footnote["content"] for footnote in footnotes] == ["new"]+ assert "_cross_page" not in footnotes[0]+++ ("previous", "current"),+ [+ (_table(0, "<table></table>"), _table(1)),+ (_table(0), _table(1, "<table><tr><td colspan='bad'>X</td></tr></table>")),+ (_table(0), {"type": BlockType.TABLE, "bbox": [0.1, 0.1, 0.9, 0.9], "content": []}),+ (_table(0), _table(1, bbox=[0.0, 0.0, 100.0, 100.0])),+ ],+)+def test_merge_table_content_returns_none_for_invalid_input(+ previous: dict[str, Any],+ current: dict[str, Any],+) -> None:+ """验证纯内容操作遇到非法 HTML、主体或 bbox 时返回空。"""+ previous_original = deepcopy(previous)+ current_original = deepcopy(current)++ assert merge_table_content(previous, current) is None+ assert previous == previous_original+ assert current == current_originaldiff --git a/tests/unittest/test_table_merge_cell_merge.py b/tests/unittest/test_table_merge_cell_merge.pyindex e3433add..ae34adf9 100644--- a/tests/unittest/test_table_merge_cell_merge.py+++ b/tests/unittest/test_table_merge_cell_merge.py@@ -1,81 +1,92 @@from __future__ import annotations-from mineru.backend.utils.table_merge import _apply_cell_merge, _build_table_state-from mineru.types import Block, BlockType, Line, Span---def _build_table_block(index: int, html: str, cell_merge: list[int]) -> Block:- """构造 cell_merge 跨页合并测试使用的两层表格块。"""- bbox = (0.0, 0.0, 100.0, 100.0)- body_block = Block(- index=index,- type=BlockType.TABLE_BODY,- bbox=bbox,- lines=[- Line(- bbox=bbox,- spans=[Span(type=BlockType.TABLE, bbox=bbox, content=html)],- )- ],+from copy import deepcopy+from typing import Any++from bs4 import BeautifulSoup++from mineru.backend.utils.table_merge import merge_table_content+from mineru.types import BlockType+++def _build_table_block(index: int, html: str, cell_merge: list[int] | None = None) -> dict[str, Any]:+ """构造纯内容合并测试使用的两层 dict 表格块。"""+ body: dict[str, Any] = {+ "index": index,+ "type": BlockType.TABLE_BODY,+ "bbox": [0.1, 0.1, 0.9, 0.9],+ "content": html,+ }+ if cell_merge is not None:+ body["cell_merge"] = cell_merge+ return {+ "index": index,+ "type": BlockType.TABLE,+ "bbox": [0.1, 0.1, 0.9, 0.9],+ "content": [body],+ }+++def _row_texts(table: dict[str, Any]) -> list[list[str]]:+ """提取合并后 table body 的逐行单元格文本。"""+ body = table["content"][0]+ soup = BeautifulSoup(body["content"], "html.parser")+ return [[cell.get_text() for cell in row.find_all(["td", "th"])] for row in soup.find_all("tr")]+++def test_merge_table_content_applies_partial_cell_merge_from_table_body() -> None:+ """验证部分视觉列续接后保留当前首行并清空已迁移单元格。"""+ previous_table = _build_table_block(+ 0,+ "<table><tr><td>A</td><td>X</td></tr></table>",)- body_block._cell_merge = cell_merge- return Block(- index=index,- type=BlockType.TABLE,- bbox=bbox,- blocks=[body_block],+ current_table = _build_table_block(+ 1,+ "<table><tr><td>B</td><td>Y</td></tr></table>",+ [1, 0],)+ previous_original = deepcopy(previous_table)+ current_original = deepcopy(current_table)++ merged = merge_table_content(previous_table, current_table)+ assert merged is not None+ assert _row_texts(merged) == [["AB", "X"], ["", "Y"]]+ assert previous_table == previous_original+ assert current_table == current_original-def test_apply_cell_merge_reads_metadata_from_table_body() -> None:- """验证顶层无 cell_merge 时仍按 table body 元数据续接单元格。"""++def test_merge_table_content_applies_full_cell_merge_and_removes_consumed_row() -> None:+ """验证全部视觉列续接后删除已消费行,并继续追加后续数据行。"""+ previous_table = _build_table_block(+ 0,+ "<table><tr><td>A</td><td>X</td></tr></table>",+ )+ current_table = _build_table_block(+ 1,+ "<table><tr><td>B</td><td>Y</td></tr><tr><td>C</td><td>Z</td></tr></table>",+ [1, 1],+ )++ merged = merge_table_content(previous_table, current_table)++ assert merged is not None+ assert _row_texts(merged) == [["AB", "XY"], ["C", "Z"]]+++def test_merge_table_content_supports_fully_consumed_only_current_row() -> None:+ """验证当前表仅有一行且被 cell_merge 全部消费时仍返回合并结果。"""previous_table = _build_table_block(0,"<table><tr><td>A</td><td>X</td></tr></table>",- [],)current_table = _build_table_block(1,"<table><tr><td>B</td><td>Y</td></tr></table>",- [1, 0],+ [1, 1],)- previous_state = _build_table_state(previous_table)- current_state = _build_table_state(current_table)- assert previous_state is not None- assert current_state is not None- assert current_table._cell_merge == []-- _apply_cell_merge(previous_state, current_state, header_count=0)-- previous_cells = previous_state.rows[-1].find_all(["td", "th"])- current_cells = current_state.rows[0].find_all(["td", "th"])- assert [cell.get_text() for cell in previous_cells] == ["AB", "X"]- assert [cell.get_text() for cell in current_cells] == ["", "Y"]---def test_apply_cell_merge_skips_missing_or_empty_body_metadata() -> None:- """验证 table body 缺失或 cell_merge 为空时安全跳过。"""- for remove_body, cell_merge in [(False, []), (True, [1, 0])]:- previous_table = _build_table_block(- 0,- "<table><tr><td>A</td><td>X</td></tr></table>",- [],- )- current_table = _build_table_block(- 1,- "<table><tr><td>B</td><td>Y</td></tr></table>",- cell_merge,- )- previous_state = _build_table_state(previous_table)- current_state = _build_table_state(current_table)- assert previous_state is not None- assert current_state is not None- if remove_body:- current_table.blocks = []-- _apply_cell_merge(previous_state, current_state, header_count=0)-- previous_cells = previous_state.rows[-1].find_all(["td", "th"])- current_cells = current_state.rows[0].find_all(["td", "th"])- assert [cell.get_text() for cell in previous_cells] == ["A", "X"]- assert [cell.get_text() for cell in current_cells] == ["B", "Y"]++ merged = merge_table_content(previous_table, current_table)++ assert merged is not None+ assert _row_texts(merged) == [["AB", "XY"]]