Skip to content

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

feat: 添加富文本解析,pptx添加多级列表

Sidney23320e798e6128a
diff --git a/demo/pptx/powerpoint_sample.pptx b/demo/pptx/powerpoint_sample.pptx
new file mode 100644
index 00000000..da07693a
Binary files /dev/null and b/demo/pptx/powerpoint_sample.pptx differ
diff --git a/demo/xlsx/xlsx_01.xlsx b/demo/xlsx/xlsx_01.xlsx
new file mode 100644
index 00000000..5a0475f8
Binary files /dev/null and b/demo/xlsx/xlsx_01.xlsx differ
diff --git a/mineru/model/pptx/powerpoint_sample.pptx b/mineru/model/pptx/powerpoint_sample.pptx
index da07693a..dc3c1a33 100644
Binary files a/mineru/model/pptx/powerpoint_sample.pptx and b/mineru/model/pptx/powerpoint_sample.pptx differ
diff --git a/mineru/model/pptx/pptx_converter.py b/mineru/model/pptx/pptx_converter.py
index 90d0d7dc..836ec9a0 100644
--- a/mineru/model/pptx/pptx_converter.py
+++ b/mineru/model/pptx/pptx_converter.py
@@ -200,76 +200,301 @@ class PptxConverter:
logger.warning(f"Warning: image cannot be loaded by Pillow: {e}")
return
+ @staticmethod
+ def _get_style_str_from_run(run) -> Optional[str]:
+ """从PPTX run对象提取可序列化的字体样式字符串。"""
+ if run is None:
+ return None
+
+ try:
+ font = run.font
+ except Exception:
+ return None
+
+ styles = []
+ if getattr(font, "bold", None) is True:
+ styles.append("bold")
+ if getattr(font, "italic", None) is True:
+ styles.append("italic")
+
+ underline = getattr(font, "underline", None)
+ if underline not in (None, False):
+ styles.append("underline")
+
+ if getattr(font, "strike", None) is True:
+ styles.append("strikethrough")
+
+ return ",".join(styles) if styles else None
+
+ @staticmethod
+ def _format_text_with_hyperlink(
+ text: str,
+ hyperlink: Optional[str],
+ style_str: Optional[str] = None,
+ ) -> str:
+ """按Office约定格式输出带样式/超链接的文本片段。"""
+ if not text:
+ return ""
+
+ if hyperlink is None or str(hyperlink).strip() in ("", "."):
+ if style_str:
+ return f'<text style="{style_str}">{text}</text>'
+ return text
+
+ if style_str:
+ text_tag = f'<text style="{style_str}">{text}</text>'
+ else:
+ text_tag = f"<text>{text}</text>"
+
+ return f"<hyperlink>{text_tag}<url>{hyperlink}</url></hyperlink>"
+
+ def _resolve_hyperlink_from_run(self, run, shape) -> Optional[str]:
+ """解析 run 对应的超链接,优先公开 API,回退到 XML + rels。"""
+ try:
+ if hasattr(run, "hyperlink") and run.hyperlink is not None:
+ address = run.hyperlink.address
+ if address and str(address).strip():
+ return str(address).strip()
+ except Exception:
+ pass
+
+ try:
+ rPr = run._r.find("a:rPr", namespaces=self.namespaces)
+ if rPr is None:
+ return None
+
+ hlink_click = rPr.find("a:hlinkClick", namespaces=self.namespaces)
+ if hlink_click is None:
+ return None
+
+ rid = hlink_click.get(
+ "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
+ )
+ if not rid:
+ return None
+
+ rels = shape.part.rels
+ if rid not in rels:
+ return None
+
+ rel = rels[rid]
+ target_ref = getattr(rel, "target_ref", None)
+ if target_ref and str(target_ref).strip():
+ return str(target_ref).strip()
+
+ target_part = getattr(rel, "target_part", None)
+ if target_part is not None:
+ partname = getattr(target_part, "partname", None)
+ if partname and str(partname).strip():
+ return str(partname).strip()
+ except Exception:
+ return None
+
+ return None
+
+ def _build_paragraph_plain_text(self, paragraph) -> str:
+ """构建段落纯文本(保留软换行为空格)。"""
+ p = paragraph._element
+ text_parts = []
+ for node in p.content_children:
+ if isinstance(node, CT_TextLineBreak):
+ text_parts.append(" ")
+ continue
+
+ node_text = getattr(node, "text", None)
+ if node_text is not None:
+ text_parts.append(node_text)
+
+ return "".join(text_parts)
+
+ def _build_paragraph_rich_text(self, paragraph, shape) -> str:
+ """按 run 维度构建段落富文本,支持样式与超链接标签。"""
+ run_map = {}
+ for run in paragraph.runs:
+ try:
+ run_map[id(run._r)] = run
+ except Exception:
+ continue
+
+ rich_parts = []
+ for node in paragraph._element.content_children:
+ if isinstance(node, CT_TextLineBreak):
+ rich_parts.append(" ")
+ continue
+
+ node_text = getattr(node, "text", None)
+ if node_text is None:
+ continue
+
+ run = run_map.get(id(node))
+ if run is None:
+ rich_parts.append(node_text)
+ continue
+
+ style_str = self._get_style_str_from_run(run)
+ hyperlink = self._resolve_hyperlink_from_run(run, shape)
+ rich_parts.append(
+ self._format_text_with_hyperlink(node_text, hyperlink, style_str)
+ )
+
+ return "".join(rich_parts)
+
+ def _get_paragraph_list_info(self, shape, paragraph) -> dict:
+ """基于段落->文本框->布局->母版继承链解析段落列表属性。"""
+ marker_info = self._get_effective_list_marker(shape, paragraph)
+ p = paragraph._element
+ level = marker_info.get("level", self._get_paragraph_level(p))
+ kind = marker_info.get("kind")
+
+ if marker_info.get("is_list") is False:
+ return {
+ "is_list": False,
+ "attribute": "unordered",
+ "level": level,
+ "kind": kind,
+ }
+
+ if kind == "buAutoNum":
+ return {
+ "is_list": True,
+ "attribute": "ordered",
+ "level": level,
+ "kind": kind,
+ }
+
+ if kind in ("buChar", "buBlip"):
+ return {
+ "is_list": True,
+ "attribute": "unordered",
+ "level": level,
+ "kind": kind,
+ }
+
+ if marker_info.get("is_list") is True:
+ return {
+ "is_list": True,
+ "attribute": "unordered",
+ "level": level,
+ "kind": kind,
+ }
+
+ # 兜底:段落级标记 + 缩进层级判断
+ if p.find(".//a:buAutoNum", namespaces={"a": self.namespaces["a"]}) is not None:
+ return {
+ "is_list": True,
+ "attribute": "ordered",
+ "level": paragraph.level,
+ "kind": "buAutoNum",
+ }
+
+ if p.find(".//a:buChar", namespaces={"a": self.namespaces["a"]}) is not None:
+ return {
+ "is_list": True,
+ "attribute": "unordered",
+ "level": paragraph.level,
+ "kind": "buChar",
+ }
+
+ if paragraph.level > 0:
+ return {
+ "is_list": True,
+ "attribute": "unordered",
+ "level": paragraph.level,
+ "kind": None,
+ }
+
+ return {
+ "is_list": False,
+ "attribute": "unordered",
+ "level": 0,
+ "kind": None,
+ }
+
+ def _ensure_list_level(self, list_stack: list, level: int, attribute: str):
+ """将列表栈调整到目标层级,并在必要时创建同级/子级列表块。"""
+ while len(list_stack) > level + 1:
+ list_stack.pop()
+
+ if len(list_stack) == level + 1 and list_stack[level].get("attribute") != attribute:
+ list_stack.pop()
+
+ while len(list_stack) < level + 1:
+ ilevel = len(list_stack)
+ new_list_block = {
+ "type": BlockType.LIST,
+ "attribute": attribute,
+ "ilevel": ilevel,
+ "content": [],
+ }
+
+ if list_stack:
+ list_stack[-1]["content"].append(new_list_block)
+ else:
+ self.cur_page.append(new_list_block)
+
+ list_stack.append(new_list_block)
+
+ def _append_list_item(
+ self,
+ list_stack: list,
+ level: int,
+ attribute: str,
+ content: str,
+ ):
+ """向目标层级列表追加文本项。"""
+ self._ensure_list_level(list_stack, level, attribute)
+ list_stack[-1]["content"].append(
+ {
+ "type": BlockType.TEXT,
+ "content": content,
+ }
+ )
+
def _handle_text_elements(self, shape):
- is_list_group_created = False
- enum_list_item_value = 0
- new_list = None
+ self.list_block_stack = []
# 遍历段落以构建文本
for paragraph in shape.text_frame.paragraphs:
- is_a_list, bullet_type = self._is_list_item(paragraph)
- p = paragraph._element
-
- # 将换行符转换为空格并累积文本
- p_text = ""
- for e in p.content_children:
- if isinstance(e, CT_TextLineBreak):
- p_text += " "
- else:
- p_text += e.text
-
- if is_a_list:
- enum_marker = ""
- enumerated = bullet_type == "Numbered"
-
- if not is_list_group_created:
- if enumerated:
- list_attribute = "ordered"
- else:
- list_attribute = "unordered"
- new_list_block = {
- "type": BlockType.LIST,
- "attribute": list_attribute,
- "list_items": [],
- }
- self.cur_page.append(new_list_block)
- self.list_block_stack.append(new_list_block)
- is_list_group_created = True
- enum_list_item_value = 0
-
- if enumerated:
- enum_list_item_value += 1
- enum_marker = str(enum_list_item_value) + ". "
-
- list_item = {
- "type": BlockType.TEXT,
- "content": enum_marker + p_text,
+ list_info = self._get_paragraph_list_info(shape, paragraph)
+
+ if list_info["is_list"]:
+ rich_text = self._build_paragraph_rich_text(paragraph, shape)
+ if rich_text.strip():
+ self._append_list_item(
+ self.list_block_stack,
+ list_info["level"],
+ list_info["attribute"],
+ rich_text,
+ )
+ continue
+
+ # 段落不是列表项,关闭当前 shape 的列表上下文
+ self.list_block_stack.clear()
+
+ p_text = self._build_paragraph_plain_text(paragraph)
+ if len(p_text.strip()) == 0:
+ continue
+
+ # 根据文本类型分配标签(标题/部分标题/段落等)
+ label = BlockType.TEXT
+ if shape.is_placeholder:
+ placeholder_type = shape.placeholder_format.type
+ if placeholder_type in [
+ PP_PLACEHOLDER.CENTER_TITLE,
+ PP_PLACEHOLDER.TITLE,
+ PP_PLACEHOLDER.SUBTITLE,
+ ]:
+ label = BlockType.TITLE
+
+ self.cur_page.append(
+ {
+ "type": label,
+ "content": p_text,
}
- self.list_block_stack[-1]["list_items"].append(list_item)
- else: # 段落不是列表项
- if is_list_group_created:
- is_list_group_created = False
- new_list = None
- enum_list_item_value = 0
- self.list_block_stack.pop()
- # 根据文本类型分配标签(标题/部分标题/段落等)
- label = BlockType.TEXT
- if shape.is_placeholder:
- placeholder_type = shape.placeholder_format.type
- if placeholder_type in [
- PP_PLACEHOLDER.CENTER_TITLE,
- PP_PLACEHOLDER.TITLE,
- PP_PLACEHOLDER.SUBTITLE,
- ]:
- label = BlockType.TITLE
-
- # 输出累积的内联文本
- self.cur_page.append(
- {
- "type": label,
- "content": p_text,
- }
- )
+ )
+
+ # shape 结束后清理列表上下文,避免跨 shape 污染
+ self.list_block_stack.clear()
return
def _is_list_item(self, paragraph) -> tuple[bool, str]:
@@ -286,8 +511,6 @@ class PptxConverter:
`bullet_type` - 为以下之一:'Bullet'(项目符号)、'Numbered'(编号)或'None',
描述列表标记类型。
"""
- p = paragraph._element
-
# 尝试从段落获取形状(包含该段落的对象),如果可能的话
shape = None
try:
@@ -300,32 +523,16 @@ class PptxConverter:
pass
if shape is not None:
- marker_info = self._get_effective_list_marker(shape, paragraph)
-
- # 检查这是否肯定是一个列表项
- if marker_info["is_list"] is True or marker_info["kind"] in (
- "buChar",
- "buAutoNum",
- "buBlip",
- ):
- if marker_info["kind"] == "buChar":
- return (True, "Bullet")
- elif marker_info["kind"] == "buAutoNum":
- return (True, "Numbered")
- else:
- return (True, "None")
-
- # 检查这是否肯定不是列表项
- if marker_info["is_list"] is False:
+ list_info = self._get_paragraph_list_info(shape, paragraph)
+ if not list_info["is_list"]:
return (False, "None")
- # 回退到段落级别检查(缩进级别大于0时视为列表项)
- if paragraph.level > 0:
- return (True, "None")
-
- return (False, "None")
+ if list_info["attribute"] == "ordered":
+ return (True, "Numbered")
+ return (True, "Bullet")
# 如果无法获取形状,使用更简单的检查方式
+ p = paragraph._element
if p.find(".//a:buChar", namespaces={"a": self.namespaces["a"]}) is not None:
return (True, "Bullet")
elif (
@@ -394,6 +601,18 @@ class PptxConverter:
except Exception:
layout_ph = None
+ # 某些PPT由不同工具生成时,layout 的 idx 与 slide placeholder 不一致。
+ # 这类场景回退到按 placeholder type 匹配,尽量保持继承链可解析。
+ if layout_ph is None:
+ try:
+ ph_type = shape.placeholder_format.type
+ for candidate in layout.placeholders:
+ if candidate.placeholder_format.type == ph_type:
+ layout_ph = candidate
+ break
+ except Exception:
+ layout_ph = None
+
if layout_ph is not None:
layout_tx = layout_ph._element.find(
".//p:txBody", namespaces=self.namespaces
@@ -608,7 +827,11 @@ class PptxConverter:
if placeholder_type in (PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.OBJECT):
return txStyles.find("p:bodyStyle", namespaces=self.namespaces)
- if placeholder_type == PP_PLACEHOLDER.TITLE:
+ if placeholder_type in (
+ PP_PLACEHOLDER.TITLE,
+ PP_PLACEHOLDER.CENTER_TITLE,
+ PP_PLACEHOLDER.SUBTITLE,
+ ):
return txStyles.find("p:titleStyle", namespaces=self.namespaces)
return txStyles.find("p:otherStyle", namespaces=self.namespaces)
diff --git a/mineru/model/xlsx/test_xlsx/xlsx_01.xlsx b/mineru/model/xlsx/test_xlsx/xlsx_01.xlsx
index 7e69dabb..5a0475f8 100644
Binary files a/mineru/model/xlsx/test_xlsx/xlsx_01.xlsx and b/mineru/model/xlsx/test_xlsx/xlsx_01.xlsx differ
diff --git a/mineru/model/xlsx/xlsx_converter.py b/mineru/model/xlsx/xlsx_converter.py
index 8e523da7..570c85ff 100644
--- a/mineru/model/xlsx/xlsx_converter.py
+++ b/mineru/model/xlsx/xlsx_converter.py
@@ -4,10 +4,12 @@ import posixpath
import zipfile
import re
import xml.etree.ElementTree as ET
+from urllib.parse import urlparse
from typing import BinaryIO, Annotated, cast
from openpyxl import load_workbook
+from openpyxl.cell.rich_text import CellRichText
from openpyxl.worksheet.worksheet import Worksheet
from openpyxl.drawing.image import Image as XlsImage
from PIL import Image
@@ -65,6 +67,7 @@ class ExcelCell(BaseModel):
col_span: int
styles: dict = Field(default_factory=dict)
media: list[str] = Field(default_factory=list)
+ text_is_html: bool = False
class ExcelTable(BaseModel):
@@ -116,7 +119,11 @@ class XlsxConverter:
if hasattr(file_stream, "seek"):
file_stream.seek(0)
- self.workbook = load_workbook(filename=file_stream, data_only=True)
+ self.workbook = load_workbook(
+ filename=file_stream,
+ data_only=True,
+ rich_text=True,
+ )
if self.workbook is not None:
# 遍历工作簿中的所有工作表
for idx, name in enumerate(self.workbook.sheetnames):
@@ -312,8 +319,10 @@ class XlsxConverter:
if style_parts:
attr_str += f' style="{"; ".join(style_parts)}"'
- # 生成 HTML 单元格,注意对文本进行 HTML 转义
- text_content = html.escape(cell.text) if cell.text else ""
+ # 生成 HTML 单元格,富文本片段避免二次转义
+ text_content = ""
+ if cell.text:
+ text_content = cell.text if cell.text_is_html else html.escape(cell.text)
# 添加媒体内容 (Images)
if cell.media:
@@ -603,11 +612,14 @@ class XlsxConverter:
continue
cell = sheet.cell(row=ri + 1, column=rj + 1)
- cell_text = str(cell.value) if cell.value is not None else ""
+ raw_cell_text = str(cell.value) if cell.value is not None else ""
+ cell_text = ""
+ text_is_html = False
media_content = ""
- if "DISPIMG" in cell_text:
- media_content = self._get_cell_image(cell_text)
- cell_text = ""
+ if "DISPIMG" in raw_cell_text:
+ media_content = self._get_cell_image(raw_cell_text)
+ else:
+ cell_text, text_is_html = self._cell_value_to_html(cell)
# 计算合并跨度(默认为 1x1)
row_span = 1
@@ -627,6 +639,7 @@ class XlsxConverter:
col_span=col_span,
styles=self._extract_cell_style(cell),
media=[media_content] if media_content else [],
+ text_is_html=text_is_html,
)
)
@@ -731,6 +744,111 @@ class XlsxConverter:
return self.cell_image_map
+ @staticmethod
+ def _escape_text_with_line_breaks(text: str) -> str:
+ return (
+ html.escape(text)
+ .replace("\r\n", "\n")
+ .replace("\r", "\n")
+ .replace("\n", "<br>")
+ )
+
+ @staticmethod
+ def _get_cell_hyperlink_target(cell) -> str:
+ hyperlink = getattr(cell, "hyperlink", None)
+ if not hyperlink:
+ return ""
+
+ target = getattr(hyperlink, "target", None)
+ if target:
+ return str(target)
+
+ location = getattr(hyperlink, "location", None)
+ if location:
+ return f"#{location}"
+
+ return ""
+
+ @staticmethod
+ def _sanitize_hyperlink_target(target: str) -> str:
+ href = target.strip()
+ if not href:
+ return ""
+
+ if href.lower().startswith(("javascript:", "data:", "vbscript:")):
+ return ""
+
+ parsed = urlparse(href)
+ allowed_schemes = {"http", "https", "mailto", "ftp"}
+ scheme = parsed.scheme.lower() if parsed.scheme else ""
+ if scheme and scheme not in allowed_schemes:
+ return ""
+
+ return html.escape(href, quote=True)
+
+ def _inline_font_to_style(self, inline_font) -> str:
+ if inline_font is None:
+ return ""
+
+ style_parts = []
+ if getattr(inline_font, "b", False):
+ style_parts.append("font-weight: bold")
+ if getattr(inline_font, "i", False):
+ style_parts.append("font-style: italic")
+
+ text_decorations = []
+ if getattr(inline_font, "u", None):
+ text_decorations.append("underline")
+ if getattr(inline_font, "strike", False):
+ text_decorations.append("line-through")
+ if text_decorations:
+ style_parts.append(f"text-decoration: {' '.join(text_decorations)}")
+
+ color = getattr(inline_font, "color", None)
+ color_value = getattr(color, "rgb", None) if color else None
+ if isinstance(color_value, str):
+ if len(color_value) == 8:
+ style_parts.append(f"color: #{color_value[2:]}")
+ elif len(color_value) == 6:
+ style_parts.append(f"color: #{color_value}")
+
+ return "; ".join(style_parts)
+
+ def _cell_value_to_html(self, cell) -> tuple[str, bool]:
+ if cell.value is None:
+ return "", False
+
+ link_target = self._sanitize_hyperlink_target(
+ self._get_cell_hyperlink_target(cell)
+ )
+
+ if isinstance(cell.value, CellRichText):
+ html_parts = []
+ for part in cell.value:
+ if hasattr(part, "text"):
+ part_text = self._escape_text_with_line_breaks(
+ str(getattr(part, "text", ""))
+ )
+ style_str = self._inline_font_to_style(getattr(part, "font", None))
+ if style_str:
+ html_parts.append(f'<span style="{style_str}">{part_text}</span>')
+ else:
+ html_parts.append(part_text)
+ else:
+ html_parts.append(self._escape_text_with_line_breaks(str(part)))
+
+ rich_text_html = "".join(html_parts)
+ if link_target and rich_text_html:
+ rich_text_html = f'<a href="{link_target}">{rich_text_html}</a>'
+ return rich_text_html, True
+
+ plain_text = str(cell.value)
+ if link_target and plain_text:
+ escaped_text = self._escape_text_with_line_breaks(plain_text)
+ return f'<a href="{link_target}">{escaped_text}</a>', True
+
+ return plain_text, False
+
def _extract_cell_style(self, cell):
"""Extract styles from an openpyxl cell."""
style = {}