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
fix: refactor markdown conversion functions for improved title handling and content merging
myhloli86116144e3e4
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.pyindex c081cd6f..91b97b34 100644--- a/mineru/backend/office/office_middle_json_mkcontent.py+++ b/mineru/backend/office/office_middle_json_mkcontent.py@@ -22,18 +22,22 @@ inline_left_delimiter = delimiters['inline']['left']inline_right_delimiter = delimiters['inline']['right']-def merge_para_with_text(para_block, formula_enable=True, img_buket_path=''):- block_text = ''+def get_title_level(para_block):+ title_level = para_block.get('level', 2)+ return title_level+++def merge_para_with_text(para_block):+ # First pass: collect all non-empty (span_type, content) parts+ parts = []+ if para_block['type'] == BlockType.TITLE:+ if para_block.get('is_numbered_style', False):+ section_number = para_block.get('section_number', '')+ if section_number:+ parts.append((ContentType.TEXT, f"{section_number} "))+for line in para_block['lines']:for span in line['spans']:- if span['type'] in [ContentType.TEXT]:- span['content'] = full_to_half_exclude_marks(span['content'])- block_text += span['content']- block_lang = detect_lang(block_text)-- para_text = ''- for i, line in enumerate(para_block['lines']):- for j, span in enumerate(line['spans']):span_type = span['type']content = ''if span_type == ContentType.TEXT:@@ -41,67 +45,67 @@ def merge_para_with_text(para_block, formula_enable=True, img_buket_path=''):elif span_type == ContentType.INLINE_EQUATION:content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"elif span_type == ContentType.INTERLINE_EQUATION:- if formula_enable:- content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"- else:- if span.get('image_path', ''):- content = f""+ content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"+ elif span_type == ContentType.HYPERLINK:+ content = f"[{span['content']}]({span.get('url', '')})"content = content.strip()if content:+ parts.append((span_type, content))- if span_type == ContentType.INTERLINE_EQUATION:- para_text += content- continue+ # Second pass: join parts, keeping one space on each side of inline equations+ para_text = ''+ for i, (span_type, content) in enumerate(parts):+ is_last = i == len(parts) - 1+ if span_type == ContentType.INLINE_EQUATION:+ # Ensure one space before the equation (if there is preceding text)+ if para_text and not para_text.endswith(' '):+ para_text += ' '+ para_text += content+ # Ensure one space after the equation, unless it is the last part+ if not is_last:+ para_text += ' '+ else:+ para_text += content- # 定义CJK语言集合(中日韩)- cjk_langs = {'zh', 'ja', 'ko'}- # logger.info(f'block_lang: {block_lang}, content: {content}')+ return para_text- # 判断是否为行末span- is_last_span = j == len(line['spans']) - 1- if block_lang in cjk_langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格- if is_last_span and span_type != ContentType.INLINE_EQUATION:- para_text += content- else:- para_text += f'{content} '+def merge_list_to_markdown(list_block):+ """Recursively convert a nested list block to markdown text."""+ result = ''+ ilevel = list_block.get('ilevel', 0)+ attribute = list_block.get('attribute', 'unordered')+ indent = ' ' * ilevel # 2 spaces per indentation level+ ordered_counter = 1++ for block in list_block.get('blocks', []):+ block_type = block['type']+ if block_type == BlockType.LIST:+ # Nested sub-list: recurse+ result += merge_list_to_markdown(block)+ else:+ # Regular text / inline-equation item+ item_text = merge_para_with_text(block)+ if item_text.strip():+ if attribute == 'ordered':+ result += f"{indent}{ordered_counter}. {item_text}\n"+ ordered_counter += 1else:- # 西方文本语境下 每行的最后一个span判断是否要去除连字符- if span_type in [ContentType.TEXT, ContentType.INLINE_EQUATION]:- # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除- if (- is_last_span- and span_type == ContentType.TEXT- and is_hyphen_at_line_end(content)- ):- # 如果下一行的第一个span是小写字母开头,删除连字符- if (- i+1 < len(para_block['lines'])- and para_block['lines'][i + 1].get('spans')- and para_block['lines'][i + 1]['spans'][0].get('type') == ContentType.TEXT- and para_block['lines'][i + 1]['spans'][0].get('content', '')- and para_block['lines'][i + 1]['spans'][0]['content'][0].islower()- ):- para_text += content[:-1]- else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格- para_text += content- else: # 西方文本语境下 content间需要空格分隔- para_text += f'{content} '- return para_text+ result += f"{indent}- {item_text}\n"++ return result-def mk_blocks_to_markdown(para_blocks, make_mode, formula_enable, table_enable, img_buket_path=''):+def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path=''):page_markdown = []for para_block in para_blocks:para_text = ''para_type = para_block['type']- if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION, BlockType.PHONETIC, BlockType.REF_TEXT]:- para_text = merge_para_with_text(para_block, formula_enable=formula_enable, img_buket_path=img_buket_path)+ if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:+ para_text = merge_para_with_text(para_block)elif para_type == BlockType.LIST:- for block in para_block['blocks']:- item_text = merge_para_with_text(block, formula_enable=formula_enable, img_buket_path=img_buket_path)- para_text += f"{item_text} \n"+ para_text = merge_list_to_markdown(para_block)elif para_type == BlockType.TITLE:title_level = get_title_level(para_block)para_text = f'{"#" * title_level} {merge_para_with_text(para_block)}'@@ -109,76 +113,33 @@ def mk_blocks_to_markdown(para_blocks, make_mode, formula_enable, table_enable,if make_mode == MakeMode.NLP_MD:continueelif make_mode == MakeMode.MM_MD:- # 检测是否存在图片脚注- has_image_footnote = any(block['type'] == BlockType.IMAGE_FOOTNOTE for block in para_block['blocks'])- # 如果存在图片脚注,则将图片脚注拼接到图片正文后面- if has_image_footnote:- for block in para_block['blocks']: # 1st.拼image_caption- if block['type'] == BlockType.IMAGE_CAPTION:- para_text += merge_para_with_text(block) + ' \n'- for block in para_block['blocks']: # 2nd.拼image_body- if block['type'] == BlockType.IMAGE_BODY:- for line in block['lines']:- for span in line['spans']:- if span['type'] == ContentType.IMAGE:- if span.get('image_path', ''):- para_text += f""- for block in para_block['blocks']: # 3rd.拼image_footnote- if block['type'] == BlockType.IMAGE_FOOTNOTE:- para_text += ' \n' + merge_para_with_text(block)- else:- for block in para_block['blocks']: # 1st.拼image_body- if block['type'] == BlockType.IMAGE_BODY:- for line in block['lines']:- for span in line['spans']:- if span['type'] == ContentType.IMAGE:- if span.get('image_path', ''):- para_text += f""- for block in para_block['blocks']: # 2nd.拼image_caption- if block['type'] == BlockType.IMAGE_CAPTION:- para_text += ' \n' + merge_para_with_text(block)+ for block in para_block['blocks']: # 1st.拼image_body+ if block['type'] == BlockType.IMAGE_BODY:+ for line in block['lines']:+ for span in line['spans']:+ if span['type'] == ContentType.IMAGE:+ if span.get('image_path', ''):+ para_text += f""+ for block in para_block['blocks']: # 2nd.拼image_caption+ if block['type'] == BlockType.IMAGE_CAPTION:+ para_text += ' \n' + merge_para_with_text(block)elif para_type == BlockType.TABLE:if make_mode == MakeMode.NLP_MD:continueelif make_mode == MakeMode.MM_MD:- for block in para_block['blocks']: # 1st.拼table_caption- if block['type'] == BlockType.TABLE_CAPTION:- para_text += merge_para_with_text(block) + ' \n'- for block in para_block['blocks']: # 2nd.拼table_body+ for block in para_block['blocks']: # 1st.拼table_bodyif block['type'] == BlockType.TABLE_BODY:for line in block['lines']:for span in line['spans']:if span['type'] == ContentType.TABLE:- # if processed by table model- if table_enable:- if span.get('html', ''):- para_text += f"\n{span['html']}\n"- elif span.get('image_path', ''):- para_text += f""- else:- if span.get('image_path', ''):- para_text += f""- for block in para_block['blocks']: # 3rd.拼table_footnote- if block['type'] == BlockType.TABLE_FOOTNOTE:- para_text += '\n' + merge_para_with_text(block) + ' '- elif para_type == BlockType.CODE:- sub_type = para_block["sub_type"]- for block in para_block['blocks']: # 1st.拼code_caption- if block['type'] == BlockType.CODE_CAPTION:- para_text += merge_para_with_text(block) + ' \n'- for block in para_block['blocks']: # 2nd.拼code_body- if block['type'] == BlockType.CODE_BODY:- if sub_type == BlockType.CODE:- guess_lang = para_block["guess_lang"]- para_text += f"```{guess_lang}\n{merge_para_with_text(block)}\n```"- elif sub_type == BlockType.ALGORITHM:- para_text += merge_para_with_text(block)-+ para_text += f"\n{span['html']}\n"+ for block in para_block['blocks']: # 2nd.拼table_caption+ if block['type'] == BlockType.TABLE_CAPTION:+ para_text += ' \n' + merge_para_with_text(block)if para_text.strip() == '':continueelse:- # page_markdown.append(para_text.strip() + ' ')page_markdown.append(para_text.strip())return page_markdown@@ -611,26 +572,22 @@ def union_make(pdf_info_dict: list,img_buket_path: str = '',):- formula_enable = get_formula_enable(os.getenv('MINERU_VLM_FORMULA_ENABLE', 'True').lower() == 'true')- table_enable = get_table_enable(os.getenv('MINERU_VLM_TABLE_ENABLE', 'True').lower() == 'true')-output_content = []for page_info in pdf_info_dict:paras_of_layout = page_info.get('para_blocks')paras_of_discarded = page_info.get('discarded_blocks')page_idx = page_info.get('page_idx')- page_size = page_info.get('page_size')if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:if not paras_of_layout:continue- page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, formula_enable, table_enable, img_buket_path)+ page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, img_buket_path)output_content.extend(page_markdown)elif make_mode == MakeMode.CONTENT_LIST:para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])if not para_blocks:continuefor para_block in para_blocks:- para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)+ para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx)output_content.append(para_content)elif make_mode == MakeMode.CONTENT_LIST_V2:# https://github.com/drunkpig/llm-webkit-mirror/blob/dev6/docs/specification/output_format/content_list_spec.md@@ -638,7 +595,7 @@ def union_make(pdf_info_dict: list,page_contents = []if para_blocks:for para_block in para_blocks:- para_content = make_blocks_to_content_list_v2(para_block, img_buket_path, page_size)+ para_content = make_blocks_to_content_list_v2(para_block, img_buket_path)page_contents.append(para_content)output_content.append(page_contents)@@ -648,11 +605,3 @@ def union_make(pdf_info_dict: list,return output_contentreturn None--def get_title_level(block):- title_level = block.get('level', 1)- if title_level > 4:- title_level = 4- elif title_level < 1:- title_level = 0- return title_level