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: enhance content list generation by adding support for SEAL and CHART block types
myhlolid3e79967df1c
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.pyindex 0fe70ff4..ef7cede3 100644--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py@@ -6,7 +6,7 @@ from loguru import loggerfrom mineru.utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_endfrom mineru.utils.config_reader import get_latex_delimiter_configfrom mineru.backend.pipeline.para_split import ListLineTag-from mineru.utils.enum_class import BlockType, ContentType, MakeMode+from mineru.utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeModefrom mineru.utils.language import detect_lang@@ -401,23 +401,222 @@ def _next_line_starts_with_lowercase_text(para_block, line_idx):return bool(next_content) and next_content[0].islower()+def merge_adjacent_ref_text_blocks_for_content(para_blocks):+ merged_blocks = []+ ref_group = []++ def flush_ref_group():+ nonlocal ref_group+ if not ref_group:+ return+ if len(ref_group) == 1:+ merged_blocks.append(ref_group[0])+ else:+ merged_blocks.append({+ 'type': BlockType.REF_TEXT,+ 'blocks': list(ref_group),+ 'bbox': ref_group[0].get('bbox'),+ })+ ref_group = []++ for para_block in para_blocks or []:+ if para_block.get('type') == BlockType.REF_TEXT:+ ref_group.append(para_block)+ continue++ flush_ref_group()+ merged_blocks.append(para_block)++ flush_ref_group()+ return merged_blocks+++def _build_bbox(para_bbox, page_size):+ if not para_bbox or not page_size:+ return None++ page_width, page_height = page_size+ x0, y0, x1, y1 = para_bbox+ return [+ int(x0 * 1000 / page_width),+ int(y0 * 1000 / page_height),+ int(x1 * 1000 / page_width),+ int(y1 * 1000 / page_height),+ ]+++def _get_seal_span(para_block):+ for line in para_block.get('lines', []):+ for span in line.get('spans', []):+ if span.get('type') == ContentType.SEAL:+ return span+ return None+++def _get_seal_text(para_block):+ seal_span = _get_seal_span(para_block)+ if not seal_span:+ return ''++ content = seal_span.get('content', '')+ if isinstance(content, list):+ return ' '.join(str(item) for item in content if str(item).strip())+ if isinstance(content, str):+ return content.strip()+ return ''+++def _get_ref_text_item_blocks(para_block):+ return para_block.get('blocks') or [para_block]+++def _split_list_item_blocks(para_block):+ item_blocks = []+ current_lines = []++ for line_idx, line in enumerate(para_block.get('lines', [])):+ if line_idx > 0 and line.get(ListLineTag.IS_LIST_START_LINE, False) and current_lines:+ item_blocks.append({+ 'type': BlockType.TEXT,+ 'lines': current_lines,+ })+ current_lines = []+ current_lines.append(line)++ if current_lines:+ item_blocks.append({+ 'type': BlockType.TEXT,+ 'lines': current_lines,+ })++ return item_blocks+++def _get_body_data(para_block):+ def get_data_from_spans(lines):+ for line in lines:+ for span in line.get('spans', []):+ span_type = span.get('type')+ if span_type == ContentType.TABLE:+ return span.get('image_path', ''), span.get('html', '')+ if span_type == ContentType.CHART:+ return span.get('image_path', ''), span.get('content', '')+ if span_type == ContentType.IMAGE:+ return span.get('image_path', ''), ''+ if span_type == ContentType.INTERLINE_EQUATION:+ return span.get('image_path', ''), span.get('content', '')+ return '', ''++ if 'blocks' in para_block:+ for block in para_block['blocks']:+ block_type = block.get('type')+ if block_type in [+ BlockType.IMAGE_BODY,+ BlockType.TABLE_BODY,+ BlockType.CHART_BODY,+ BlockType.CODE_BODY,+ ]:+ result = get_data_from_spans(block.get('lines', []))+ if result != ('', '') or block_type == BlockType.CHART_BODY:+ return result+ return '', ''++ return get_data_from_spans(para_block.get('lines', []))+++def merge_para_with_text_v2(para_block):+ block_lang = detect_lang(_collect_text_for_lang_detection(para_block))+ para_content = []+ para_type = para_block.get('type')++ for line_idx, line in enumerate(para_block.get('lines', [])):+ for span_idx, span in enumerate(line.get('spans', [])):+ span_type = span.get('type')++ if span_type == ContentType.TEXT:+ content = _normalize_text_content(span.get('content', ''))+ if not content.strip():+ continue++ output_type = (+ ContentTypeV2.SPAN_PHONETIC+ if para_type == BlockType.PHONETIC+ else ContentTypeV2.SPAN_TEXT+ )+ is_last_span = span_idx == len(line['spans']) - 1++ if block_lang in CJK_LANGS:+ rendered_content = content if is_last_span else f"{content} "+ else:+ if (+ is_last_span+ and is_hyphen_at_line_end(content)+ and _next_line_starts_with_lowercase_text(para_block, line_idx)+ ):+ rendered_content = content[:-1]+ elif is_last_span and is_hyphen_at_line_end(content):+ rendered_content = content+ else:+ rendered_content = f"{content} "++ if para_content and para_content[-1]['type'] == output_type:+ para_content[-1]['content'] += rendered_content+ else:+ para_content.append({+ 'type': output_type,+ 'content': rendered_content,+ })+ elif span_type == ContentType.INLINE_EQUATION:+ content = span.get('content', '').strip()+ if content:+ para_content.append({+ 'type': ContentTypeV2.SPAN_EQUATION_INLINE,+ 'content': content,+ })++ if para_content and para_content[-1]['type'] in [+ ContentTypeV2.SPAN_TEXT,+ ContentTypeV2.SPAN_PHONETIC,+ ]:+ para_content[-1]['content'] = para_content[-1]['content'].rstrip()++ return para_content++def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size):para_type = para_block['type']- para_content = {}+ para_content = Noneif para_type in [BlockType.TEXT,- BlockType.LIST,BlockType.INDEX,+ BlockType.LIST,+ BlockType.ABSTRACT,]:para_content = {'type': ContentType.TEXT,'text': merge_para_with_text(para_block),}- elif para_type == BlockType.DISCARDED:+ elif para_type in [+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.ASIDE_TEXT,+ BlockType.PAGE_FOOTNOTE,+ ]:para_content = {'type': para_type,'text': merge_para_with_text(para_block),}+ elif para_type == BlockType.REF_TEXT:+ para_content = {+ 'type': BlockType.LIST,+ 'sub_type': BlockType.REF_TEXT,+ 'list_items': [],+ }+ for block in _get_ref_text_item_blocks(para_block):+ item_text = merge_para_with_text(block)+ if item_text.strip():+ para_content['list_items'].append(item_text)elif para_type == BlockType.TITLE:para_content = {'type': ContentType.TEXT,@@ -436,6 +635,15 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)if para_block['lines'][0]['spans'][0].get('content', ''):para_content['text'] = merge_para_with_text(para_block)para_content['text_format'] = 'latex'+ elif para_type == BlockType.SEAL:+ seal_span = _get_seal_span(para_block)+ if not seal_span:+ return None+ para_content = {+ 'type': ContentType.SEAL,+ 'img_path': f"{img_buket_path}/{seal_span.get('image_path', '')}",+ 'text': _get_seal_text(para_block),+ }elif para_type == BlockType.IMAGE:para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}for block in para_block['blocks']:@@ -469,23 +677,289 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))if block['type'] == BlockType.TABLE_FOOTNOTE:para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))+ elif para_type == BlockType.CHART:+ para_content = {+ 'type': ContentType.CHART,+ 'img_path': '',+ 'content': '',+ BlockType.CHART_CAPTION: [],+ BlockType.CHART_FOOTNOTE: [],+ }+ for block in para_block.get('blocks', []):+ if block['type'] == BlockType.CHART_BODY:+ for line in block['lines']:+ for span in line['spans']:+ if span['type'] == ContentType.CHART and span.get('image_path', ''):+ para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"+ if block['type'] == BlockType.CHART_CAPTION:+ para_content[BlockType.CHART_CAPTION].append(merge_para_with_text(block))+ if block['type'] == BlockType.CHART_FOOTNOTE:+ para_content[BlockType.CHART_FOOTNOTE].append(merge_para_with_text(block))+ elif para_type == BlockType.CODE:+ para_content = {+ 'type': BlockType.CODE,+ 'sub_type': para_block['sub_type'],+ BlockType.CODE_CAPTION: [],+ BlockType.CODE_FOOTNOTE: [],+ }+ for block in para_block.get('blocks', []):+ render_block = _inherit_parent_code_render_metadata(block, para_block)+ if block['type'] == BlockType.CODE_BODY:+ para_content[BlockType.CODE_BODY] = merge_para_with_text(render_block)+ if block['type'] == BlockType.CODE_CAPTION:+ para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))+ if block['type'] == BlockType.CODE_FOOTNOTE:+ para_content[BlockType.CODE_FOOTNOTE].append(merge_para_with_text(block))++ if not para_content:+ return None- page_width, page_height = page_size- para_bbox = para_block.get('bbox')- if para_bbox:- x0, y0, x1, y1 = para_bbox- para_content['bbox'] = [- int(x0 * 1000 / page_width),- int(y0 * 1000 / page_height),- int(x1 * 1000 / page_width),- int(y1 * 1000 / page_height),- ]-+ bbox = _build_bbox(para_block.get('bbox'), page_size)+ if bbox:+ para_content['bbox'] = bboxpara_content['page_idx'] = page_idxreturn para_content+def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):+ para_type = para_block['type']+ para_content = None++ if para_type in [+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.ASIDE_TEXT,+ BlockType.PAGE_NUMBER,+ BlockType.PAGE_FOOTNOTE,+ ]:+ if para_type == BlockType.HEADER:+ content_type = ContentTypeV2.PAGE_HEADER+ elif para_type == BlockType.FOOTER:+ content_type = ContentTypeV2.PAGE_FOOTER+ elif para_type == BlockType.ASIDE_TEXT:+ content_type = ContentTypeV2.PAGE_ASIDE_TEXT+ elif para_type == BlockType.PAGE_NUMBER:+ content_type = ContentTypeV2.PAGE_NUMBER+ elif para_type == BlockType.PAGE_FOOTNOTE:+ content_type = ContentTypeV2.PAGE_FOOTNOTE+ else:+ raise ValueError(f"Unknown para_type: {para_type}")+ para_content = {+ 'type': content_type,+ 'content': {+ f"{content_type}_content": merge_para_with_text_v2(para_block),+ },+ }+ elif para_type == BlockType.TITLE:+ title_level = get_title_level(para_block)+ if title_level != 0:+ para_content = {+ 'type': ContentTypeV2.TITLE,+ 'content': {+ 'title_content': merge_para_with_text_v2(para_block),+ 'level': title_level,+ },+ }+ else:+ para_content = {+ 'type': ContentTypeV2.PARAGRAPH,+ 'content': {+ 'paragraph_content': merge_para_with_text_v2(para_block),+ },+ }+ elif para_type in [+ BlockType.TEXT,+ BlockType.ABSTRACT,+ ]:+ para_content = {+ 'type': ContentTypeV2.PARAGRAPH,+ 'content': {+ 'paragraph_content': merge_para_with_text_v2(para_block),+ },+ }+ elif para_type == BlockType.INTERLINE_EQUATION:+ image_path, math_content = _get_body_data(para_block)+ para_content = {+ 'type': ContentTypeV2.EQUATION_INTERLINE,+ 'content': {+ 'math_content': math_content,+ 'math_type': 'latex',+ 'image_source': {'path': f"{img_buket_path}/{image_path}"},+ },+ }+ elif para_type == BlockType.IMAGE:+ image_caption = []+ image_footnote = []+ image_path, _ = _get_body_data(para_block)+ for block in para_block.get('blocks', []):+ if block['type'] == BlockType.IMAGE_CAPTION:+ image_caption.extend(merge_para_with_text_v2(block))+ if block['type'] == BlockType.IMAGE_FOOTNOTE:+ image_footnote.extend(merge_para_with_text_v2(block))+ para_content = {+ 'type': ContentTypeV2.IMAGE,+ 'content': {+ 'image_source': {'path': f"{img_buket_path}/{image_path}"},+ 'image_caption': image_caption,+ 'image_footnote': image_footnote,+ },+ }+ elif para_type == BlockType.TABLE:+ table_caption = []+ table_footnote = []+ image_path, html = _get_body_data(para_block)+ table_html = _format_embedded_html(html, img_buket_path)+ table_nest_level = 2 if table_html.count('<table') > 1 else 1+ if 'colspan' in table_html or 'rowspan' in table_html or table_nest_level > 1:+ table_type = ContentTypeV2.TABLE_COMPLEX+ else:+ table_type = ContentTypeV2.TABLE_SIMPLE+ for block in para_block.get('blocks', []):+ if block['type'] == BlockType.TABLE_CAPTION:+ table_caption.extend(merge_para_with_text_v2(block))+ if block['type'] == BlockType.TABLE_FOOTNOTE:+ table_footnote.extend(merge_para_with_text_v2(block))+ para_content = {+ 'type': ContentTypeV2.TABLE,+ 'content': {+ 'image_source': {'path': f"{img_buket_path}/{image_path}"},+ 'table_caption': table_caption,+ 'table_footnote': table_footnote,+ 'html': table_html,+ 'table_type': table_type,+ 'table_nest_level': table_nest_level,+ },+ }+ elif para_type == BlockType.CHART:+ chart_caption = []+ chart_footnote = []+ image_path, _ = _get_body_data(para_block)+ for block in para_block.get('blocks', []):+ if block['type'] == BlockType.CHART_CAPTION:+ chart_caption.extend(merge_para_with_text_v2(block))+ if block['type'] == BlockType.CHART_FOOTNOTE:+ chart_footnote.extend(merge_para_with_text_v2(block))+ para_content = {+ 'type': ContentTypeV2.CHART,+ 'content': {+ 'image_source': {'path': f"{img_buket_path}/{image_path}"},+ 'content': '',+ 'chart_caption': chart_caption,+ 'chart_footnote': chart_footnote,+ },+ }+ elif para_type == BlockType.CODE:+ code_caption = []+ code_footnote = []+ code_content = []+ for block in para_block.get('blocks', []):+ if block['type'] == BlockType.CODE_CAPTION:+ code_caption.extend(merge_para_with_text_v2(block))+ if block['type'] == BlockType.CODE_FOOTNOTE:+ code_footnote.extend(merge_para_with_text_v2(block))+ if block['type'] == BlockType.CODE_BODY:+ code_content = merge_para_with_text_v2(block)++ sub_type = para_block['sub_type']+ if sub_type == BlockType.CODE:+ para_content = {+ 'type': ContentTypeV2.CODE,+ 'content': {+ 'code_caption': code_caption,+ 'code_content': code_content,+ 'code_footnote': code_footnote,+ 'code_language': para_block.get('guess_lang', 'txt'),+ },+ }+ elif sub_type == BlockType.ALGORITHM:+ para_content = {+ 'type': ContentTypeV2.ALGORITHM,+ 'content': {+ 'algorithm_caption': code_caption,+ 'algorithm_content': code_content,+ 'algorithm_footnote': code_footnote,+ },+ }+ else:+ raise ValueError(f"Unknown code sub_type: {sub_type}")+ elif para_type == BlockType.REF_TEXT:+ list_items = []+ for block in _get_ref_text_item_blocks(para_block):+ item_content = merge_para_with_text_v2(block)+ if item_content:+ list_items.append({+ 'item_type': 'text',+ 'item_content': item_content,+ })+ para_content = {+ 'type': ContentTypeV2.LIST,+ 'content': {+ 'list_type': ContentTypeV2.LIST_REF,+ 'list_items': list_items,+ },+ }+ elif para_type == BlockType.LIST:+ list_items = []+ for block in _split_list_item_blocks(para_block):+ item_content = merge_para_with_text_v2(block)+ if item_content:+ list_items.append({+ 'item_type': 'text',+ 'item_content': item_content,+ })+ para_content = {+ 'type': ContentTypeV2.LIST,+ 'content': {+ 'list_type': ContentTypeV2.LIST_TEXT,+ 'attribute': para_block.get('attribute', 'unordered'),+ 'list_items': list_items,+ },+ }+ elif para_type == BlockType.INDEX:+ list_items = []+ for block in _split_list_item_blocks(para_block):+ item_content = merge_para_with_text_v2(block)+ if item_content:+ list_items.append({+ 'item_type': 'text',+ 'item_content': item_content,+ })+ para_content = {+ 'type': ContentTypeV2.INDEX,+ 'content': {+ 'list_type': ContentTypeV2.LIST_TEXT,+ 'list_items': list_items,+ },+ }+ elif para_type == BlockType.SEAL:+ seal_span = _get_seal_span(para_block)+ if not seal_span:+ return None+ seal_text = _get_seal_text(para_block)+ para_content = {+ 'type': ContentTypeV2.SEAL,+ 'content': {+ 'image_source': {+ 'path': f"{img_buket_path}/{seal_span.get('image_path', '')}",+ },+ 'seal_content': (+ [{'type': ContentTypeV2.SPAN_TEXT, 'content': seal_text}]+ if seal_text else []+ ),+ },+ }++ if not para_content:+ return None++ bbox = _build_bbox(para_block.get('bbox'), page_size)+ if bbox:+ para_content['bbox'] = bbox++ return para_content++def union_make(pdf_info_dict: list,make_mode: str,img_buket_path: str = '',@@ -502,17 +976,30 @@ def union_make(pdf_info_dict: list,page_markdown = make_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 [])+ para_blocks = merge_adjacent_ref_text_blocks_for_content(+ (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)if para_content:output_content.append(para_content)+ elif make_mode == MakeMode.CONTENT_LIST_V2:+ para_blocks = merge_adjacent_ref_text_blocks_for_content(+ (paras_of_layout or []) + (paras_of_discarded or [])+ )+ 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)+ if para_content:+ page_contents.append(para_content)+ output_content.append(page_contents)if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:return '\n\n'.join(output_content)- elif make_mode == MakeMode.CONTENT_LIST:+ elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:return output_contentelse:logger.error(f"Unsupported make mode: {make_mode}")@@ -521,9 +1008,7 @@ def union_make(pdf_info_dict: list,def get_title_level(block):title_level = block.get('level', 1)- if title_level > 4:- title_level = 4- elif title_level < 1:+ if title_level < 1:title_level = 0return title_leveldiff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.pyindex c081cd6f..a1128af5 100644--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py@@ -261,8 +261,6 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)for block in para_block['blocks']:if block['type'] == BlockType.CODE_BODY:para_content[BlockType.CODE_BODY] = merge_para_with_text(block)- if para_block["sub_type"] == BlockType.CODE:- para_content["guess_lang"] = para_block["guess_lang"]if block['type'] == BlockType.CODE_CAPTION:para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))diff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex c0a51bfc..d20d943f 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -172,17 +172,18 @@ def _process_output()if f_dump_content_list:+content_list = make_func(pdf_info, MakeMode.CONTENT_LIST, image_dir)md_writer.write_string(f"{pdf_file_name}_content_list.json",json.dumps(content_list, ensure_ascii=False, indent=4),)- if process_mode != "pipeline":- content_list_v2 = make_func(pdf_info, MakeMode.CONTENT_LIST_V2, image_dir)- md_writer.write_string(- f"{pdf_file_name}_content_list_v2.json",- json.dumps(content_list_v2, ensure_ascii=False, indent=4),- )++ content_list_v2 = make_func(pdf_info, MakeMode.CONTENT_LIST_V2, image_dir)+ md_writer.write_string(+ f"{pdf_file_name}_content_list_v2.json",+ json.dumps(content_list_v2, ensure_ascii=False, indent=4),+ )if f_dump_middle_json:diff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.pyindex 2c84ed00..bf990a8b 100644--- a/mineru/utils/enum_class.py+++ b/mineru/utils/enum_class.py@@ -65,6 +65,7 @@ class ContentTypeV2:ALGORITHM = "algorithm"EQUATION_INTERLINE = 'equation_interline'IMAGE = 'image'+ SEAL = 'seal'TABLE = 'table'CHART = 'chart'TABLE_SIMPLE = 'simple_table'