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: refactor page model processing to enhance block handling and streamline OCR functionality
myhloli00d5c4b0b102
diff --git a/mineru/backend/pipeline/model_json_to_middle_json.py b/mineru/backend/pipeline/model_json_to_middle_json.pyindex 8ffc241b..d928c3cf 100644--- a/mineru/backend/pipeline/model_json_to_middle_json.py+++ b/mineru/backend/pipeline/model_json_to_middle_json.py@@ -9,23 +9,17 @@ from mineru.backend.utils import cross_page_table_mergefrom mineru.utils.config_reader import get_device, get_llm_aided_config, get_formula_enablefrom mineru.backend.pipeline.model_init import AtomModelSingletonfrom mineru.backend.pipeline.para_split import para_split-from mineru.utils.block_pre_proc import prepare_block_bboxes, process_groups-from mineru.utils.block_sort import sort_blocks_by_bbox-from mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratiofrom mineru.utils.cut_image import cut_image_and_table-from mineru.utils.enum_class import ContentType+from mineru.utils.enum_class import ContentType, BlockTypefrom mineru.utils.llm_aided import llm_aided_titlefrom mineru.utils.model_utils import clean_memoryfrom mineru.backend.pipeline.pipeline_magic_model import MagicModelfrom mineru.utils.ocr_utils import OcrConfidence-from mineru.utils.span_block_fix import fill_spans_in_blocks, fix_discarded_block, fix_block_spans-from mineru.utils.span_pre_proc import remove_outside_spans, remove_overlaps_low_confidence_spans, \- remove_overlaps_min_spans, txt_spans_extractfrom mineru.version import __version__from mineru.utils.hash_utils import bytes_md5-def page_model_info_to_page_info(page_model_info, image_dict, page, image_writer, page_index, ocr_enable=False, formula_enabled=True):+def page_model_info_to_page_info(page_model_info, image_dict, page, image_writer, page_index, ocr_enable=False):scale = image_dict["scale"]page_pil_img = image_dict["img_pil"]page_img_md5 = bytes_md5(page_pil_img.tobytes())@@ -41,28 +35,34 @@ def page_model_info_to_page_info(page_model_info, image_dict, page, image_writer)"""从magic_model对象中获取后面会用到的区块信息"""- discarded_blocks = magic_model.get_discarded()- text_blocks = magic_model.get_text_blocks()- title_blocks = magic_model.get_title_blocks()- inline_equations, interline_equations, interline_equation_blocks = magic_model.get_equations()-- """获取所有的spans信息"""- spans = magic_model.get_all_spans()+ preproc_blocks = magic_model.get_preproc_blocks()+ discarded_blocks = magic_model.get_discarded_blocks()+ all_image_spans = magic_model.get_all_image_spans()++ # 对image/table/chart/interline_equation的span截图+ for span in all_image_spans:+ if span["type"] in [+ ContentType.IMAGE,+ ContentType.TABLE,+ ContentType.CHART,+ ContentType.SEAL,+ ContentType.INTERLINE_EQUATION+ ]:+ span = cut_image_and_table(span, page_pil_img, page_img_md5, page_index, image_writer, scale=scale)"""构造page_info"""- page_info = make_page_info_dict(sorted_blocks, page_index, page_w, page_h, fix_discarded_blocks)+ page_info = make_page_info_dict(preproc_blocks, page_index, page_w, page_h, discarded_blocks)return page_info-def result_to_middle_json(model_list, images_list, pdf_doc, image_writer, lang=None, ocr_enable=False, formula_enabled=True):+def result_to_middle_json(model_list, images_list, pdf_doc, image_writer, lang=None, ocr_enable=False):middle_json = {"pdf_info": [], "_backend":"pipeline", "_version_name": __version__}- formula_enabled = get_formula_enable(formula_enabled)for page_index, page_model_info in tqdm(enumerate(model_list), total=len(model_list), desc="Processing pages"):page = pdf_doc[page_index]image_dict = images_list[page_index]page_info = page_model_info_to_page_info(- page_model_info, image_dict, page, image_writer, page_index, ocr_enable=ocr_enable, formula_enabled=formula_enabled+ page_model_info, image_dict, page, image_writer, page_index, ocr_enable=ocr_enable,)if page_info is None:page_w, page_h = map(int, page.get_size())@@ -75,11 +75,11 @@ def result_to_middle_json(model_list, images_list, pdf_doc, image_writer, lang=Ntext_block_list = []for page_info in middle_json["pdf_info"]:for block in page_info['preproc_blocks']:- if block['type'] in ['table', 'image']:+ if 'blocks' in block:for sub_block in block['blocks']:- if sub_block['type'] in ['image_caption', 'image_footnote', 'table_caption', 'table_footnote']:+ if sub_block.get("type", "").endswith('caption') or sub_block.get("type", "").endswith('footnote'):text_block_list.append(sub_block)- elif block['type'] in ['text', 'title']:+ elif block["type"] not in [BlockType.INTERLINE_EQUATION, BlockType.SEAL]:text_block_list.append(block)for block in page_info['discarded_blocks']:text_block_list.append(block)diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.pyindex aeb21533..f941f43e 100644--- a/mineru/backend/pipeline/pipeline_magic_model.py+++ b/mineru/backend/pipeline/pipeline_magic_model.py@@ -17,9 +17,11 @@ class MagicModel:"doc_title": BlockType.DOC_TITLE,"figure_title": BlockType.CAPTION,"footer": BlockType.FOOTER,+ "footer_image": BlockType.FOOTER,"footnote": BlockType.PAGE_FOOTNOTE,"formula_number": BlockType.FORMULA_NUMBER,"header": BlockType.HEADER,+ "header_image": BlockType.HEADER,"image": BlockType.IMAGE,"number": BlockType.PAGE_NUMBER,"paragraph_title": BlockType.PARAGRAPH_TITLE,@@ -59,7 +61,7 @@ class MagicModel:page_pil_img=None,page_w=None,page_h=None,- ocr_enable=True,+ ocr_enable=False,):self.__page_model_info = page_model_infoself.page_inline_formula = []@@ -68,22 +70,22 @@ class MagicModel:self.image_groups = []self.table_groups = []self.chart_groups = []+ self.all_image_spans = []self.__layout_det_by_index = {}self.__scale = scaleself.__fix_axis() # bbox坐标修正,删除高度或者宽度小于等于0的spansself.__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(+ self.page_ocr_res = txt_spans_extract(page,- self.page_text_inline_formula_spans,+ self.page_ocr_res,page_pil_img,scale,[virtual_block],[],)+ self.page_text_inline_formula_spans = self.page_inline_formula + self.page_ocr_resfor layout_det in self.__page_model_info['layout_dets']:if layout_det.get('label') in self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES:@@ -101,7 +103,57 @@ class MagicModel:self.page_blocks.append(block)self.page_blocks.sort(key=lambda x: x["index"])+ self.__build_page_blocks()+ self.__classify_visual_blocks()+ self.__build_return_blocks()+++ @staticmethod+ def __fix_text_block(block):+ if block["type"] == BlockType.VERTICAL_TEXT:+ # 如果是纵向文本块,则按纵向lines处理+ block_lines = merge_spans_to_vertical_line(block['spans'])+ sort_block_lines = vertical_line_sort_spans_from_top_to_bottom(block_lines)+ else:+ block_lines = merge_spans_to_line(block['spans'])+ sort_block_lines = line_sort_spans_by_left_to_right(block_lines)++ block['lines'] = sort_block_lines+ del block['spans']+ return block++ @staticmethod+ def __copy_block_fields(block, **overrides):+ copied_block = {+ key: value+ for key, value in block.items()+ if key not in {"cls_id", "label"}+ }+ copied_block.update(overrides)+ return copied_block+++ @staticmethod+ def __is_inline_formula_block(layout_det: dict) -> bool:+ return (+ layout_det.get("label") == "inline_formula"+ 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 __build_return_blocks(self):+ self.preproc_blocks = []+ self.discarded_blocks = []+ for block in self.page_blocks:+ if block["type"] in [BlockType.HEADER, BlockType.FOOTER, BlockType.PAGE_NUMBER, BlockType.ASIDE_TEXT, BlockType.PAGE_FOOTNOTE]:+ self.discarded_blocks.append(block)+ else:+ self.preproc_blocks.append(block)+ def __build_page_blocks(self):span_type = "unknown"for block in self.page_blocks:if block["type"] in [@@ -147,11 +199,13 @@ class MagicModel:}if span_type == ContentType.TABLE:span["html"] = block["html"]+ block.pop("html")if span_type == ContentType.INTERLINE_EQUATION:span["content"] = block["latex"]if span_type == ContentType.SEAL:span["content"] = block.get("text")+ self.all_image_spans.append(span)# 构造line对象spans = [span]line = {"bbox": block["bbox"], "spans": spans}@@ -170,47 +224,6 @@ class MagicModel:block["spans"] = block_spansblock = self.__fix_text_block(block)-- self.__classify_visual_blocks()- return None--- @staticmethod- def __fix_text_block(block):- if block["type"] == BlockType.VERTICAL_TEXT:- # 如果是纵向文本块,则按纵向lines处理- block_lines = merge_spans_to_vertical_line(block['spans'])- sort_block_lines = vertical_line_sort_spans_from_top_to_bottom(block_lines)- else:- block_lines = merge_spans_to_line(block['spans'])- sort_block_lines = line_sort_spans_by_left_to_right(block_lines)-- block['lines'] = sort_block_lines- del block['spans']- return block-- @staticmethod- def __copy_block_fields(block, **overrides):- copied_block = {- key: value- for key, value in block.items()- if key not in {"cls_id", "label"}- }- copied_block.update(overrides)- return copied_block--- @staticmethod- def __is_inline_formula_block(layout_det: dict) -> bool:- return (- layout_det.get("label") == "inline_formula"- 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"]@@ -451,6 +464,15 @@ class MagicModel:def get_page_blocks(self):return self.page_blocks+ def get_all_image_spans(self):+ return self.all_image_spans++ def get_preproc_blocks(self):+ return self.preproc_blocks++ def get_discarded_blocks(self):+ return self.discarded_blocks+def get_imgs(self):return self.image_groupsdiff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex 129e3884..b080297e 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -227,7 +227,7 @@ def _process_pipeline(middle_json = pipeline_result_to_middle_json(model_list, images_list, pdf_doc, image_writer,- _lang, _ocr_enable, p_formula_enable+ _lang, _ocr_enable,)pdf_info = middle_json["pdf_info"]