Skip to content

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

feat: enhance text block parsing to support font styles and improve hyperlink formatting in DocxConverter

myhlolia215f2ee69c3
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index e99b4875..df7e6c92 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -175,21 +175,28 @@ class MagicModel:
def parse_text_block_spans(content: str) -> list:
"""
- 解析文本类block的content,提取其中的文本、行内公式和超链接。
+ 解析文本类block的content,提取其中的文本、行内公式、超链接和字体样式。
支持的标签格式:
- <eq>...</eq>: 行内公式
- - <hyperlink><text>...</text><url>...</url></hyperlink>: 超链接
+ - <hyperlink><text [style="..."]>...</text><url>...</url></hyperlink>: 超链接(支持样式)
+ - <text style="...">...</text>: 带字体样式的普通文本
+
+ 字体样式值(逗号分隔):bold, italic, underline, strikethrough
Args:
content: 文本块的content字符串,可能包含特殊标签
Returns:
- 包含多个span的列表,每个span是一个字典,包含type和content等字段
+ 包含多个span的列表,每个span是一个字典,包含type和content等字段。
+ 带样式的文本span额外包含 style 字段(list类型)。
"""
if not content:
return []
+ # 匹配 <text> 或 <text style="..."> 开始标签
+ _text_tag_re = re.compile(r'<text(?:\s+style="([^"]*)")?>')
+
spans = []
last_end = 0
pos = 0
@@ -199,20 +206,21 @@ def parse_text_block_spans(content: str) -> list:
eq_start = content.find('<eq>', pos)
# 查找超链接标签 <hyperlink>
hyperlink_start = content.find('<hyperlink>', pos)
-
- # 确定下一个标签的位置
- next_tag_pos = -1
- next_tag_type = None
-
- if eq_start != -1 and (hyperlink_start == -1 or eq_start < hyperlink_start):
- next_tag_pos = eq_start
- next_tag_type = 'eq'
- elif hyperlink_start != -1:
- next_tag_pos = hyperlink_start
- next_tag_type = 'hyperlink'
+ # 查找带样式的文本标签 <text ...>(顶层,不在 hyperlink 内部)
+ text_tag_match = _text_tag_re.search(content, pos)
+ text_tag_start = text_tag_match.start() if text_tag_match else -1
+
+ # 收集所有有效的标签位置
+ candidates = []
+ if eq_start != -1:
+ candidates.append((eq_start, 'eq'))
+ if hyperlink_start != -1:
+ candidates.append((hyperlink_start, 'hyperlink'))
+ if text_tag_start != -1:
+ candidates.append((text_tag_start, 'text'))
# 没有找到任何标签,处理剩余文本
- if next_tag_pos == -1:
+ if not candidates:
remaining_text = content[last_end:]
if remaining_text:
spans.append({
@@ -221,6 +229,9 @@ def parse_text_block_spans(content: str) -> list:
})
break
+ # 取位置最小的标签
+ next_tag_pos, next_tag_type = min(candidates, key=lambda x: x[0])
+
# 处理标签前的文本
if next_tag_pos > last_end:
text_before = content[last_end:next_tag_pos]
@@ -234,7 +245,6 @@ def parse_text_block_spans(content: str) -> list:
if next_tag_type == 'eq':
eq_end = content.find('</eq>', next_tag_pos)
if eq_end != -1:
- # 提取公式内容(去除<eq>和</eq>标签)
formula_content = content[next_tag_pos + 4:eq_end]
spans.append({
"type": ContentType.INLINE_EQUATION,
@@ -250,6 +260,32 @@ def parse_text_block_spans(content: str) -> list:
})
break
+ # 处理带样式的文本标签
+ elif next_tag_type == 'text':
+ text_end = content.find('</text>', next_tag_pos)
+ if text_end != -1:
+ # text_tag_match 对应当前 next_tag_pos 的匹配
+ # 重新匹配确保位置对齐
+ tag_open_end = content.find('>', next_tag_pos) + 1
+ text_content = content[tag_open_end:text_end]
+ style_str = text_tag_match.group(1) if text_tag_match and text_tag_match.start() == next_tag_pos else None
+ span = {
+ "type": ContentType.TEXT,
+ "content": text_content
+ }
+ if style_str:
+ span["style"] = [s.strip() for s in style_str.split(',') if s.strip()]
+ spans.append(span)
+ pos = text_end + 7 # 跳过 </text>
+ last_end = pos
+ else:
+ # 未找到闭合标签,作为普通文本处理
+ spans.append({
+ "type": ContentType.TEXT,
+ "content": content[last_end:]
+ })
+ break
+
# 处理超链接
elif next_tag_type == 'hyperlink':
hyperlink_end = content.find('</hyperlink>', next_tag_pos)
@@ -257,21 +293,26 @@ def parse_text_block_spans(content: str) -> list:
# 提取超链接内容
hyperlink_content = content[next_tag_pos + 11:hyperlink_end]
- # 解析<text>和<url>标签
- text_start = hyperlink_content.find('<text>')
- text_end = hyperlink_content.find('</text>')
+ # 解析内部的 <text [style="..."]> 和 <url> 标签
+ inner_text_match = _text_tag_re.search(hyperlink_content)
+ text_end_in_hl = hyperlink_content.find('</text>')
url_start = hyperlink_content.find('<url>')
url_end = hyperlink_content.find('</url>')
- if text_start != -1 and text_end != -1 and url_start != -1 and url_end != -1:
- link_text = hyperlink_content[text_start + 6:text_end]
+ if inner_text_match and text_end_in_hl != -1 and url_start != -1 and url_end != -1:
+ style_str = inner_text_match.group(1)
+ link_text_start = inner_text_match.end() # 开始标签结束后的位置
+ link_text = hyperlink_content[link_text_start:text_end_in_hl]
link_url = hyperlink_content[url_start + 5:url_end]
- spans.append({
+ span = {
"type": ContentType.HYPERLINK,
"content": link_text,
"url": link_url
- })
+ }
+ if style_str:
+ span["style"] = [s.strip() for s in style_str.split(',') if s.strip()]
+ spans.append(span)
pos = hyperlink_end + 12 # 跳过</hyperlink>
last_end = pos
else:
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
index 6d8f6afd..cd8ec3cc 100644
--- a/mineru/backend/office/office_middle_json_mkcontent.py
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -21,6 +21,42 @@ inline_left_delimiter = delimiters['inline']['left']
inline_right_delimiter = delimiters['inline']['right']
+def _apply_markdown_style(content: str, style: list) -> str:
+ """
+ 按照字体样式列表对文本内容应用 Markdown 格式。
+
+ 支持的样式:bold, italic, underline, strikethrough
+ 组合顺序:先处理 bold/italic(内层),再处理 strikethrough 和 underline(外层)。
+
+ Args:
+ content: 待格式化的文本内容
+ style: 样式列表,如 ["bold", "italic"]
+
+ Returns:
+ str: 应用 Markdown 格式后的文本
+ """
+ if not style or not content:
+ return content
+
+ # bold 和 italic 可合并为 ***text***
+ if 'bold' in style and 'italic' in style:
+ content = f'***{content}***'
+ elif 'bold' in style:
+ content = f'**{content}**'
+ elif 'italic' in style:
+ content = f'*{content}*'
+
+ # strikethrough: ~~text~~
+ if 'strikethrough' in style:
+ content = f'~~{content}~~'
+
+ # underline: markdown 无原生语法,使用 HTML <u> 标签
+ if 'underline' in style:
+ content = f'<u>{content}</u>'
+
+ return content
+
+
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:
@@ -61,19 +97,36 @@ def merge_para_with_text(para_block):
for line in para_block['lines']:
for span in line['spans']:
span_type = span['type']
- content = ''
+ span_style = span.get('style', [])
+
if span_type == ContentType.TEXT:
- content = span['content']
+ original_content = span['content']
+ content_stripped = original_content.strip()
+ if content_stripped:
+ # Apply markdown style to stripped content, then restore surrounding whitespace
+ styled = _apply_markdown_style(content_stripped, span_style)
+ leading = original_content[:len(original_content) - len(original_content.lstrip())]
+ trailing = original_content[len(original_content.rstrip()):]
+ parts.append((span_type, leading + styled + trailing))
+ elif original_content:
+ # Whitespace-only span: preserve as spacing between styled parts
+ parts.append((span_type, original_content))
elif span_type == ContentType.INLINE_EQUATION:
content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
+ content = content.strip()
+ if content:
+ parts.append((span_type, content))
elif span_type == ContentType.INTERLINE_EQUATION:
content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
+ content = content.strip()
+ if content:
+ parts.append((span_type, content))
elif span_type == ContentType.HYPERLINK:
- content = f"[{span['content']}]({span.get('url', '')})"
-
- content = content.strip()
- if content:
- parts.append((span_type, content))
+ link_text = span['content'].strip()
+ if link_text:
+ link_text = _apply_markdown_style(link_text, span_style)
+ content = f"[{link_text}]({span.get('url', '')})"
+ parts.append((span_type, content))
# Second pass: join parts, keeping one space on each side of inline equations
para_text = ''
diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.py
index 16c428eb..565de3c2 100644
--- a/mineru/model/docx/docx_converter.py
+++ b/mineru/model/docx/docx_converter.py
@@ -135,16 +135,47 @@ class DocxConverter:
url = url.replace("(", "%28").replace(")", "%29")
return url
+ @staticmethod
+ def _get_style_str_from_format(format_obj) -> Optional[str]:
+ """
+ 从 Formatting 对象提取样式字符串。
+
+ Args:
+ format_obj: Formatting 对象
+
+ Returns:
+ Optional[str]: 样式字符串(如 "bold,italic"),无样式时返回 None
+ """
+ if format_obj is None:
+ return None
+ styles = []
+ if format_obj.bold:
+ styles.append('bold')
+ if format_obj.italic:
+ styles.append('italic')
+ if format_obj.underline:
+ styles.append('underline')
+ if format_obj.strikethrough:
+ styles.append('strikethrough')
+ return ','.join(styles) if styles else None
+
@classmethod
def _format_text_with_hyperlink(
- cls, text: str, hyperlink: Optional[Union[AnyUrl, Path, str]]
+ cls,
+ text: str,
+ hyperlink: Optional[Union[AnyUrl, Path, str]],
+ style_str: Optional[str] = None,
) -> str:
"""
- 将文本和超链接格式化为 Markdown 格式 [文本](链接)。
+ 将文本和超链接格式化,支持字体样式标记。
+
+ 无超链接时:有样式包裹为 <text style="...">文本</text>,无样式直接返回文本。
+ 有超链接时:格式化为 <hyperlink><text [style="..."]>文本</text><url>链接</url></hyperlink>。
Args:
text: 文本内容
hyperlink: 超链接地址
+ style_str: 样式字符串(如 "bold,italic"),无样式时为 None
Returns:
str: 格式化后的文本
@@ -154,17 +185,24 @@ class DocxConverter:
# 检查超链接是否有效(非空)
if hyperlink is None:
+ # 无超链接:只有有样式时才包裹 <text> 标签
+ if style_str:
+ return f'<text style="{style_str}">{text}</text>'
return text
hyperlink_str = str(hyperlink)
if not hyperlink_str or hyperlink_str.strip() == "" or hyperlink_str == ".":
+ if style_str:
+ return f'<text style="{style_str}">{text}</text>'
return text
- # 转义文本中的方括号和链接中的括号
- # escaped_text = cls._escape_hyperlink_text(text)
- # escaped_url = cls._escape_hyperlink_url(hyperlink_str)
+ # 有超链接:构建 <text> 标签(含可选样式)
+ if style_str:
+ text_tag = f'<text style="{style_str}">{text}</text>'
+ else:
+ text_tag = f'<text>{text}</text>'
- return f"<hyperlink><text>{text}</text><url>{hyperlink_str}</url></hyperlink>"
+ return f"<hyperlink>{text_tag}<url>{hyperlink_str}</url></hyperlink>"
def _build_text_from_elements(
self,
@@ -173,7 +211,7 @@ class DocxConverter:
],
) -> str:
"""
- 从 paragraph_elements 重组文本,应用超链接格式。
+ 从 paragraph_elements 重组文本,应用超链接格式和字体样式。
Args:
paragraph_elements: 段落元素列表
@@ -182,9 +220,10 @@ class DocxConverter:
str: 重组后的文本
"""
result_parts = []
- for text, format, hyperlink in paragraph_elements:
+ for text, format_obj, hyperlink in paragraph_elements:
if text:
- formatted_text = self._format_text_with_hyperlink(text, hyperlink)
+ style_str = self._get_style_str_from_format(format_obj)
+ formatted_text = self._format_text_with_hyperlink(text, hyperlink, style_str)
result_parts.append(formatted_text)
return " ".join(result_parts) if result_parts else ""
@@ -197,20 +236,18 @@ class DocxConverter:
equations: list,
) -> str:
"""
- 构建同时包含公式和超链接的文本。
-
- 此方法将公式标记插入到带有超链接格式的文本中。
+ 构建同时包含公式、超链接和字体样式的文本。
Args:
- paragraph_elements: 段落元素列表,包含超链接信息
+ paragraph_elements: 段落元素列表,包含格式和超链接信息
text_with_equations: 包含公式标记的原始文本
equations: 公式列表
Returns:
- str: 包含公式标记和超链接格式的文本
+ str: 包含公式标记、超链接格式和字体样式的文本
"""
if not equations:
- # 没有公式,直接返回带超链接的文本
+ # 没有公式,直接返回带超链接和样式的文本
return self._build_text_from_elements(paragraph_elements)
# 检查是否有超链接
@@ -219,27 +256,32 @@ class DocxConverter:
for _, _, hyperlink in paragraph_elements
)
- if not has_hyperlink:
- # 没有超链接,直接返回带公式的文本
+ # 检查是否有字体样式
+ has_style = any(
+ fmt is not None and (fmt.bold or fmt.italic or fmt.underline or fmt.strikethrough)
+ for _, fmt, _ in paragraph_elements
+ )
+
+ if not has_hyperlink and not has_style:
+ # 没有超链接也没有样式,直接返回带公式的文本
return text_with_equations
- # 同时有公式和超链接,需要合并处理
- # 策略:在带超链接的文本基础上,将公式标记插入到正确的位置
+ # 同时有公式和超链接/样式,需要合并处理
+ # 策略:在带公式的文本基础上,将样式/超链接标记插入到正确的位置
- # 1. 先构建带超链接的文本(但不格式化超链接文本)
- # 记录每个元素的原始文本和对应的超链接格式化结果
+ # 1. 记录每个元素的原始文本和对应的格式化结果
element_mappings = []
- for text, format, hyperlink in paragraph_elements:
+ for text, format_obj, hyperlink in paragraph_elements:
if text:
- formatted_text = self._format_text_with_hyperlink(text, hyperlink)
+ style_str = self._get_style_str_from_format(format_obj)
+ formatted_text = self._format_text_with_hyperlink(text, hyperlink, style_str)
element_mappings.append((text, formatted_text))
# 2. 在 text_with_equations 中定位每个元素的原始文本,然后替换为格式化后的文本
result_text = text_with_equations
for original_text, formatted_text in element_mappings:
if original_text != formatted_text:
- # 只有当文本被格式化为超链接时才需要替换
- # 需要确保不替换公式标记内的文本
+ # 只有当文本被格式化(添加样式或超链接)时才需要替换
result_text = self._replace_text_outside_equations(
result_text, original_text, formatted_text
)