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 image handling in DocxConverter and HTML processing to support base64 images and improve table rendering
myhloli20527e3fa450
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.pyindex 97902f66..82069c54 100644--- a/mineru/backend/office/model_output_to_middle_json.py+++ b/mineru/backend/office/model_output_to_middle_json.py@@ -11,6 +11,33 @@ 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 blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:"""将blocks转换为页面信息"""@@ -28,24 +55,39 @@ def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:img_b64 = span.get("image_base64", "")if not img_b64:continue- # Parse data URI: data:image/{format};base64,{data}- m = re.match(r'data:image/(\w+);base64,(.+)', img_b64, re.DOTALL)- if not m:- logger.warning(f"Unrecognized image_base64 format in page {page_index}, skipping.")+ img_path = _save_base64_image(img_b64, image_writer, page_index)+ if img_path:+ span["image_path"] = img_path+ del span["image_base64"]++ table_blocks = magic_model.get_table_blocks()++ # Replace inline base64 images inside table HTML with local paths+ if image_writer:+ 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- 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}")+ html = span.get("html", "")+ if not html or "base64," not in html:continue- img_path = f"{str_sha256(img_b64)}.{ext}"- image_writer.write(img_path, img_bytes)- span["image_path"] = img_path- del span["image_base64"]- table_blocks = magic_model.get_table_blocks()+ 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"] = re.sub(+ r'src="(data:image/[^"]+)"',+ _replace_src,+ html,+ )+title_blocks = magic_model.get_title_blocks()discarded_blocks = magic_model.get_discarded_blocks()list_blocks = magic_model.get_list_blocks()diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.pyindex 17e7e0e7..e99b4875 100644--- a/mineru/backend/office/office_magic_model.py+++ b/mineru/backend/office/office_magic_model.py@@ -405,6 +405,8 @@ def clean_table_html(html: str) -> str:# 需要保留的属性(对表格结构有用)preserved_attrs = {'colspan', 'rowspan'}+ # img 标签需要额外保留的属性(内联 base64 图片内容)+ img_preserved_attrs = {'src', 'alt', 'width', 'height'}def clean_tag(match):"""清洗单个标签,只保留结构相关的属性"""@@ -414,6 +416,9 @@ def clean_table_html(html: str) -> str:# 自闭合标签的处理is_self_closing = full_tag.rstrip().endswith('/>')+ # img 标签额外保留图片相关属性(如内联 base64 src)+ current_preserved = preserved_attrs | (img_preserved_attrs if tag_name == 'img' else set())+# 提取需要保留的属性kept_attrs = []@@ -430,8 +435,8 @@ def clean_table_html(html: str) -> str:attr_name = attr_name.lower()attr_value = attr_match.group(2) or attr_match.group(3) or attr_match.group(4) or ""- # 只保留colspan和rowspan- if attr_name in preserved_attrs:+ # 只保留指定属性(表格结构属性,img 标签还额外保留图片内容属性)+ if attr_name in current_preserved:kept_attrs.append(f'{attr_name}="{attr_value}"')# 重建标签diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.pyindex 8d42cbb0..b3ab9002 100644--- a/mineru/backend/office/office_middle_json_mkcontent.py+++ b/mineru/backend/office/office_middle_json_mkcontent.py@@ -1,4 +1,5 @@import os+import refrom loguru import logger@@ -20,6 +21,17 @@ inline_left_delimiter = delimiters['inline']['left']inline_right_delimiter = delimiters['inline']['right']+def _prefix_table_img_src(html: str, img_buket_path: str) -> str:+ """Prefix local-path img src attributes in table HTML with img_buket_path."""+ if not html or not img_buket_path:+ return html+ return re.sub(+ r'src="(?!data:)([^"]+)"',+ lambda m: f'src="{img_buket_path}/{m.group(1)}"',+ html,+ )++def get_title_level(para_block):title_level = para_block.get('level', 2)return title_level@@ -216,7 +228,7 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=Nofor line in block['lines']:for span in line['spans']:if span['type'] == ContentType.TABLE:- para_text += f"\n{span['html']}\n"+ para_text += f"\n{_prefix_table_img_src(span['html'], img_buket_path)}\n"for block in para_block['blocks']: # 2nd.拼table_captionif block['type'] == BlockType.TABLE_CAPTION:para_text += ' \n' + merge_para_with_text(block)@@ -284,7 +296,7 @@ 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] = f"{span['html']}"+ para_content[BlockType.TABLE_BODY] = _prefix_table_img_src(span['html'], img_buket_path)if block['type'] == BlockType.TABLE_CAPTION:para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))@@ -386,7 +398,7 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path):'type': ContentTypeV2.TABLE,'content': {'table_caption': table_caption,- 'html': html,+ 'html': _prefix_table_img_src(html, img_buket_path),'table_type': table_type,'table_nest_level': table_nest_level,}diff --git a/mineru/cli/gradio_app.py b/mineru/cli/gradio_app.pyindex aa242b87..f93481fd 100644--- a/mineru/cli/gradio_app.py+++ b/mineru/cli/gradio_app.py@@ -107,31 +107,39 @@ def replace_image_with_base64(markdown_text, image_dir_path):'.webp': 'image/webp',}- # 匹配Markdown中的图片标签- pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'+ def _path_to_data_uri(relative_path):+ file_ext = os.path.splitext(relative_path)[1].lower()+ if file_ext not in mime_types:+ return None+ try:+ full_path = os.path.join(image_dir_path, relative_path)+ base64_image = image_to_base64(full_path)+ return f'data:{mime_types[file_ext]};base64,{base64_image}'+ except Exception as e:+ logger.warning(f"Failed to convert image {relative_path} to base64: {e}")+ return None- # 替换图片链接- def replace(match):+ # 匹配Markdown中的图片标签 + def replace_md(match):relative_path = match.group(1)- # 获取文件扩展名(不区分大小写)- file_ext = os.path.splitext(relative_path)[1].lower()+ data_uri = _path_to_data_uri(relative_path)+ if data_uri:+ return f''+ return match.group(0)- # 如果是支持的图片格式,转换为base64- if file_ext in mime_types:- try:- full_path = os.path.join(image_dir_path, relative_path)- base64_image = image_to_base64(full_path)- mime_type = mime_types[file_ext]- return f''- except Exception as e:- logger.warning(f"Failed to convert image {relative_path} to base64: {e}")- return match.group(0)- else:- # 其他格式的图片保持原样- return match.group(0)+ result = re.sub(r'\!\[(?:[^\]]*)\]\(([^)]+)\)', replace_md, markdown_text)++ # 匹配HTML表格中的 <img src="path"> (跳过已有的data: URI)+ def replace_html_src(match):+ relative_path = match.group(1)+ data_uri = _path_to_data_uri(relative_path)+ if data_uri:+ return f'src="{data_uri}"'+ return match.group(0)++ result = re.sub(r'src="(?!data:)([^"]+)"', replace_html_src, result)- # 应用替换- return re.sub(pattern, replace, markdown_text)+ return resultasync def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=True, table_enable=True, language="ch", backend="pipeline", url=None):diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.pyindex 552e61cd..b8b6e26b 100644--- a/mineru/model/docx/docx_converter.py+++ b/mineru/model/docx/docx_converter.py@@ -68,6 +68,8 @@ class DocxConverter:self.docx_obj = Noneself.pages = []self.cur_page = []+ self._mammoth_tables_html: list = [] # 完整文档 mammoth 预解析的表格 HTML 列表+ self._mammoth_table_idx: int = 0 # 当前预解析表格游标self.pre_num_id: int = -1 # 上一个处理元素的 numIdself.pre_ilevel: int = -1 # 上一个处理元素的缩进等级, 用于判断列表层级self.list_block_stack: list = [] # 列表块堆栈@@ -259,7 +261,12 @@ class DocxConverter:file_stream: BinaryIO,):self.file_stream = file_stream- self.docx_obj = Document(file_stream)+ # 读取文件字节,以便 mammoth 和 python-docx 各自使用独立读取流+ file_bytes = file_stream.read()+ # 使用完整文档 mammoth 转换预解析所有表格,获得完整上下文(编号/图片/样式等)+ self._mammoth_tables_html = self._preparse_tables_with_mammoth(file_bytes)+ self._mammoth_table_idx = 0+ self.docx_obj = Document(BytesIO(file_bytes))self.pages.append(self.cur_page)self._walk_linear(self.docx_obj.element.body)self._add_header_footer(self.docx_obj)@@ -384,15 +391,65 @@ class DocxConverter:else:logger.debug(f"Ignoring element in DOCX with tag: {tag_name}")+ def _preparse_tables_with_mammoth(self, file_bytes: bytes) -> list:+ """+ 使用 mammoth 完整文档转换预解析所有顶层表格的 HTML。++ 孤立模式下(仅传入 <w:tbl> XML 片段),mammoth 缺少编号定义+ (word/numbering.xml)、样式(word/styles.xml)和关系+ (word/_rels/document.xml.rels)等上下文,在遇到含列表项或图片+ 的单元格时会抛出 AttributeError。通过完整文档转换,mammoth 可+ 获得完整上下文,从而正确处理这些情况。++ 图片会被 mammoth 转换为内联 data-URI base64 格式(<img src="data:...">)。++ Returns:+ list[str]: 文档中所有顶层表格的 HTML 字符串列表,按文档顺序排列+ """+ try:+ import mammoth as _mammoth+ from bs4 import BeautifulSoup as _BeautifulSoup++ result = _mammoth.convert_to_html(BytesIO(file_bytes))+ soup = _BeautifulSoup(result.value, 'html.parser')++ # 仅保留顶层表格,排除嵌套在其他表格单元格内的子表格+ all_tables = soup.find_all('table')+ top_level_tables = [t for t in all_tables if not t.find_parent('table')]++ logger.debug(+ f"Pre-parsed {len(top_level_tables)} top-level tables via full mammoth conversion"+ )+ return [str(t) for t in top_level_tables]+ except Exception as e:+ logger.debug(f"Could not pre-parse tables with full mammoth conversion: {e}")+ return []+def _handle_tables(self, element: BaseOxmlElement):"""处理表格。+ 优先使用完整文档 mammoth 转换的预解析结果(支持列表、图片、样式等+ 复杂单元格内容),若预解析结果耗尽则回退到孤立 XML 解析模式。+Args:element: 元素对象Returns:list[RefItem]: 元素引用列表"""+ # 优先使用预解析表格(完整文档上下文,能正确处理列表/图片等)+ if self._mammoth_table_idx < len(self._mammoth_tables_html):+ html = self._mammoth_tables_html[self._mammoth_table_idx]+ self._mammoth_table_idx += 1+ html = self._normalize_table_colspans(html)+ table_block = {+ "type": BlockType.TABLE,+ "content": html,+ }+ self.cur_page.append(table_block)+ return++ # 回退:孤立 XML 解析模式(原始方案,不含文档上下文)table = read_str(element.xml)body_reader = body_xml.reader()t = body_reader.read_all([table])