Skip to content

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

feat: add support for base64 image handling in table HTML and normalize embedded content

myhloli5a6caa18dd87
diff --git a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py
index d1d4d4fc..0a331445 100644
--- a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py
@@ -1,6 +1,8 @@
# Copyright (c) Opendatalab. All rights reserved.
+import base64
import os
+import re
import time
import cv2
@@ -12,8 +14,8 @@ from mineru.backend.hybrid.hybrid_magic_model import MagicModel
from mineru.backend.utils import cross_page_table_merge
from mineru.utils.config_reader import get_table_enable, get_llm_aided_config
from mineru.utils.cut_image import cut_image_and_table
-from mineru.utils.enum_class import ContentType
-from mineru.utils.hash_utils import bytes_md5
+from mineru.utils.enum_class import BlockType, ContentType
+from mineru.utils.hash_utils import bytes_md5, str_sha256
from mineru.utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_needed
from mineru.utils.pdf_image_tools import get_crop_img
from mineru.utils.pdfium_guard import close_pdfium_document, pdfium_guard
@@ -34,6 +36,65 @@ if llm_aided_config:
"please execute `pip install mineru[core]` to install the required packages.")
+def _save_base64_image(b64_data_uri: str, image_writer, page_index: int):
+ """Persist a data-URI image via image_writer and return a relative path."""
+ m = re.match(r'data:image/(\w+);base64,(.+)', b64_data_uri, re.DOTALL)
+ if not m:
+ logger.warning(f"Unrecognized image_base64 format in page {page_index}, skipping.")
+ return None
+
+ fmt = m.group(1)
+ ext = "jpg" if fmt == "jpeg" else fmt
+ try:
+ img_bytes = base64.b64decode(m.group(2))
+ except Exception as e:
+ logger.warning(f"Failed to decode image_base64 on page {page_index}: {e}")
+ return None
+
+ img_path = f"{str_sha256(b64_data_uri)}.{ext}"
+ image_writer.write(img_path, img_bytes)
+ return img_path
+
+
+def _replace_inline_base64_img_src(markup: str, image_writer, page_index: int) -> str:
+ """Replace inline base64 image sources in table HTML with local relative paths."""
+ if not markup or "base64," not in markup:
+ return markup
+
+ def _replace_src(match, _writer=image_writer, _idx=page_index):
+ img_path = _save_base64_image(match.group(1), _writer, _idx)
+ if img_path:
+ return f'src="{img_path}"'
+ return match.group(0)
+
+ return re.sub(
+ r'src="(data:image/[^"]+)"',
+ _replace_src,
+ markup,
+ )
+
+
+def _replace_inline_table_images(table_blocks: list[dict], image_writer, page_index: int) -> None:
+ """Persist inline base64 images embedded inside table HTML."""
+ if not image_writer:
+ return
+
+ for block in table_blocks:
+ for sub_block in block.get("blocks", []):
+ if sub_block.get("type") != BlockType.TABLE_BODY:
+ continue
+
+ for line in sub_block.get("lines", []):
+ for span in line.get("spans", []):
+ if span.get("type") != ContentType.TABLE:
+ continue
+ span["html"] = _replace_inline_base64_img_src(
+ span.get("html", ""),
+ image_writer,
+ page_index,
+ )
+
+
def blocks_to_page_info(
page_model_list,
image_dict,
@@ -112,6 +173,8 @@ def blocks_to_page_info(
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)
+ _replace_inline_table_images(table_blocks, image_writer, page_index)
+
page_blocks = []
page_blocks.extend([
*image_blocks,
diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.py
index 01cdfe2e..2101af09 100644
--- a/mineru/backend/vlm/model_output_to_middle_json.py
+++ b/mineru/backend/vlm/model_output_to_middle_json.py
@@ -1,4 +1,6 @@
+import base64
import os
+import re
import time
import cv2
@@ -10,8 +12,8 @@ from mineru.backend.utils import cross_page_table_merge
from mineru.backend.vlm.vlm_magic_model import MagicModel
from mineru.utils.config_reader import get_table_enable, get_llm_aided_config
from mineru.utils.cut_image import cut_image_and_table
-from mineru.utils.enum_class import ContentType
-from mineru.utils.hash_utils import bytes_md5
+from mineru.utils.enum_class import BlockType, ContentType
+from mineru.utils.hash_utils import bytes_md5, str_sha256
from mineru.utils.pdf_image_tools import get_crop_img
from mineru.utils.pdfium_guard import close_pdfium_document, pdfium_guard
from mineru.version import __version__
@@ -31,6 +33,65 @@ if llm_aided_config:
"please execute `pip install mineru[core]` to install the required packages.")
+def _save_base64_image(b64_data_uri: str, image_writer, page_index: int):
+ """Persist a data-URI image via image_writer and return a relative path."""
+ m = re.match(r'data:image/(\w+);base64,(.+)', b64_data_uri, re.DOTALL)
+ if not m:
+ logger.warning(f"Unrecognized image_base64 format in page {page_index}, skipping.")
+ return None
+
+ fmt = m.group(1)
+ ext = "jpg" if fmt == "jpeg" else fmt
+ try:
+ img_bytes = base64.b64decode(m.group(2))
+ except Exception as e:
+ logger.warning(f"Failed to decode image_base64 on page {page_index}: {e}")
+ return None
+
+ img_path = f"{str_sha256(b64_data_uri)}.{ext}"
+ image_writer.write(img_path, img_bytes)
+ return img_path
+
+
+def _replace_inline_base64_img_src(markup: str, image_writer, page_index: int) -> str:
+ """Replace inline base64 image sources in table HTML with local relative paths."""
+ if not markup or "base64," not in markup:
+ return markup
+
+ def _replace_src(match, _writer=image_writer, _idx=page_index):
+ img_path = _save_base64_image(match.group(1), _writer, _idx)
+ if img_path:
+ return f'src="{img_path}"'
+ return match.group(0)
+
+ return re.sub(
+ r'src="(data:image/[^"]+)"',
+ _replace_src,
+ markup,
+ )
+
+
+def _replace_inline_table_images(table_blocks: list[dict], image_writer, page_index: int) -> None:
+ """Persist inline base64 images embedded inside table HTML."""
+ if not image_writer:
+ return
+
+ for block in table_blocks:
+ for sub_block in block.get("blocks", []):
+ if sub_block.get("type") != BlockType.TABLE_BODY:
+ continue
+
+ for line in sub_block.get("lines", []):
+ for span in line.get("spans", []):
+ if span.get("type") != ContentType.TABLE:
+ continue
+ span["html"] = _replace_inline_base64_img_src(
+ span.get("html", ""),
+ image_writer,
+ page_index,
+ )
+
+
def blocks_to_page_info(page_blocks, image_dict, page, image_writer, page_index) -> dict:
"""将blocks转换为页面信息"""
@@ -83,6 +144,8 @@ def blocks_to_page_info(page_blocks, image_dict, page, image_writer, page_index)
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)
+ _replace_inline_table_images(table_blocks, image_writer, page_index)
+
page_blocks = []
page_blocks.extend([
*image_blocks,
diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
index 0b542058..3b906b9f 100644
--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py
+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
@@ -1,4 +1,6 @@
import os
+import re
+from html import unescape
from loguru import logger
@@ -22,6 +24,38 @@ inline_left_delimiter = delimiters['inline']['left']
inline_right_delimiter = delimiters['inline']['right']
+def _prefix_table_img_src(html, img_buket_path):
+ """Prefix non-data image sources in table HTML with img_buket_path."""
+ if not html or not img_buket_path:
+ return html
+
+ return re.sub(
+ r'src="(?!data:)([^"]+)"',
+ lambda match: f'src="{img_buket_path}/{match.group(1)}"',
+ html,
+ )
+
+
+def _replace_eq_tags_in_table_html(html):
+ """Replace <eq>...</eq> tags in table HTML with inline math delimiters."""
+ if not html:
+ return html
+
+ return re.sub(
+ r'<eq>(.*?)</eq>',
+ lambda match: (
+ f" {inline_left_delimiter}{unescape(match.group(1))}{inline_right_delimiter} "
+ ),
+ html,
+ flags=re.DOTALL,
+ )
+
+
+def _format_embedded_html(html, img_buket_path):
+ """Normalize embedded table HTML for markdown/content outputs."""
+ return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_buket_path))
+
+
def merge_para_with_text(para_block, formula_enable=True, img_buket_path=''):
block_text = ''
for line in para_block['lines']:
@@ -153,7 +187,7 @@ def mk_blocks_to_markdown(para_blocks, make_mode, formula_enable, table_enable,
# if processed by table model
if table_enable:
if span.get('html', ''):
- para_text += f"\n{span['html']}\n"
+ para_text += f"\n{_format_embedded_html(span['html'], img_buket_path)}\n"
elif span.get('image_path', ''):
para_text += f"![]({img_buket_path}/{span['image_path']})"
else:
@@ -247,7 +281,10 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)
if span['type'] == ContentType.TABLE:
if span.get('html', ''):
- para_content[BlockType.TABLE_BODY] = f"{span['html']}"
+ para_content[BlockType.TABLE_BODY] = _format_embedded_html(
+ span['html'],
+ img_buket_path,
+ )
if span.get('image_path', ''):
para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
@@ -373,16 +410,17 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
table_caption = []
table_footnote = []
image_path, html = get_body_data(para_block)
+ table_html = _format_embedded_html(html, img_buket_path)
image_source = {
'path': f"{img_buket_path}/{image_path}",
}
- if html.count("<table") > 1:
+ if table_html.count("<table") > 1:
table_nest_level = 2
else:
table_nest_level = 1
if (
- "colspan" in html or
- "rowspan" in html or
+ "colspan" in table_html or
+ "rowspan" in table_html or
table_nest_level > 1
):
table_type = ContentTypeV2.TABLE_COMPLEX
@@ -400,7 +438,7 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
'image_source': image_source,
'table_caption': table_caption,
'table_footnote': table_footnote,
- 'html': html,
+ 'html': table_html,
'table_type': table_type,
'table_nest_level': table_nest_level,
}