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 footnote and formula number content types in layout processing
myhloli00b9def90cad
diff --git a/mineru/backend/pipeline/model_json_to_middle_json.py b/mineru/backend/pipeline/model_json_to_middle_json.pyindex 3b3418d8..8ffc241b 100644--- a/mineru/backend/pipeline/model_json_to_middle_json.py+++ b/mineru/backend/pipeline/model_json_to_middle_json.py@@ -28,10 +28,17 @@ from mineru.utils.hash_utils import bytes_md5def page_model_info_to_page_info(page_model_info, image_dict, page, image_writer, page_index, ocr_enable=False, formula_enabled=True):scale = image_dict["scale"]page_pil_img = image_dict["img_pil"]- # page_img_md5 = str_md5(image_dict["img_base64"])page_img_md5 = bytes_md5(page_pil_img.tobytes())page_w, page_h = map(int, page.get_size())- magic_model = MagicModel(page_model_info, scale)+ magic_model = MagicModel(+ page_model_info,+ page,+ scale,+ page_pil_img,+ page_w,+ page_h,+ ocr_enable+ )"""从magic_model对象中获取后面会用到的区块信息"""discarded_blocks = magic_model.get_discarded()@@ -39,134 +46,9 @@ def page_model_info_to_page_info(page_model_info, image_dict, page, image_writertitle_blocks = magic_model.get_title_blocks()inline_equations, interline_equations, interline_equation_blocks = magic_model.get_equations()- img_groups = magic_model.get_imgs()- table_groups = magic_model.get_tables()-- """对image和table的区块分组"""- img_body_blocks, img_caption_blocks, img_footnote_blocks, maybe_text_image_blocks = process_groups(- img_groups, 'image_body', 'image_caption_list', 'image_footnote_list'- )-- table_body_blocks, table_caption_blocks, table_footnote_blocks, _ = process_groups(- table_groups, 'table_body', 'table_caption_list', 'table_footnote_list'- )-"""获取所有的spans信息"""spans = magic_model.get_all_spans()- """某些图可能是文本块,通过简单的规则判断一下"""- if len(maybe_text_image_blocks) > 0:- for block in maybe_text_image_blocks:- should_add_to_text_blocks = False-- if ocr_enable:- # 找到与当前block重叠的text spans- span_in_block_list = [- span for span in spans- if span['type'] == 'text' and- calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block['bbox']) > 0.7- ]-- if len(span_in_block_list) > 0:- # 计算spans总面积- spans_area = sum(- (span['bbox'][2] - span['bbox'][0]) * (span['bbox'][3] - span['bbox'][1])- for span in span_in_block_list- )-- # 计算block面积- block_area = (block['bbox'][2] - block['bbox'][0]) * (block['bbox'][3] - block['bbox'][1])-- # 判断是否符合文本图条件- if block_area > 0 and spans_area / block_area > 0.25:- should_add_to_text_blocks = True-- # 根据条件决定添加到哪个列表- if should_add_to_text_blocks:- block.pop('group_id', None) # 移除group_id- text_blocks.append(block)- else:- img_body_blocks.append(block)--- """将所有区块的bbox整理到一起"""- if formula_enabled:- interline_equation_blocks = []-- if len(interline_equation_blocks) > 0:-- for block in interline_equation_blocks:- spans.append({- "type": ContentType.INTERLINE_EQUATION,- 'score': block['score'],- "bbox": block['bbox'],- "content": "",- })-- all_bboxes, all_discarded_blocks, footnote_blocks = prepare_block_bboxes(- img_body_blocks, img_caption_blocks, img_footnote_blocks,- table_body_blocks, table_caption_blocks, table_footnote_blocks,- discarded_blocks,- text_blocks,- title_blocks,- interline_equation_blocks,- page_w,- page_h,- )- else:- all_bboxes, all_discarded_blocks, footnote_blocks = prepare_block_bboxes(- img_body_blocks, img_caption_blocks, img_footnote_blocks,- table_body_blocks, table_caption_blocks, table_footnote_blocks,- discarded_blocks,- text_blocks,- title_blocks,- interline_equations,- page_w,- page_h,- )-- """在删除重复span之前,应该通过image_body和table_body的block过滤一下image和table的span"""- """顺便删除大水印并保留abandon的span"""- spans = remove_outside_spans(spans, all_bboxes, all_discarded_blocks)-- """删除重叠spans中置信度较低的那些"""- spans, dropped_spans_by_confidence = remove_overlaps_low_confidence_spans(spans)- """删除重叠spans中较小的那些"""- spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)-- """根据parse_mode,构造spans,主要是文本类的字符填充"""- if ocr_enable:- pass- else:- """使用新版本的混合ocr方案."""- spans = txt_spans_extract(page, spans, page_pil_img, scale, all_bboxes, all_discarded_blocks)-- """先处理不需要排版的discarded_blocks"""- discarded_block_with_spans, spans = fill_spans_in_blocks(- all_discarded_blocks, spans, 0.4- )- fix_discarded_blocks = fix_discarded_block(discarded_block_with_spans)-- """如果当前页面没有有效的bbox则跳过"""- if len(all_bboxes) == 0 and len(fix_discarded_blocks) == 0:- return None-- """对image/table/interline_equation截图"""- for span in spans:- if span['type'] in [ContentType.IMAGE, ContentType.TABLE, ContentType.INTERLINE_EQUATION]:- span = cut_image_and_table(- span, page_pil_img, page_img_md5, page_index, image_writer, scale=scale- )-- """span填充进block"""- block_with_spans, spans = fill_spans_in_blocks(all_bboxes, spans, 0.5)-- """对block进行fix操作"""- fix_blocks = fix_block_spans(block_with_spans)-- """对block进行排序"""- sorted_blocks = sort_blocks_by_bbox(fix_blocks, page_w, page_h, footnote_blocks)-"""构造page_info"""page_info = make_page_info_dict(sorted_blocks, page_index, page_w, page_h, fix_discarded_blocks)diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.pyindex 11e3fa07..f1f1ec58 100644--- a/mineru/backend/pipeline/pipeline_magic_model.py+++ b/mineru/backend/pipeline/pipeline_magic_model.py@@ -1,15 +1,77 @@-from mineru.utils.boxbase import bbox_relative_pos, calculate_iou, bbox_distance, get_minbox_if_overlap_by_ratio-from mineru.utils.enum_class import CategoryId, ContentType-from mineru.utils.magic_model_utils import tie_up_category_by_distance_v3, reduct_overlap+from mineru.utils.enum_class import ContentType, BlockType+from mineru.utils.span_pre_proc import txt_spans_extractclass MagicModel:- """每个函数没有得到元素的时候返回空list."""- def __init__(self, page_model_info: dict, scale: float):++ PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES = {+ "abstract": BlockType.ABSTRACT,+ "algorithm": BlockType.ALGORITHM,+ "aside_text": BlockType.ASIDE_TEXT,+ "chart": BlockType.CHART,+ "content": BlockType.TEXT,+ "display_formula": BlockType.INTERLINE_EQUATION,+ "doc_title": BlockType.DOC_TITLE,+ "figure_title": BlockType.CAPTION,+ "footer": BlockType.FOOTER,+ "footer_image": BlockType.FOOTER_IMAGE,+ "footnote": BlockType.PAGE_FOOTNOTE,+ "formula_number":BlockType.FORMULA_NUMBER,+ "header": BlockType.HEADER,+ "header_image": BlockType.HEADER_IMAGE,+ "image": BlockType.IMAGE,+ "number": BlockType.PAGE_NUMBER,+ "paragraph_title": BlockType.PARAGRAPH_TITLE,+ "reference_content": BlockType.REF_TEXT,+ "seal": BlockType.SEAL,+ "table": BlockType.TABLE,+ "text": BlockType.TEXT,+ "vertical_text": BlockType.VERTICAL_TEXT,+ "vision_footnote": BlockType.FOOTNOTE,+ }++ def __init__(self,+ page_model_info: dict,+ page,+ scale,+ page_pil_img,+ page_w,+ page_h,+ ocr_enable+ ):self.__page_model_info = page_model_info+ self.page_inline_formula = []+ self.page_ocr_res = []+ self.page_blocks = []self.__scale = scale- """为所有模型数据添加bbox信息(缩放,poly->bbox)"""- self.__fix_axis()+ self.__fix_axis() # bbox坐标修正,删除高度或者宽度小于等于0的spans+ self.__post_process() # index重排,填充行内公式和文本span+ self.page_text_inline_formula_spans = self.page_inline_formula + self.page_ocr_res++ if not ocr_enable:+ virtual_block = [0, 0, page_w, page_h, None, None, None, "text"]+ self.page_text_inline_formula_spans = txt_spans_extract(+ page,+ self.page_text_inline_formula_spans,+ page_pil_img,+ scale,+ [virtual_block],+ []+ )++ for layout_det in self.__page_model_info['layout_dets']:+ if layout_det.get('label') in self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES:+ block_bbox = layout_det['bbox']+ block_type = self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES[layout_det['label']]+ block_index = layout_det['index']+ block_score = layout_det['score']+ self.page_blocks.append({+ "bbox": block_bbox,+ "type": block_type,+ "index": block_index,+ "score": block_score,+ })+@staticmethoddef __is_inline_formula_block(layout_det: dict) -> bool:@@ -18,6 +80,10 @@ class MagicModel:or layout_det.get('cls_id') == 15)+ @staticmethod+ def __is_ocr_text_block(layout_det: dict) -> bool:+ return layout_det.get('label') == 'ocr_text'+def __fix_axis(self):need_remove_list = []layout_dets = self.__page_model_info['layout_dets']@@ -30,182 +96,35 @@ class MagicModel:int(y1 / self.__scale),]layout_det['bbox'] = bbox- # 删除高度或者宽度小于等于0的spans- if bbox[2] - bbox[0] <= 0 or bbox[3] - bbox[1] <= 0:+ # 删除高度或者宽度小于等于2的spans+ if bbox[2] - bbox[0] <= 2 or bbox[3] - bbox[1] <= 2:need_remove_list.append(layout_det)for need_remove in need_remove_list:layout_dets.remove(need_remove)+ def __post_process(self):next_index = 1+ layout_dets = self.__page_model_info['layout_dets']for layout_det in layout_dets:if self.__is_inline_formula_block(layout_det):layout_det.pop('index', None)+ self.page_inline_formula.append({+ "bbox": layout_det["bbox"],+ "type": ContentType.INLINE_EQUATION,+ "content": layout_det["latex"],+ "score": layout_det["score"],+ })+ continue++ if self.__is_ocr_text_block(layout_det):+ self.page_ocr_res.append({+ "bbox": layout_det["bbox"],+ "type": ContentType.TEXT,+ "content": layout_det["text"],+ "score": layout_det["score"],+ })continueif 'index' in layout_det:layout_det['index'] = next_index- next_index += 1--- def __tie_up_category_by_distance_v3(self, subject_category_id, object_category_id):- # 定义获取主体和客体对象的函数- def get_subjects():- return reduct_overlap(- list(- map(- lambda x: {'bbox': x['bbox'], 'score': x['score']},- filter(- lambda x: x['category_id'] == subject_category_id,- self.__page_model_info['layout_dets'],- ),- )- )- )-- def get_objects():- return reduct_overlap(- list(- map(- lambda x: {'bbox': x['bbox'], 'score': x['score']},- filter(- lambda x: x['category_id'] == object_category_id,- self.__page_model_info['layout_dets'],- ),- )- )- )-- # 调用通用方法- return tie_up_category_by_distance_v3(- get_subjects,- get_objects- )-- def get_imgs(self):- with_captions = self.__tie_up_category_by_distance_v3(- CategoryId.ImageBody, CategoryId.ImageCaption- )- with_footnotes = self.__tie_up_category_by_distance_v3(- CategoryId.ImageBody, CategoryId.ImageFootnote- )- ret = []- for v in with_captions:- record = {- 'image_body': v['sub_bbox'],- 'image_caption_list': v['obj_bboxes'],- }- filter_idx = v['sub_idx']- d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))- record['image_footnote_list'] = d['obj_bboxes']- ret.append(record)- return ret-- def get_tables(self) -> list:- with_captions = self.__tie_up_category_by_distance_v3(- CategoryId.TableBody, CategoryId.TableCaption- )- with_footnotes = self.__tie_up_category_by_distance_v3(- CategoryId.TableBody, CategoryId.TableFootnote- )- ret = []- for v in with_captions:- record = {- 'table_body': v['sub_bbox'],- 'table_caption_list': v['obj_bboxes'],- }- filter_idx = v['sub_idx']- d = next(filter(lambda x: x['sub_idx'] == filter_idx, with_footnotes))- record['table_footnote_list'] = d['obj_bboxes']- ret.append(record)- return ret-- def get_equations(self) -> tuple[list, list, list]: # 有坐标,也有字- inline_equations = self.__get_blocks_by_type(- CategoryId.InlineEquation, ['latex']- )- interline_equations = self.__get_blocks_by_type(- CategoryId.InterlineEquation_YOLO, ['latex']- )- interline_equations_blocks = self.__get_blocks_by_type(- CategoryId.InterlineEquation_Layout- )- return inline_equations, interline_equations, interline_equations_blocks-- def get_discarded(self) -> list: # 自研模型,只有坐标- blocks = self.__get_blocks_by_type(CategoryId.Abandon)- return blocks-- def get_text_blocks(self) -> list: # 自研模型搞的,只有坐标,没有字- blocks = self.__get_blocks_by_type(CategoryId.Text)- return blocks-- def get_title_blocks(self) -> list: # 自研模型,只有坐标,没字- blocks = self.__get_blocks_by_type(CategoryId.Title)- return blocks-- def get_all_spans(self) -> list:-- def remove_duplicate_spans(spans):- new_spans = []- for span in spans:- if not any(span == existing_span for existing_span in new_spans):- new_spans.append(span)- return new_spans-- all_spans = []- layout_dets = self.__page_model_info['layout_dets']- allow_category_id_list = [- CategoryId.ImageBody,- CategoryId.TableBody,- CategoryId.InlineEquation,- CategoryId.InterlineEquation_YOLO,- CategoryId.OcrText,- ]- """当成span拼接的"""- for layout_det in layout_dets:- category_id = layout_det['category_id']- if category_id in allow_category_id_list:- span = {'bbox': layout_det['bbox'], 'score': layout_det['score']}- if category_id == CategoryId.ImageBody:- span['type'] = ContentType.IMAGE- elif category_id == CategoryId.TableBody:- # 获取table模型结果- latex = layout_det.get('latex', None)- html = layout_det.get('html', None)- if latex:- span['latex'] = latex- elif html:- span['html'] = html- span['type'] = ContentType.TABLE- elif category_id == CategoryId.InlineEquation:- span['content'] = layout_det['latex']- span['type'] = ContentType.INLINE_EQUATION- elif category_id == CategoryId.InterlineEquation_YOLO:- span['content'] = layout_det['latex']- span['type'] = ContentType.INTERLINE_EQUATION- elif category_id == CategoryId.OcrText:- span['content'] = layout_det['text']- span['type'] = ContentType.TEXT- all_spans.append(span)- return remove_duplicate_spans(all_spans)-- def __get_blocks_by_type(- self, category_type: int, extra_col=None- ) -> list:- if extra_col is None:- extra_col = []- blocks = []- layout_dets = self.__page_model_info.get('layout_dets', [])- for item in layout_dets:- category_id = item.get('category_id', -1)- bbox = item.get('bbox', None)-- if category_id == category_type:- block = {- 'bbox': bbox,- 'score': item.get('score'),- }- for col in extra_col:- block[col] = item.get(col, None)- blocks.append(block)- return blocks+ next_index += 1\ No newline at end of filediff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.pyindex fcd1e257..be72e72a 100644--- a/mineru/utils/enum_class.py+++ b/mineru/utils/enum_class.py@@ -11,6 +11,7 @@ class BlockType:IMAGE_CAPTION = 'image_caption'TABLE_CAPTION = 'table_caption'CHART_CAPTION = 'chart_caption'+ FOOTNOTE = 'footnote' # pp_layout中的vision_footnoteIMAGE_FOOTNOTE = 'image_footnote'TABLE_FOOTNOTE = 'table_footnote'Chart_FOOTNOTE = 'chart_footnote'@@ -43,6 +44,7 @@ class BlockType:SEAL = "seal"HEADER_IMAGE = "header_image"FOOTER_IMAGE = "footer_image"+ FORMULA_NUMBER = "formula_number"class ContentType:IMAGE = 'image'