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: implement base64 image handling utilities for HTML and table content
myhloli4a807320a0b0
diff --git a/mineru/backend/html_image_utils.py b/mineru/backend/html_image_utils.pynew file mode 100644index 00000000..4340115d--- /dev/null+++ b/mineru/backend/html_image_utils.py@@ -0,0 +1,105 @@+import base64+import re++from loguru import logger++from mineru.utils.enum_class import BlockType, ContentType+from mineru.utils.hash_utils import str_sha256+++def _normalize_image_extension(fmt: str) -> str:+ normalized = fmt.lower().split("+", 1)[0]+ return "jpg" if normalized == "jpeg" else normalized+++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."""+ if not image_writer:+ return None++ match = re.match(r"data:image/([^;]+);base64,(.+)", b64_data_uri, re.DOTALL)+ if not match:+ logger.warning(f"Unrecognized image_base64 format in page {page_index}, skipping.")+ return None++ fmt = _normalize_image_extension(match.group(1))+ try:+ img_bytes = base64.b64decode(match.group(2))+ except Exception as exc:+ logger.warning(f"Failed to decode image_base64 on page {page_index}: {exc}")+ return None++ img_path = f"{str_sha256(b64_data_uri)}.{fmt}"+ 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 HTML-like markup with local paths."""+ if not markup or not image_writer 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(+ blocks: list[dict],+ image_writer,+ page_index: int,+ table_block_type=BlockType.TABLE,+ table_body_type=BlockType.TABLE_BODY,+ table_span_type=ContentType.TABLE,+) -> None:+ """Persist inline base64 images embedded inside table HTML."""+ if not image_writer:+ return++ for block in blocks:+ if block.get("type") != table_block_type:+ continue++ for sub_block in block.get("blocks", []):+ if sub_block.get("type") != table_body_type:+ continue++ for line in sub_block.get("lines", []):+ for span in line.get("spans", []):+ if span.get("type") != table_span_type:+ continue+ span["html"] = replace_inline_base64_img_src(+ span.get("html", ""),+ image_writer,+ page_index,+ )+++def save_span_image_if_needed(+ span: dict,+ image_writer,+ page_index: int,+ source_key: str = "image_base64",+ target_key: str = "image_path",+) -> None:+ """Persist a span-level base64 image and normalize the target path field."""+ image_base64 = span.get(source_key, "")+ if not image_base64:+ span.setdefault(target_key, "")+ return++ img_path = save_base64_image(image_base64, image_writer, page_index)+ if img_path:+ span[target_key] = img_path+ del span[source_key]+ return++ span.setdefault(target_key, "")diff --git a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.pyindex 0a331445..cf422197 100644--- a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py+++ b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py@@ -1,8 +1,6 @@# Copyright (c) Opendatalab. All rights reserved.-import base64import os-import reimport timeimport cv2@@ -10,12 +8,13 @@ import numpy as npfrom loguru import loggerfrom tqdm import tqdm+from mineru.backend.html_image_utils import replace_inline_table_imagesfrom mineru.backend.hybrid.hybrid_magic_model import MagicModelfrom mineru.backend.utils import cross_page_table_mergefrom mineru.utils.config_reader import get_table_enable, get_llm_aided_configfrom mineru.utils.cut_image import cut_image_and_table-from mineru.utils.enum_class import BlockType, ContentType-from mineru.utils.hash_utils import bytes_md5, str_sha256+from mineru.utils.enum_class import ContentType+from mineru.utils.hash_utils import bytes_md5from mineru.utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_neededfrom mineru.utils.pdf_image_tools import get_crop_imgfrom mineru.utils.pdfium_guard import close_pdfium_document, pdfium_guard@@ -36,65 +35,6 @@ 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,@@ -173,7 +113,7 @@ 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)+ replace_inline_table_images(table_blocks, image_writer, page_index)page_blocks = []page_blocks.extend([diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.pyindex a351f4eb..fb6193dd 100644--- a/mineru/backend/office/model_output_to_middle_json.py+++ b/mineru/backend/office/model_output_to_middle_json.py@@ -1,73 +1,12 @@--import base64import refrom collections import defaultdict-from loguru import logger-+from mineru.backend.html_image_utils import replace_inline_table_images, save_span_image_if_neededfrom mineru.backend.office.office_magic_model import MagicModelfrom mineru.utils.enum_class import BlockType-from mineru.utils.hash_utils import str_sha256from mineru.version import __version__-def _save_base64_image(b64_data_uri: str, image_writer, page_index: int):- """将 data-URI 格式的 base64 图片解码并通过 image_writer 保存到本地。-- Args:- b64_data_uri: 形如 ``data:image/{fmt};base64,{data}`` 的字符串。- image_writer: DataWriter 实例,用于将字节写入本地存储。- page_index: 当前页索引,仅用于日志信息。-- Returns:- 保存成功时返回相对路径字符串(如 ``"abc123.png"``),否则返回 ``None``。- """- 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 _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转换为页面信息"""@@ -85,22 +24,9 @@ def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:continuefor line in sub_block.get("lines", []):for span in line.get("spans", []):- _save_span_image_if_needed(span, image_writer, page_index)+ save_span_image_if_needed(span, image_writer, page_index)- # Replace inline base64 images inside table HTML with local paths- for tbl_block in table_blocks:- for sub_block in tbl_block.get("blocks", []):- if sub_block.get("type") != "table_body":- continue- for line in sub_block.get("lines", []):- for span in line.get("spans", []):- if span.get("type") != "table":- continue- span["html"] = _replace_inline_base64_img_src(- span.get("html", ""),- image_writer,- page_index,- )+ replace_inline_table_images(table_blocks, image_writer, page_index)# Replace inline base64 images inside chart content with local pathsfor chart_block in chart_blocks:@@ -111,7 +37,7 @@ def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:for span in line.get("spans", []):if span.get("type") != "chart":continue- _save_span_image_if_needed(span, image_writer, page_index)+ save_span_image_if_needed(span, image_writer, page_index)title_blocks = magic_model.get_title_blocks()discarded_blocks = magic_model.get_discarded_blocks()diff --git a/mineru/backend/pipeline/model_json_to_middle_json.py b/mineru/backend/pipeline/model_json_to_middle_json.pyindex 5e16b51a..cff57dfd 100644--- a/mineru/backend/pipeline/model_json_to_middle_json.py+++ b/mineru/backend/pipeline/model_json_to_middle_json.py@@ -1,13 +1,12 @@# Copyright (c) Opendatalab. All rights reserved.-import base64import copyimport os-import reimport timefrom loguru import loggerfrom tqdm import tqdm+from mineru.backend.html_image_utils import replace_inline_table_imagesfrom 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 AtomModelSingleton@@ -20,72 +19,10 @@ from mineru.utils.model_utils import clean_memoryfrom mineru.backend.pipeline.pipeline_magic_model import MagicModelfrom mineru.utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_neededfrom mineru.version import __version__-from mineru.utils.hash_utils import bytes_md5, str_sha256+from mineru.utils.hash_utils import bytes_md5from mineru.utils.pdfium_guard import close_pdfium_document, pdfium_guard-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 img src attributes 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(preproc_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 preproc_blocks:- if block.get("type") != BlockType.TABLE:- continue-- 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 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"]@@ -119,7 +56,7 @@ def page_model_info_to_page_info(page_model_info, image_dict, page, image_writerspan = cut_image_and_table(span, page_pil_img, page_img_md5, page_index, image_writer, scale=scale)"""构造page_info"""- _replace_inline_table_images(preproc_blocks, image_writer, page_index)+ replace_inline_table_images(preproc_blocks, image_writer, page_index)page_info = make_page_info_dict(preproc_blocks, page_index, page_w, page_h, discarded_blocks)diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.pyindex 2101af09..fc3cde0f 100644--- a/mineru/backend/vlm/model_output_to_middle_json.py+++ b/mineru/backend/vlm/model_output_to_middle_json.py@@ -1,6 +1,4 @@-import base64import os-import reimport timeimport cv2@@ -8,12 +6,13 @@ import numpy as npfrom loguru import loggerfrom tqdm import tqdm+from mineru.backend.html_image_utils import replace_inline_table_imagesfrom mineru.backend.utils import cross_page_table_mergefrom mineru.backend.vlm.vlm_magic_model import MagicModelfrom mineru.utils.config_reader import get_table_enable, get_llm_aided_configfrom mineru.utils.cut_image import cut_image_and_table-from mineru.utils.enum_class import BlockType, ContentType-from mineru.utils.hash_utils import bytes_md5, str_sha256+from mineru.utils.enum_class import ContentType+from mineru.utils.hash_utils import bytes_md5from mineru.utils.pdf_image_tools import get_crop_imgfrom mineru.utils.pdfium_guard import close_pdfium_document, pdfium_guardfrom mineru.version import __version__@@ -33,65 +32,6 @@ 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转换为页面信息"""@@ -144,7 +84,7 @@ 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)+ replace_inline_table_images(table_blocks, image_writer, page_index)page_blocks = []page_blocks.extend([