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: add fallback for inline caption fragments in visual processing
myhloli7299a5abc0ef
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex a88563b4..59a64e93 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -15,6 +15,7 @@ from mineru.utils.visual_magic_model_utils import (VISUAL_MAIN_TYPES,clean_content,code_content_clean,+ fallback_inline_caption_fragments,isolated_formula_clean,regroup_visual_blocks,)@@ -311,6 +312,8 @@ class MagicModel:blocks.append(block)+ fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)+self.image_blocks = []self.table_blocks = []self.chart_blocks = []diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.pyindex 949536bb..e60a3a04 100644--- a/mineru/backend/pipeline/pipeline_magic_model.py+++ b/mineru/backend/pipeline/pipeline_magic_model.py@@ -2,8 +2,6 @@from mineru.backend.pipeline.para_split import ListLineTagfrom mineru.backend.pipeline.pipeline_middle_json_mkcontent import _merge_para_textfrom mineru.utils.boxbase import (- bbox_center_distance,- bbox_distance,calculate_overlap_area_2_minbox_area_ratio,calculate_overlap_area_in_bbox1_area_ratio,)@@ -12,6 +10,10 @@ from mineru.utils.guess_suffix_or_lang import guess_language_by_textfrom mineru.utils.span_block_fix import merge_spans_to_vertical_line, vertical_line_sort_spans_from_top_to_bottom, \merge_spans_to_line, line_sort_spans_by_left_to_right, is_vertical_text_block_by_spansfrom mineru.utils.span_pre_proc import txt_spans_extract+from mineru.utils.visual_magic_model_utils import (+ fallback_inline_caption_fragments,+ find_best_visual_parent,+)class MagicModel:@@ -118,6 +120,7 @@ class MagicModel:self.page_blocks.sort(key=lambda x: x["index"])self.__build_page_blocks()+ fallback_inline_caption_fragments(self.page_blocks, self.VISUAL_MAIN_TYPES)self.__classify_visual_blocks()self.__build_return_blocks()@@ -459,54 +462,16 @@ class MagicModel:if child_type not in self.VISUAL_CHILD_TYPES:return None- best_parent = None- best_key = None- for main_block in main_blocks:- if not self.__is_visual_neighbor(- child_block,- main_block,- ordered_blocks,- original_type_by_index,- position_by_index,- ):- continue-- candidate_key = (- abs(child_block["index"] - main_block["index"]),- bbox_distance(child_block["bbox"], main_block["bbox"]),- bbox_center_distance(child_block["bbox"], main_block["bbox"]),- main_block["index"],- )-- if best_key is None or candidate_key < best_key:- best_key = candidate_key- best_parent = main_block-- return best_parent-- def __is_visual_neighbor(- self,- child_block,- main_block,- ordered_blocks,- original_type_by_index,- position_by_index,- ):- child_type = original_type_by_index[child_block["index"]]- if child_type == BlockType.FOOTNOTE and child_block["index"] < main_block["index"]:- return False-- child_pos = position_by_index[child_block["index"]]- main_pos = position_by_index[main_block["index"]]- start_pos = min(child_pos, main_pos) + 1- end_pos = max(child_pos, main_pos)-- for pos in range(start_pos, end_pos):- between_block = ordered_blocks[pos]- if original_type_by_index[between_block["index"]] != child_type:- return False-- return True+ return find_best_visual_parent(+ child_block,+ main_blocks,+ ordered_blocks,+ position_by_index,+ main_type_to_visual_type={+ block_type: block_type for block_type in self.VISUAL_MAIN_TYPES+ },+ type_by_index=original_type_by_index,+ )@staticmethoddef __child_kind(block_type):diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.pyindex 32ecb66b..20f294b7 100644--- a/mineru/backend/vlm/vlm_magic_model.py+++ b/mineru/backend/vlm/vlm_magic_model.py@@ -12,6 +12,7 @@ from mineru.utils.visual_magic_model_utils import (VISUAL_MAIN_TYPES,clean_content,code_content_clean,+ fallback_inline_caption_fragments,isolated_formula_clean,regroup_visual_blocks,)@@ -228,6 +229,8 @@ class MagicModel:blocks.append(block)+ fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)+self.image_blocks = []self.table_blocks = []self.chart_blocks = []diff --git a/mineru/utils/visual_magic_model_utils.py b/mineru/utils/visual_magic_model_utils.pyindex 20c6fcd3..ffc3544d 100644--- a/mineru/utils/visual_magic_model_utils.py+++ b/mineru/utils/visual_magic_model_utils.py@@ -11,6 +11,14 @@ from mineru.utils.enum_class import BlockTypeIMAGE_BLOCK_BODY = "image_block_body"GENERIC_CHILD_TYPES = (BlockType.CAPTION, BlockType.FOOTNOTE)+INLINE_CAPTION_FRAGMENT_TYPES = {BlockType.TEXT, BlockType.FOOTNOTE}+VISUAL_RELATION_IGNORED_TYPES = {+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.PAGE_FOOTNOTE,+ BlockType.ASIDE_TEXT,+}VISUAL_MAIN_TYPES = {BlockType.IMAGE_BODY: BlockType.IMAGE,IMAGE_BLOCK_BODY: BlockType.IMAGE,@@ -84,6 +92,80 @@ def clean_content(content):return content+def fallback_inline_caption_fragments(blocks, visual_main_types):+ """将紧贴视觉主体上方的同行 text/footnote 片段兜底为通用 caption。"""+ if len(blocks) < 3:+ return++ main_types = set(visual_main_types)+ ordered_blocks = sorted(blocks, key=lambda x: x["index"])+ for pos, block in enumerate(ordered_blocks):+ if block.get("type") not in INLINE_CAPTION_FRAGMENT_TYPES:+ continue++ previous_block = find_previous_effective_block(ordered_blocks, pos)+ next_block = find_next_effective_block(ordered_blocks, pos)+ if not (+ previous_block+ and next_block+ and previous_block.get("type") == BlockType.CAPTION+ and next_block.get("type") in main_types+ ):+ continue++ if not is_inline_caption_fragment(previous_block, block, next_block):+ continue++ block["type"] = BlockType.CAPTION+ # fallback 后该块已是视觉 caption 片段,不再参与正文跨块合并。+ block.pop("merge_prev", None)+++def find_previous_effective_block(ordered_blocks, pos):+ """向前查找参与视觉关系判断的有效块,跳过页眉页脚等外围块。"""+ for index in range(pos - 1, -1, -1):+ block = ordered_blocks[index]+ if block.get("type") not in VISUAL_RELATION_IGNORED_TYPES:+ return block+ return None+++def find_next_effective_block(ordered_blocks, pos):+ """向后查找参与视觉关系判断的有效块,跳过页眉页脚等外围块。"""+ for index in range(pos + 1, len(ordered_blocks)):+ block = ordered_blocks[index]+ if block.get("type") not in VISUAL_RELATION_IGNORED_TYPES:+ return block+ return None+++def is_inline_caption_fragment(previous_caption, text_block, next_visual):+ """判断当前块是否是前一 caption 的同行补充片段。"""+ caption_bbox = previous_caption["bbox"]+ text_bbox = text_block["bbox"]+ visual_bbox = next_visual["bbox"]++ caption_height = max(caption_bbox[3] - caption_bbox[1], 1)+ text_height = max(text_bbox[3] - text_bbox[1], 1)+ min_text_height = max(min(caption_height, text_height), 1)++ vertical_overlap = min(caption_bbox[3], text_bbox[3]) - max(caption_bbox[1], text_bbox[1])+ center_y_diff = abs(+ ((caption_bbox[1] + caption_bbox[3]) / 2)+ - ((text_bbox[1] + text_bbox[3]) / 2)+ )+ is_same_line = (+ vertical_overlap / min_text_height >= 0.6+ or center_y_diff <= max(caption_height, text_height) * 0.5+ )+ if not is_same_line:+ return False++ vertical_gap_to_visual = visual_bbox[1] - max(caption_bbox[3], text_bbox[3])+ max_allowed_gap = max(12, max(caption_height, text_height) * 1.5)+ return 0 <= vertical_gap_to_visual <= max_allowed_gap++def regroup_visual_blocks(blocks):ordered_blocks = sorted(blocks, key=lambda x: x["index"])absorbed_member_indices, sub_images_by_index = absorb_image_block_members(ordered_blocks)@@ -236,34 +318,126 @@ def absorb_image_block_members(blocks):return absorbed_member_indices, sub_images_by_index-def find_best_visual_parent(child_block, main_blocks, ordered_blocks, position_by_index):- best_parent = None- best_key = None-+def find_best_visual_parent(+ child_block,+ main_blocks,+ ordered_blocks,+ position_by_index,+ main_type_to_visual_type=None,+ type_by_index=None,+):+ """为通用 caption/footnote 查找最合适的视觉主体。"""+ if main_type_to_visual_type is None:+ main_type_to_visual_type = VISUAL_MAIN_TYPES+ candidates = []for main_block in main_blocks:if not is_visual_neighbor(child_block,main_block,ordered_blocks,position_by_index,+ type_by_index=type_by_index,):continue- candidate_key = (- bbox_distance(child_block["bbox"], main_block["bbox"]),- abs(child_block["index"] - main_block["index"]),+ candidates.append(main_block)++ if not candidates:+ return None++ min_effective_index_diff = min(+ effective_visual_index_diff(+ child_block,+ main_block,+ ordered_blocks,+ type_by_index=type_by_index,+ )+ for main_block in candidates+ )+ closest_index_candidates = [+ main_block+ for main_block in candidates+ if effective_visual_index_diff(+ child_block,+ main_block,+ ordered_blocks,+ type_by_index=type_by_index,+ )+ == min_effective_index_diff+ ]++ if len(closest_index_candidates) == 1:+ return closest_index_candidates[0]++ edge_distances = [+ (main_block, bbox_distance(child_block["bbox"], main_block["bbox"]))+ for main_block in closest_index_candidates+ ]+ edge_values = [edge_distance for _, edge_distance in edge_distances]+ if max(edge_values) - min(edge_values) > 2:+ return min(+ edge_distances,+ key=lambda item: (item[1], item[0]["index"]),+ )[0]++ child_type = block_type(child_block, type_by_index)+ if (+ child_type == BlockType.CAPTION+ and all(+ main_type_to_visual_type.get(block_type(main_block, type_by_index))+ == BlockType.TABLE+ for main_block in closest_index_candidates+ )+ ):+ # 表格 caption 位于两个表之间且距离接近时,优先归属后一个表。+ return max(closest_index_candidates, key=lambda x: x["index"])++ if child_type == BlockType.FOOTNOTE:+ # 视觉脚注位于两个主体之间且距离接近时,优先归属前一个主体。+ return min(closest_index_candidates, key=lambda x: x["index"])++ return min(+ closest_index_candidates,+ key=lambda main_block: (bbox_center_distance(child_block["bbox"], main_block["bbox"]),main_block["index"],- )- if best_key is None or candidate_key < best_key:- best_key = candidate_key- best_parent = main_block+ ),+ )+++def effective_visual_index_diff(+ child_block,+ main_block,+ ordered_blocks,+ type_by_index=None,+):+ """计算视觉子块与主体的有效 index 距离,忽略中间同类子块。"""+ child_index = child_block["index"]+ main_index = main_block["index"]+ start_index = min(child_index, main_index)+ end_index = max(child_index, main_index)+ skipped_child_count = 0+ child_type = block_type(child_block, type_by_index)++ for block in ordered_blocks:+ block_index = block["index"]+ if (+ start_index < block_index < end_index+ and block_type(block, type_by_index) == child_type+ ):+ skipped_child_count += 1- return best_parent+ return end_index - start_index - skipped_child_count-def is_visual_neighbor(child_block, main_block, ordered_blocks, position_by_index):- child_type = child_block["type"]+def is_visual_neighbor(+ child_block,+ main_block,+ ordered_blocks,+ position_by_index,+ type_by_index=None,+):+ child_type = block_type(child_block, type_by_index)if child_type == BlockType.FOOTNOTE and child_block["index"] < main_block["index"]:return False@@ -279,12 +453,19 @@ def is_visual_neighbor(child_block, main_block, ordered_blocks, position_by_indefor pos in range(start_pos, end_pos):between_block = ordered_blocks[pos]- if between_block["type"] not in allowed_between_types:+ if block_type(between_block, type_by_index) not in allowed_between_types:return Falsereturn True+def block_type(block, type_by_index=None):+ """读取块类型;pipeline 会传入改写前的原始类型映射。"""+ if type_by_index is not None:+ return type_by_index[block["index"]]+ return block["type"]++def child_kind_from_type(block_type):if block_type == BlockType.CAPTION:return "caption"