Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: add chart support in document processing with new block types and handling

myhloli693ac8d6aa3e
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.py
index 3fc87d47..0a4f4982 100644
--- a/mineru/backend/office/model_output_to_middle_json.py
+++ b/mineru/backend/office/model_output_to_middle_json.py
@@ -38,6 +38,36 @@ def _save_base64_image(b64_data_uri: str, image_writer, page_index: int):
return img_path
+def _save_span_image_if_needed(span: dict, image_writer, page_index: int) -> None:
+ """Persist a span-level base64 image and normalize the image_path field."""
+ img_b64 = span.get("image_base64", "")
+ if img_b64:
+ img_path = _save_base64_image(img_b64, image_writer, page_index)
+ if img_path:
+ span["image_path"] = img_path
+ del span["image_base64"]
+ return
+ span.setdefault("image_path", "")
+
+
+def _replace_inline_base64_img_src(markup: str, image_writer, page_index: int) -> str:
+ """Replace inline base64 image sources in HTML-like markup with saved local paths."""
+ if not markup or "base64," not in markup:
+ return markup
+
+ def _replace_src(m_src, _writer=image_writer, _idx=page_index):
+ img_path = _save_base64_image(m_src.group(1), _writer, _idx)
+ if img_path:
+ return f'src="{img_path}"'
+ return m_src.group(0)
+
+ return re.sub(
+ r'src="(data:image/[^"]+)"',
+ _replace_src,
+ markup,
+ )
+
+
def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:
"""将blocks转换为页面信息"""
@@ -52,15 +82,10 @@ def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:
continue
for line in sub_block.get("lines", []):
for span in line.get("spans", []):
- img_b64 = span.get("image_base64", "")
- if not img_b64:
- continue
- img_path = _save_base64_image(img_b64, image_writer, page_index)
- if img_path:
- span["image_path"] = img_path
- del span["image_base64"]
+ _save_span_image_if_needed(span, image_writer, page_index)
table_blocks = magic_model.get_table_blocks()
+ chart_blocks = magic_model.get_chart_blocks()
# Replace inline base64 images inside table HTML with local paths
if image_writer:
@@ -72,21 +97,35 @@ def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:
for span in line.get("spans", []):
if span.get("type") != "table":
continue
- html = span.get("html", "")
- if not html or "base64," not in html:
- continue
-
- def _replace_src(m_src, _writer=image_writer, _idx=page_index):
- img_path = _save_base64_image(m_src.group(1), _writer, _idx)
- if img_path:
- return f'src="{img_path}"'
- return m_src.group(0) # keep original on failure
+ span["html"] = _replace_inline_base64_img_src(
+ span.get("html", ""),
+ image_writer,
+ page_index,
+ )
- span["html"] = re.sub(
- r'src="(data:image/[^"]+)"',
- _replace_src,
- html,
+ for chart_block in chart_blocks:
+ for sub_block in chart_block.get("blocks", []):
+ if sub_block.get("type") != "chart_body":
+ continue
+ for line in sub_block.get("lines", []):
+ for span in line.get("spans", []):
+ if span.get("type") != "chart":
+ continue
+ _save_span_image_if_needed(span, image_writer, page_index)
+ span["content"] = _replace_inline_base64_img_src(
+ span.get("content", ""),
+ image_writer,
+ page_index,
)
+ else:
+ for chart_block in chart_blocks:
+ for sub_block in chart_block.get("blocks", []):
+ if sub_block.get("type") != "chart_body":
+ continue
+ for line in sub_block.get("lines", []):
+ for span in line.get("spans", []):
+ if span.get("type") == "chart":
+ span.setdefault("image_path", "")
title_blocks = magic_model.get_title_blocks()
discarded_blocks = magic_model.get_discarded_blocks()
@@ -98,6 +137,7 @@ def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:
page_blocks = []
page_blocks.extend([
*image_blocks,
+ *chart_blocks,
*table_blocks,
*title_blocks,
*text_blocks,
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index cdbdb213..cd0141a7 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -22,7 +22,7 @@ class MagicModel:
block_type = block_info["type"]
block_content = block_info.get("content", "")
- if not block_content:
+ if not block_content and block_type != BlockType.CHART:
continue
if block_type in [
@@ -30,6 +30,7 @@ class MagicModel:
"title",
"image_caption",
"table_caption",
+ "chart_caption",
"header",
"footer",
]:
@@ -47,6 +48,15 @@ class MagicModel:
"type": ContentType.TABLE,
"html": clean_table_html(block_content),
}
+ elif block_type in ["chart"]:
+ block_type = BlockType.CHART_BODY
+ span = {
+ "type": ContentType.CHART,
+ "content": block_content,
+ "image_path": block_info.get("image_path", ""),
+ }
+ if block_info.get("image_base64"):
+ span["image_base64"] = block_info["image_base64"]
elif block_type in ["equation"]:
block_type = BlockType.INTERLINE_EQUATION
span = {
@@ -103,6 +113,7 @@ class MagicModel:
self.image_blocks = []
self.table_blocks = []
+ self.chart_blocks = []
self.interline_equation_blocks = []
self.text_blocks = []
self.title_blocks = []
@@ -117,6 +128,8 @@ class MagicModel:
self.image_blocks.append(block)
elif block["type"] in [BlockType.TABLE_BODY, BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE]:
self.table_blocks.append(block)
+ elif block["type"] in [BlockType.CHART_BODY, BlockType.CHART_CAPTION]:
+ self.chart_blocks.append(block)
elif block["type"] in [BlockType.CODE_BODY, BlockType.CODE_CAPTION]:
self.code_blocks.append(block)
elif block["type"] == BlockType.INTERLINE_EQUATION:
@@ -140,8 +153,9 @@ class MagicModel:
self.image_blocks, not_include_image_blocks = fix_two_layer_blocks(self.image_blocks, BlockType.IMAGE)
self.table_blocks, not_include_table_blocks = fix_two_layer_blocks(self.table_blocks, BlockType.TABLE)
+ self.chart_blocks, not_include_chart_blocks = fix_two_layer_blocks(self.chart_blocks, BlockType.CHART)
- for block in not_include_image_blocks + not_include_table_blocks:
+ for block in not_include_image_blocks + not_include_table_blocks + not_include_chart_blocks:
block["type"] = BlockType.TEXT
self.text_blocks.append(block)
@@ -158,6 +172,9 @@ class MagicModel:
def get_table_blocks(self):
return self.table_blocks
+ def get_chart_blocks(self):
+ return self.chart_blocks
+
def get_code_blocks(self):
return self.code_blocks
@@ -574,7 +591,7 @@ def __tie_up_category_by_index(blocks, subject_block_type, object_block_type):
)
-def get_type_blocks(blocks, block_type: Literal["image", "table"]):
+def get_type_blocks(blocks, block_type: Literal["image", "table", "chart"]):
with_captions = __tie_up_category_by_index(blocks, f"{block_type}_body", f"{block_type}_caption")
ret = []
for v in with_captions:
@@ -586,7 +603,7 @@ def get_type_blocks(blocks, block_type: Literal["image", "table"]):
return ret
-def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table"]):
+def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "chart"]):
need_fix_blocks = get_type_blocks(blocks, fix_type)
fixed_blocks = []
not_include_blocks = []
@@ -657,27 +674,29 @@ def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table"]):
def classify_caption_blocks(page_blocks: list) -> list:
"""
- 对page_blocks中的caption块进行分类,将其分类为image_caption或table_caption。
+ 对page_blocks中的caption块进行分类,将其分类为image_caption、table_caption或chart_caption。
规则:
- 1. 只有与type为table或image相邻的caption可以作为caption
- 2. caption块与table或image中相隔的块全部是caption的情况视为该caption块与table或image相邻
- 3. caption的类型与他前置位相邻的母块type一致(table或image),如果没有前置位母块则检查是否有后置位母块
+ 1. 只有与type为table、image或chart相邻的caption可以作为caption
+ 2. caption块与table、image或chart中相隔的块全部是caption的情况视为该caption块与母块相邻
+ 3. caption的类型与他前置位相邻的母块type一致,如果没有前置位母块则检查是否有后置位母块
4. 没有相邻母块的caption需要变更type为text
- 5. 当一个block的type是table或image时,其后续的第一个text块如果以特定前缀开头,则将其设置为相应的caption类型
+ 5. 当一个block的type是table、image或chart时,其后续的第一个text块如果以特定前缀开头,则将其设置为相应的caption类型
- table后的text块以["表", "table"]开头(不区分大小写)-> table_caption
- image后的text块以["图", "fig"]开头(不区分大小写)-> image_caption
+ - chart后的text块以["图", "fig", "chart"]开头(不区分大小写)-> chart_caption
"""
if not page_blocks:
return page_blocks
- available_types = ["table", "image"]
+ available_types = ["table", "image", "chart"]
# 定义caption前缀匹配规则
table_caption_prefixes = ["表", "table"]
image_caption_prefixes = ["图", "fig"]
+ chart_caption_prefixes = ["图", "fig", "chart"]
- # 第一步:处理table/image后续的text块,将符合条件的text块标记为caption
+ # 第一步:处理table/image/chart后续的text块,将符合条件的text块标记为caption
preprocessed_blocks = []
n = len(page_blocks)
@@ -709,6 +728,12 @@ def classify_caption_blocks(page_blocks: list) -> list:
next_block = next_block.copy()
next_block["type"] = "caption"
page_blocks[i + 1] = next_block
+ elif block_type == "chart":
+ if any(content.startswith(prefix.lower()) for prefix in chart_caption_prefixes):
+ # 将text块标记为caption,后续会被处理为chart_caption
+ next_block = next_block.copy()
+ next_block["type"] = "caption"
+ page_blocks[i + 1] = next_block
else:
preprocessed_blocks.append(block)
@@ -720,7 +745,7 @@ def classify_caption_blocks(page_blocks: list) -> list:
result_blocks.append(block)
continue
- # 查找前置位相邻的母块(table或image)
+ # 查找前置位相邻的母块(table、image或chart)
# 向前查找,跳过连续的caption块
prev_parent_type = None
j = i - 1
@@ -733,10 +758,10 @@ def classify_caption_blocks(page_blocks: list) -> list:
# 继续向前查找
j -= 1
else:
- # 遇到非caption且非table/image的块,停止查找
+ # 遇到非caption且非table/image/chart的块,停止查找
break
- # 查找后置位相邻的母块(table或image)
+ # 查找后置位相邻的母块(table、image或chart)
# 向后查找,跳过连续的caption块
next_parent_type = None
k = i + 1
@@ -749,7 +774,7 @@ def classify_caption_blocks(page_blocks: list) -> list:
# 继续向后查找
k += 1
else:
- # 遇到非caption且非table/image的块,停止查找
+ # 遇到非caption且非table/image/chart的块,停止查找
break
# 根据规则确定caption类型
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
index 54396c61..22321470 100644
--- a/mineru/backend/office/office_middle_json_mkcontent.py
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -143,6 +143,20 @@ def _replace_eq_tags_in_table_html(html: str) -> str:
)
+def _format_embedded_html(html: str, img_buket_path: str) -> str:
+ """Apply image-path prefixing and equation replacement for HTML-like content."""
+ return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_buket_path))
+
+
+def _build_media_path(img_buket_path: str, image_path: str) -> str:
+ """Build a display path while keeping empty image references empty."""
+ if not image_path:
+ return ''
+ if not img_buket_path:
+ return image_path
+ return f"{img_buket_path}/{image_path}"
+
+
def get_title_level(para_block):
title_level = para_block.get('level', 2)
return title_level
@@ -500,10 +514,24 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=No
for line in block['lines']:
for span in line['spans']:
if span['type'] == ContentType.TABLE:
- para_text += f"\n{_replace_eq_tags_in_table_html(_prefix_table_img_src(span['html'], img_buket_path))}\n"
+ para_text += f"\n{_format_embedded_html(span['html'], img_buket_path)}\n"
for block in para_block['blocks']: # 2nd.拼table_caption
if block['type'] == BlockType.TABLE_CAPTION:
para_text += ' \n' + merge_para_with_text(block)
+ elif para_type == BlockType.CHART:
+ if make_mode == MakeMode.NLP_MD:
+ continue
+ elif make_mode == MakeMode.MM_MD:
+ image_path, chart_content = get_body_data(para_block)
+ if chart_content:
+ para_text += f"\n{_format_embedded_html(chart_content, img_buket_path)}\n"
+ elif image_path:
+ para_text += f"![]({_build_media_path(img_buket_path, image_path)})"
+ else:
+ continue
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.CHART_CAPTION:
+ para_text += ' \n' + merge_para_with_text(block)
if para_text.strip() == '':
continue
else:
@@ -568,9 +596,32 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx):
for span in line['spans']:
if span['type'] == ContentType.TABLE:
if span.get('html', ''):
- para_content[BlockType.TABLE_BODY] = _replace_eq_tags_in_table_html(_prefix_table_img_src(span['html'], img_buket_path))
+ para_content[BlockType.TABLE_BODY] = _format_embedded_html(span['html'], img_buket_path)
if block['type'] == BlockType.TABLE_CAPTION:
para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
+ elif para_type == BlockType.CHART:
+ para_content = {
+ 'type': ContentType.CHART,
+ 'img_path': '',
+ 'content': '',
+ BlockType.CHART_CAPTION: [],
+ }
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.CHART_BODY:
+ for line in block['lines']:
+ for span in line['spans']:
+ if span['type'] == ContentType.CHART:
+ para_content['img_path'] = _build_media_path(
+ img_buket_path,
+ span.get('image_path', ''),
+ )
+ if span.get('content', ''):
+ para_content['content'] = _format_embedded_html(
+ span['content'],
+ img_buket_path,
+ )
+ if block['type'] == BlockType.CHART_CAPTION:
+ para_content[BlockType.CHART_CAPTION].append(merge_para_with_text(block))
para_content['page_idx'] = page_idx
anchor = para_block.get("anchor")
@@ -673,11 +724,27 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path):
'type': ContentTypeV2.TABLE,
'content': {
'table_caption': table_caption,
- 'html': _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_buket_path)),
+ 'html': _format_embedded_html(html, img_buket_path),
'table_type': table_type,
'table_nest_level': table_nest_level,
}
}
+ elif para_type == BlockType.CHART:
+ chart_caption = []
+ image_path, chart_content = get_body_data(para_block)
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.CHART_CAPTION:
+ chart_caption.extend(merge_para_with_text_v2(block))
+ para_content = {
+ 'type': ContentTypeV2.CHART,
+ 'content': {
+ 'image_source': {
+ 'path': _build_media_path(img_buket_path, image_path),
+ },
+ 'content': _format_embedded_html(chart_content, img_buket_path),
+ 'chart_caption': chart_caption,
+ }
+ }
elif para_type == BlockType.LIST:
list_type = ContentTypeV2.LIST_TEXT
attribute = para_block.get('attribute', 'unordered')
@@ -707,10 +774,11 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path):
def get_body_data(para_block):
"""
- Extract image_path and html from para_block
+ Extract image_path and body content from para_block
Returns:
- For IMAGE/INTERLINE_EQUATION: (image_path, '')
- For TABLE: (image_path, html)
+ - For CHART: (image_path, content)
- Default: ('', '')
"""
@@ -720,6 +788,8 @@ def get_body_data(para_block):
span_type = span.get('type')
if span_type == ContentType.TABLE:
return span.get('image_path', ''), span.get('html', '')
+ elif span_type == ContentType.CHART:
+ return span.get('image_path', ''), span.get('content', '')
elif span_type == ContentType.IMAGE:
return span.get('image_path', ''), ''
elif span_type == ContentType.INTERLINE_EQUATION:
@@ -732,10 +802,12 @@ def get_body_data(para_block):
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.CODE_BODY]:
+ 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 != ('', ''):
return result
+ if block_type == BlockType.CHART_BODY:
+ return result
return '', ''
# 处理直接包含 lines 的结构
diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.py
index 4367f002..63a5bf61 100644
--- a/mineru/model/docx/docx_converter.py
+++ b/mineru/model/docx/docx_converter.py
@@ -2455,13 +2455,13 @@ class DocxConverter:
".//c:chart", namespaces=DocxConverter._BLIP_NAMESPACES
)
if chart is not None:
- # 如果找到 chart 元素,构造空的表格块,后续回填html
- table_block = {
- "type": BlockType.TABLE,
+ # 如果找到 chart 元素,构造空的图表块,后续回填 html。
+ chart_block = {
+ "type": BlockType.CHART,
"content": "",
}
- self.cur_page.append(table_block)
- self.chart_list.append(table_block)
+ self.cur_page.append(chart_block)
+ self.chart_list.append(chart_block)
def _add_chart_table(self):
idx_xlsx_map = {}
diff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.py
index 4dd50861..f07c17f2 100644
--- a/mineru/utils/enum_class.py
+++ b/mineru/utils/enum_class.py
@@ -3,11 +3,14 @@ from enum import Enum
class BlockType:
IMAGE = 'image'
TABLE = 'table'
+ CHART = 'chart'
IMAGE_BODY = 'image_body'
TABLE_BODY = 'table_body'
+ CHART_BODY = 'chart_body'
CAPTION = 'caption' # generic caption type (e.g., for Word documents)
IMAGE_CAPTION = 'image_caption'
TABLE_CAPTION = 'table_caption'
+ CHART_CAPTION = 'chart_caption'
IMAGE_FOOTNOTE = 'image_footnote'
TABLE_FOOTNOTE = 'table_footnote'
TEXT = 'text'
@@ -35,6 +38,7 @@ class BlockType:
class ContentType:
IMAGE = 'image'
TABLE = 'table'
+ CHART = 'chart'
TEXT = 'text'
INTERLINE_EQUATION = 'interline_equation'
INLINE_EQUATION = 'inline_equation'
@@ -49,6 +53,7 @@ class ContentTypeV2:
EQUATION_INTERLINE = 'equation_interline'
IMAGE = 'image'
TABLE = 'table'
+ CHART = 'chart'
TABLE_SIMPLE = 'simple_table'
TABLE_COMPLEX = 'complex_table'
LIST = 'list'