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 bbox_center_distance function and refactor category tying by index
myhlolib1aefabbeaa9
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex 9bacb589..5864ada8 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -6,7 +6,7 @@ from loguru import loggerfrom mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratiofrom mineru.utils.enum_class import ContentType, BlockType, NotExtractTypefrom mineru.utils.guess_suffix_or_lang import guess_language_by_text-from mineru.utils.magic_model_utils import reduct_overlap, tie_up_category_by_distance_v3+from mineru.utils.magic_model_utils import reduct_overlap, tie_up_category_by_indexfrom mineru.utils.span_block_fix import fix_text_blockfrom mineru.utils.span_pre_proc import txt_spans_extract@@ -392,13 +392,14 @@ def clean_content(content):return content-def __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_type):+def __tie_up_category_by_index(blocks, subject_block_type, object_block_type):+ """基于index的主客体关联包装函数"""# 定义获取主体和客体对象的函数def get_subjects():return reduct_overlap(list(map(- lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle":x["angle"]},+ lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle": x["angle"]},filter(lambda x: x["type"] == subject_block_type,blocks,@@ -411,7 +412,7 @@ def __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_tyreturn reduct_overlap(list(map(- lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle":x["angle"]},+ lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle": x["angle"]},filter(lambda x: x["type"] == object_block_type,blocks,@@ -421,15 +422,16 @@ def __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_ty)# 调用通用方法- return tie_up_category_by_distance_v3(+ return tie_up_category_by_index(get_subjects,get_objects)-def get_type_blocks(blocks, block_type: Literal["image", "table", "code"]):- with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")- with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")+def get_type_blocks_by_index(blocks, block_type: Literal["image", "table", "code"]):+ """使用基于index的匹配策略来组织blocks"""+ with_captions = __tie_up_category_by_index(blocks, f"{block_type}_body", f"{block_type}_caption")+ with_footnotes = __tie_up_category_by_index(blocks, f"{block_type}_body", f"{block_type}_footnote")ret = []for v in with_captions:record = {@@ -443,51 +445,8 @@ def get_type_blocks(blocks, block_type: Literal["image", "table", "code"]):return ret-def fix_two_layer_blocks_back(blocks, fix_type: Literal["image", "table", "code"]):- need_fix_blocks = get_type_blocks(blocks, fix_type)- fixed_blocks = []- not_include_blocks = []- processed_indices = set()-- # 处理需要组织成two_layer结构的blocks- for block in need_fix_blocks:- body = block[f"{fix_type}_body"]- caption_list = block[f"{fix_type}_caption_list"]- footnote_list = block[f"{fix_type}_footnote_list"]-- body["type"] = f"{fix_type}_body"- for caption in caption_list:- caption["type"] = f"{fix_type}_caption"- processed_indices.add(caption["index"])- for footnote in footnote_list:- footnote["type"] = f"{fix_type}_footnote"- processed_indices.add(footnote["index"])-- processed_indices.add(body["index"])-- two_layer_block = {- "type": fix_type,- "bbox": body["bbox"],- "blocks": [- body,- ],- "index": body["index"],- }- two_layer_block["blocks"].extend([*caption_list, *footnote_list])-- fixed_blocks.append(two_layer_block)-- # 添加未处理的blocks- for block in blocks:- if block["index"] not in processed_indices:- # 直接添加未处理的block- not_include_blocks.append(block)-- return fixed_blocks, not_include_blocks--def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "code"]):- need_fix_blocks = get_type_blocks(blocks, fix_type)+ need_fix_blocks = get_type_blocks_by_index(blocks, fix_type)fixed_blocks = []not_include_blocks = []processed_indices = set()@@ -495,23 +454,13 @@ def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "code"]):# 特殊处理表格类型,确保标题在表格前,注脚在表格后if fix_type == "table":# 收集所有不合适的caption和footnote- misplaced_captions = [] # 存储(caption, 原始block索引)misplaced_footnotes = [] # 存储(footnote, 原始block索引)- # 第一步:移除不符合位置要求的caption和footnote+ # 第一步:移除不符合位置要求的footnotefor block_idx, block in enumerate(need_fix_blocks):body = block[f"{fix_type}_body"]body_index = body["index"]- # 检查caption应在body前或同位置- valid_captions = []- for caption in block[f"{fix_type}_caption_list"]:- if caption["index"] <= body_index:- valid_captions.append(caption)- else:- misplaced_captions.append((caption, block_idx))- block[f"{fix_type}_caption_list"] = valid_captions-# 检查footnote应在body后或同位置valid_footnotes = []for footnote in block[f"{fix_type}_footnote_list"]:@@ -521,28 +470,6 @@ def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "code"]):misplaced_footnotes.append((footnote, block_idx))block[f"{fix_type}_footnote_list"] = valid_footnotes- # 第二步:重新分配不合规的caption到合适的body- for caption, original_block_idx in misplaced_captions:- caption_index = caption["index"]- best_block_idx = None- min_distance = float('inf')-- # 寻找索引大于等于caption_index的最近body- for idx, block in enumerate(need_fix_blocks):- body_index = block[f"{fix_type}_body"]["index"]- if body_index >= caption_index and idx != original_block_idx:- distance = body_index - caption_index- if distance < min_distance:- min_distance = distance- best_block_idx = idx-- if best_block_idx is not None:- # 找到合适的body,添加到对应block的caption_list- need_fix_blocks[best_block_idx][f"{fix_type}_caption_list"].append(caption)- else:- # 没找到合适的body,作为普通block处理- not_include_blocks.append(caption)-# 第三步:重新分配不合规的footnote到合适的bodyfor footnote, original_block_idx in misplaced_footnotes:footnote_index = footnote["index"]diff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.pyindex a2e2cae3..c841cc85 100644--- a/mineru/backend/vlm/vlm_magic_model.py+++ b/mineru/backend/vlm/vlm_magic_model.py@@ -6,7 +6,7 @@ from loguru import loggerfrom mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratiofrom mineru.utils.enum_class import ContentType, BlockTypefrom mineru.utils.guess_suffix_or_lang import guess_language_by_text-from mineru.utils.magic_model_utils import reduct_overlap, tie_up_category_by_distance_v3+from mineru.utils.magic_model_utils import reduct_overlap, tie_up_category_by_distance_v3, tie_up_category_by_indexclass MagicModel:@@ -317,13 +317,14 @@ def clean_content(content):return content-def __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_type):+def __tie_up_category_by_index(blocks, subject_block_type, object_block_type):+ """基于index的主客体关联包装函数"""# 定义获取主体和客体对象的函数def get_subjects():return reduct_overlap(list(map(- lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle":x["angle"]},+ lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle": x["angle"]},filter(lambda x: x["type"] == subject_block_type,blocks,@@ -336,7 +337,7 @@ def __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_tyreturn reduct_overlap(list(map(- lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle":x["angle"]},+ lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle": x["angle"]},filter(lambda x: x["type"] == object_block_type,blocks,@@ -346,15 +347,15 @@ def __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_ty)# 调用通用方法- return tie_up_category_by_distance_v3(+ return tie_up_category_by_index(get_subjects,get_objects)def get_type_blocks(blocks, block_type: Literal["image", "table", "code"]):- with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")- with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")+ with_captions = __tie_up_category_by_index(blocks, f"{block_type}_body", f"{block_type}_caption")+ with_footnotes = __tie_up_category_by_index(blocks, f"{block_type}_body", f"{block_type}_footnote")ret = []for v in with_captions:record = {@@ -368,49 +369,6 @@ def get_type_blocks(blocks, block_type: Literal["image", "table", "code"]):return ret-def fix_two_layer_blocks_back(blocks, fix_type: Literal["image", "table", "code"]):- need_fix_blocks = get_type_blocks(blocks, fix_type)- fixed_blocks = []- not_include_blocks = []- processed_indices = set()-- # 处理需要组织成two_layer结构的blocks- for block in need_fix_blocks:- body = block[f"{fix_type}_body"]- caption_list = block[f"{fix_type}_caption_list"]- footnote_list = block[f"{fix_type}_footnote_list"]-- body["type"] = f"{fix_type}_body"- for caption in caption_list:- caption["type"] = f"{fix_type}_caption"- processed_indices.add(caption["index"])- for footnote in footnote_list:- footnote["type"] = f"{fix_type}_footnote"- processed_indices.add(footnote["index"])-- processed_indices.add(body["index"])-- two_layer_block = {- "type": fix_type,- "bbox": body["bbox"],- "blocks": [- body,- ],- "index": body["index"],- }- two_layer_block["blocks"].extend([*caption_list, *footnote_list])-- fixed_blocks.append(two_layer_block)-- # 添加未处理的blocks- for block in blocks:- if block["index"] not in processed_indices:- # 直接添加未处理的block- not_include_blocks.append(block)-- return fixed_blocks, not_include_blocks--def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "code"]):need_fix_blocks = get_type_blocks(blocks, fix_type)fixed_blocks = []@@ -423,20 +381,11 @@ def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "code"]):misplaced_captions = [] # 存储(caption, 原始block索引)misplaced_footnotes = [] # 存储(footnote, 原始block索引)- # 第一步:移除不符合位置要求的caption和footnote+ # 第一步:移除不符合位置要求的footnotefor block_idx, block in enumerate(need_fix_blocks):body = block[f"{fix_type}_body"]body_index = body["index"]- # 检查caption应在body前或同位置- valid_captions = []- for caption in block[f"{fix_type}_caption_list"]:- if caption["index"] <= body_index:- valid_captions.append(caption)- else:- misplaced_captions.append((caption, block_idx))- block[f"{fix_type}_caption_list"] = valid_captions-# 检查footnote应在body后或同位置valid_footnotes = []for footnote in block[f"{fix_type}_footnote_list"]:@@ -446,28 +395,6 @@ def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "code"]):misplaced_footnotes.append((footnote, block_idx))block[f"{fix_type}_footnote_list"] = valid_footnotes- # 第二步:重新分配不合规的caption到合适的body- for caption, original_block_idx in misplaced_captions:- caption_index = caption["index"]- best_block_idx = None- min_distance = float('inf')-- # 寻找索引大于等于caption_index的最近body- for idx, block in enumerate(need_fix_blocks):- body_index = block[f"{fix_type}_body"]["index"]- if body_index >= caption_index and idx != original_block_idx:- distance = body_index - caption_index- if distance < min_distance:- min_distance = distance- best_block_idx = idx-- if best_block_idx is not None:- # 找到合适的body,添加到对应block的caption_list- need_fix_blocks[best_block_idx][f"{fix_type}_caption_list"].append(caption)- else:- # 没找到合适的body,作为普通block处理- not_include_blocks.append(caption)-# 第三步:重新分配不合规的footnote到合适的bodyfor footnote, original_block_idx in misplaced_footnotes:footnote_index = footnote["index"]diff --git a/mineru/utils/boxbase.py b/mineru/utils/boxbase.pyindex e249ecad..62404e17 100644--- a/mineru/utils/boxbase.py+++ b/mineru/utils/boxbase.py@@ -74,6 +74,29 @@ def bbox_distance(bbox1, bbox2):return 0.0+def bbox_center_distance(bbox1, bbox2):+ """计算两个矩形框中心点之间的欧氏距离。++ Args:+ bbox1 (tuple): 第一个矩形框的坐标,格式为 (x1, y1, x2, y2)+ bbox2 (tuple): 第二个矩形框的坐标,格式为 (x1, y1, x2, y2)++ Returns:+ float: 两个矩形框中心点之间的距离+ """+ x1, y1, x1b, y1b = bbox1+ x2, y2, x2b, y2b = bbox2++ # 计算中心点+ center1_x = (x1 + x1b) / 2+ center1_y = (y1 + y1b) / 2+ center2_x = (x2 + x2b) / 2+ center2_y = (y2 + y2b) / 2++ # 计算欧氏距离+ return math.sqrt((center1_x - center2_x) ** 2 + (center1_y - center2_y) ** 2)++def get_minbox_if_overlap_by_ratio(bbox1, bbox2, ratio):"""通过calculate_overlap_area_2_minbox_area_ratio计算两个bbox重叠的面积占最小面积的box的比例如果比例大于ratio,则返回小的那个bbox, 否则返回None."""diff --git a/mineru/utils/magic_model_utils.py b/mineru/utils/magic_model_utils.pyindex 9917717e..597d6594 100644--- a/mineru/utils/magic_model_utils.py+++ b/mineru/utils/magic_model_utils.py@@ -2,7 +2,7 @@包含两个MagicModel类中重复使用的方法和逻辑"""from typing import List, Dict, Any, Callable-from mineru.utils.boxbase import bbox_distance, is_in+from mineru.utils.boxbase import bbox_distance, bbox_center_distance, is_indef reduct_overlap(bboxes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:@@ -165,4 +165,87 @@ def tie_up_category_by_distance_v3(})- return ret\ No newline at end of file+ return ret+++def tie_up_category_by_index(+ get_subjects_func: Callable,+ get_objects_func: Callable,+ extract_subject_func: Callable = None,+ extract_object_func: Callable = None+):+ """+ 基于index的类别关联方法,用于将主体对象与客体对象进行关联+ 客体优先匹配给index最接近的主体,index差值相同时使用bbox中心点距离作为tiebreaker++ 参数:+ get_subjects_func: 函数,提取主体对象+ get_objects_func: 函数,提取客体对象+ extract_subject_func: 函数,自定义提取主体属性(默认使用bbox和其他属性)+ extract_object_func: 函数,自定义提取客体属性(默认使用bbox和其他属性)++ 返回:+ 关联后的对象列表,按主体index升序排列+ """+ subjects = get_subjects_func()+ objects = get_objects_func()++ # 如果没有提供自定义提取函数,使用默认函数+ if extract_subject_func is None:+ extract_subject_func = lambda x: x+ if extract_object_func is None:+ extract_object_func = lambda x: x++ # 初始化结果字典,key为主体索引,value为关联信息+ result_dict = {}++ # 初始化所有主体+ for i, subject in enumerate(subjects):+ result_dict[i] = {+ "sub_bbox": extract_subject_func(subject),+ "obj_bboxes": [],+ "sub_idx": i,+ }++ # 为每个客体找到最匹配的主体+ for obj in objects:+ if len(subjects) == 0:+ # 如果没有主体,跳过客体+ continue++ obj_index = obj["index"]+ min_index_diff = float("inf")+ best_subject_indices = []++ # 找出index差值最小的所有主体+ for i, subject in enumerate(subjects):+ sub_index = subject["index"]+ index_diff = abs(obj_index - sub_index)++ if index_diff < min_index_diff:+ min_index_diff = index_diff+ best_subject_indices = [i]+ elif index_diff == min_index_diff:+ best_subject_indices.append(i)++ # 如果有多个主体的index差值相同,使用中心点距离作为tiebreaker+ if len(best_subject_indices) > 1:+ min_center_dist = float("inf")+ best_subject_idx = best_subject_indices[0]++ for idx in best_subject_indices:+ center_dist = bbox_center_distance(obj["bbox"], subjects[idx]["bbox"])+ if center_dist < min_center_dist:+ min_center_dist = center_dist+ best_subject_idx = idx+ else:+ best_subject_idx = best_subject_indices[0]++ # 将客体添加到最佳主体的obj_bboxes中+ result_dict[best_subject_idx]["obj_bboxes"].append(extract_object_func(obj))++ # 转换为列表并按主体index排序+ ret = list(result_dict.values())+ ret.sort(key=lambda x: x["sub_idx"])++ return ret