Skip to content

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

feat: add emphasis style support and enhance hyperlink handling in DOCX converter

myhlolif394e90232ff
diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.md
index 7c60c73b..fd21ec7b 100644
--- a/docs/en/reference/output_files.md
+++ b/docs/en/reference/output_files.md
@@ -429,6 +429,12 @@ Text levels are distinguished through the `text_level` field:
| `list` / `index` | List and index blocks with `list_items` |
| `page_header` / `page_footer` / `page_number` / `page_aside_text` / `page_footnote` | Page auxiliary blocks |
+Inline fields such as `title_content`, `paragraph_content`, and captions are
+usually span lists. A `hyperlink` span contains `content` and `url`; when one
+link contains text fragments with different styles, it may also contain
+`children`. In that case, `content` is the concatenated child text, and the
+exact styles are represented by the child `text` spans.
+
##### Sample Data
```json
diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.md
index 0d8a0505..1b24ff00 100644
--- a/docs/zh/reference/output_files.md
+++ b/docs/zh/reference/output_files.md
@@ -429,6 +429,11 @@
| `list` / `index` | 列表与索引,包含 `list_items` |
| `page_header` / `page_footer` / `page_number` / `page_aside_text` / `page_footnote` | 页面辅助块 |
+`title_content`、`paragraph_content`、说明文字等行内内容通常由 span 列表组成。
+`hyperlink` span 包含 `content`、`url`,当同一个链接内存在多段不同样式文本时,
+还会包含 `children`;此时 `content` 是 children 文本的拼接,精确样式以
+`children` 中的 `text` span 为准。
+
##### 示例数据
```json
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index 1450d75e..b1593713 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -184,6 +184,44 @@ class MagicModel:
return self.discarded_blocks
+def _parse_style_list(style_str: str | None) -> list:
+ """解析逗号分隔的 Office inline style 字符串。"""
+ if not style_str:
+ return []
+ return [style.strip() for style in style_str.split(',') if style.strip()]
+
+
+def _parse_hyperlink_text_children(hyperlink_content: str, text_tag_re) -> tuple:
+ """解析一个 hyperlink 内部的多个 text 子片段,并保留每段样式。"""
+ url_start = hyperlink_content.find('<url>')
+ url_end = hyperlink_content.find('</url>')
+ if url_start == -1 or url_end == -1 or url_end < url_start:
+ return [], ''
+
+ children = []
+ pos = 0
+ while pos < url_start:
+ text_match = text_tag_re.search(hyperlink_content, pos)
+ if text_match is None or text_match.start() >= url_start:
+ break
+
+ text_end = hyperlink_content.find('</text>', text_match.end())
+ if text_end == -1 or text_end > url_start:
+ return [], ''
+
+ child = {
+ "type": ContentType.TEXT,
+ "content": hyperlink_content[text_match.end():text_end],
+ }
+ style = _parse_style_list(text_match.group(1))
+ if style:
+ child["style"] = style
+ children.append(child)
+ pos = text_end + 7
+
+ return children, hyperlink_content[url_start + 5:url_end]
+
+
def parse_text_block_spans(content: str) -> list:
"""
解析文本类block的content,提取其中的文本、行内公式、超链接和字体样式。
@@ -304,25 +342,31 @@ def parse_text_block_spans(content: str) -> list:
# 提取超链接内容
hyperlink_content = content[next_tag_pos + 11:hyperlink_end]
- # 解析内部的 <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 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]
-
- 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()]
+ # 解析内部的一个或多个 <text [style="..."]> 和一个 <url> 标签
+ children, link_url = _parse_hyperlink_text_children(
+ hyperlink_content,
+ _text_tag_re,
+ )
+
+ if children and link_url:
+ if len(children) == 1:
+ child = children[0]
+ span = {
+ "type": ContentType.HYPERLINK,
+ "content": child["content"],
+ "url": link_url,
+ }
+ if child.get("style"):
+ span["style"] = child["style"]
+ else:
+ span = {
+ "type": ContentType.HYPERLINK,
+ "content": ''.join(
+ child["content"] for child in children
+ ),
+ "url": link_url,
+ "children": children,
+ }
spans.append(span)
pos = hyperlink_end + 12 # 跳过</hyperlink>
last_end = pos
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
index a936ec00..4493017d 100644
--- a/mineru/backend/office/office_middle_json_mkcontent.py
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -31,17 +31,19 @@ OFFICE_STYLE_RENDER_MODE_ENV = 'MINERU_OFFICE_STYLE_RENDER_MODE'
OFFICE_STYLE_RENDER_MODE_HTML = 'html'
OFFICE_STYLE_RENDER_MODE_MARKDOWN = 'markdown'
OFFICE_MARKDOWN_WRAPPER_STYLES = {'bold', 'italic', 'strikethrough'}
+OFFICE_EMPHASIS_STYLE = 'text-emphasis: dot; text-emphasis-position: under;'
def _apply_markdown_style(content: str, style: list) -> str:
"""
按照字体样式列表对文本内容应用 Markdown 格式。
- 支持的样式:bold, italic, underline, strikethrough
+ 支持的样式:bold, italic, underline, emphasis, strikethrough
组合顺序(由内到外):
1. bold/italic(纯 Markdown,最内层,兼容性最广)
2. strikethrough(~~,中间层,包裹纯 Markdown 符号广泛支持)
3. underline(HTML <u>,最外层,作为 HTML 容器不干扰内部 Markdown 解析)
+ 4. emphasis(HTML span,最外层,表达 Word 着重号语义)
这样可避免 `**~~<u>text</u>~~**` 在部分渲染器中因 HTML 标签打断
外层 Markdown 标记解析而导致样式失效的问题,
@@ -74,6 +76,10 @@ def _apply_markdown_style(content: str, style: list) -> str:
if 'underline' in style:
content = f'<u>{content}</u>'
+ # 第四层:emphasis —— markdown 无原生着重号语法,使用 CSS text-emphasis 表达。
+ if 'emphasis' in style:
+ content = f'<span style="{OFFICE_EMPHASIS_STYLE}">{content}</span>'
+
return content
@@ -95,6 +101,9 @@ def _apply_html_style(content: str, style: list) -> str:
if 'underline' in style:
content = f'<u>{content}</u>'
+ if 'emphasis' in style:
+ content = f'<span style="{OFFICE_EMPHASIS_STYLE}">{content}</span>'
+
return content
@@ -408,11 +417,9 @@ def _append_text_part(parts: list[dict], original_content: str, span_style: list
)
elif original_content:
visible_styles = {'underline', 'strikethrough'}
+ rendered_content = original_content
if span_style and any(s in visible_styles for s in span_style):
- rendered_content = original_content.replace(" ", "&nbsp;")
rendered_content = _apply_configured_style(rendered_content, span_style)
- else:
- rendered_content = original_content
parts.append(
_make_rendered_part(
ContentType.TEXT,
@@ -423,26 +430,48 @@ def _append_text_part(parts: list[dict], original_content: str, span_style: list
)
+def _render_hyperlink_children_label(children: list[dict]) -> str:
+ """渲染 hyperlink 的子文本片段,保留各自样式后再组成同一个链接 label。"""
+ child_parts = []
+ for child in children or []:
+ if child.get('type') != ContentType.TEXT:
+ continue
+ _append_text_part(
+ child_parts,
+ child.get('content', ''),
+ child.get('style', []),
+ )
+ return _join_rendered_parts(child_parts).strip()
+
+
def _append_hyperlink_part(
parts: list[dict],
original_content: str,
span_style: list,
url: str = '',
plain_text_only: bool = False,
+ children: list[dict] | None = None,
):
- stripped_content = original_content.strip()
- if not stripped_content:
- return
-
- styled_text = _render_styled_inline_text(stripped_content, span_style)
- if plain_text_only:
- leading = original_content[:len(original_content) - len(original_content.lstrip())]
- trailing = original_content[len(original_content.rstrip()):]
- rendered_content = leading + styled_text + trailing
- has_markdown_wrapper = _has_visible_marker_markdown_wrapper(span_style)
- else:
- rendered_content = _render_link(styled_text, url)
+ if children:
+ styled_text = _render_hyperlink_children_label(children)
+ if not styled_text:
+ return
+ rendered_content = styled_text if plain_text_only else _render_link(styled_text, url)
has_markdown_wrapper = False
+ else:
+ stripped_content = original_content.strip()
+ if not stripped_content:
+ return
+
+ styled_text = _render_styled_inline_text(stripped_content, span_style)
+ if plain_text_only:
+ leading = original_content[:len(original_content) - len(original_content.lstrip())]
+ trailing = original_content[len(original_content.rstrip()):]
+ rendered_content = leading + styled_text + trailing
+ has_markdown_wrapper = _has_visible_marker_markdown_wrapper(span_style)
+ else:
+ rendered_content = _render_link(styled_text, url)
+ has_markdown_wrapper = False
parts.append(
_make_rendered_part(
@@ -505,6 +534,7 @@ def merge_para_with_text(para_block, escape_text_block_prefix=True):
span['content'],
span_style,
url=span.get('url', ''),
+ children=span.get('children'),
)
para_text = _join_rendered_parts(parts)
@@ -1097,6 +1127,24 @@ def get_body_data(para_block):
return get_data_from_spans(para_block.get('lines', []))
+def _span_has_content_for_v2(span: dict, visible_styles: set) -> bool:
+ """判断 V2 span 是否应保留,支持 hyperlink children 的可见空白样式。"""
+ content = span.get("content", '')
+ span_style = span.get('style', [])
+ if content.strip():
+ return True
+ if content and span_style and any(s in visible_styles for s in span_style):
+ return True
+ for child in span.get('children') or []:
+ child_content = child.get('content', '')
+ child_style = child.get('style', [])
+ if child_content.strip():
+ return True
+ if child_content and child_style and any(s in visible_styles for s in child_style):
+ return True
+ return False
+
+
def merge_para_with_text_v2(para_block):
_visible_styles = {'underline', 'strikethrough'}
para_content = []
@@ -1110,12 +1158,7 @@ def merge_para_with_text_v2(para_block):
})
for i, line in enumerate(para_block['lines']):
for j, span in enumerate(line['spans']):
- content = span.get("content", '')
- span_style = span.get('style', [])
- has_visible_style = bool(
- span_style and any(s in _visible_styles for s in span_style)
- )
- if content.strip() or (content and has_visible_style):
+ if _span_has_content_for_v2(span, _visible_styles):
if span['type'] == ContentType.INLINE_EQUATION:
span['type'] = ContentTypeV2.SPAN_EQUATION_INLINE
para_content.append(span)
diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.py
index 63261afa..3c010889 100644
--- a/mineru/model/docx/docx_converter.py
+++ b/mineru/model/docx/docx_converter.py
@@ -152,6 +152,8 @@ class DocxConverter:
styles.append('italic')
if format_obj.underline:
styles.append('underline')
+ if format_obj.emphasis:
+ styles.append('emphasis')
if format_obj.strikethrough:
styles.append('strikethrough')
return ','.join(styles) if styles else None
@@ -171,7 +173,70 @@ class DocxConverter:
"""
if format_obj is None:
return False
- return bool(format_obj.underline or format_obj.strikethrough)
+ return bool(format_obj.underline or format_obj.emphasis or format_obj.strikethrough)
+
+ @staticmethod
+ def _has_non_visible_text_style(format_obj) -> bool:
+ """判断格式是否只有空白文本不可见的字形样式。"""
+ if format_obj is None:
+ return False
+ return bool(format_obj.bold or format_obj.italic)
+
+ @classmethod
+ def _normalize_format_for_text(
+ cls,
+ format_obj: Optional[Formatting],
+ text: str,
+ *,
+ preserve_blank_non_visible_style: bool = False,
+ ) -> Optional[Formatting]:
+ """按文本内容收敛 run 格式,避免空白 run 把不可见样式传给输出。
+
+ preserve_blank_non_visible_style 用于超链接内部 run 合并:空白 run 的
+ bold/italic 虽然自身不可见,但它可能表示同一链接 label 的连续样式边界。
+ """
+ if format_obj is None:
+ return None
+ if text.strip():
+ return format_obj
+
+ updates = {}
+ if format_obj.underline_style == "words":
+ updates["underline"] = False
+ updates["underline_style"] = ""
+ if (
+ cls._has_non_visible_text_style(format_obj)
+ and not preserve_blank_non_visible_style
+ ):
+ updates["bold"] = False
+ updates["italic"] = False
+
+ if updates:
+ format_obj = format_obj.model_copy(update=updates)
+ if not cls._has_visible_style(format_obj):
+ if preserve_blank_non_visible_style and cls._has_non_visible_text_style(
+ format_obj
+ ):
+ return format_obj
+ return None
+ return format_obj
+
+ @classmethod
+ def _should_keep_group_text(
+ cls,
+ text: str,
+ format_obj: Optional[Formatting],
+ *,
+ preserve_plain_blank: bool = False,
+ ) -> bool:
+ """判断当前累积 run 是否需要输出,保留夹在可见样式之间的普通空白。"""
+ if not text:
+ return False
+ if text.strip():
+ return True
+ if cls._has_visible_style(format_obj):
+ return True
+ return preserve_plain_blank
@staticmethod
def _append_paragraph_element(
@@ -241,23 +306,111 @@ class DocxConverter:
# 检查超链接是否有效(非空)
if hyperlink is None:
# 无超链接:只有有样式时才包裹 <text> 标签
- if style_str:
- return f'<text style="{style_str}">{text}</text>'
- return text
+ return cls._format_text_tag(text, style_str)
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
+ return cls._format_text_tag(text, style_str)
# 有超链接:构建 <text> 标签(含可选样式)
+ text_tag = cls._format_text_tag(text, style_str, force_tag=True)
+ return f"<hyperlink>{text_tag}<url>{hyperlink_str}</url></hyperlink>"
+
+ @staticmethod
+ def _format_text_tag(
+ text: str,
+ style_str: Optional[str] = None,
+ *,
+ force_tag: bool = False,
+ ) -> str:
+ """生成内部富文本标记;无样式时普通文本不额外包裹。"""
+ if not text:
+ return text
if style_str:
- text_tag = f'<text style="{style_str}">{text}</text>'
- else:
- text_tag = f'<text>{text}</text>'
+ return f'<text style="{style_str}">{text}</text>'
+ if force_tag:
+ return f"<text>{text}</text>"
+ return text
- return f"<hyperlink>{text_tag}<url>{hyperlink_str}</url></hyperlink>"
+ @staticmethod
+ def _is_valid_hyperlink_target(
+ hyperlink: Optional[Union[AnyUrl, Path, str]],
+ ) -> bool:
+ """判断 hyperlink 是否是可输出的真实链接目标。"""
+ if hyperlink is None:
+ return False
+ hyperlink_str = str(hyperlink)
+ return bool(hyperlink_str and hyperlink_str.strip() and hyperlink_str != ".")
+
+ @classmethod
+ def _format_hyperlink_group(
+ cls,
+ group: list[
+ tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]
+ ],
+ ) -> str:
+ """将连续同 URL 的 hyperlink 片段输出为一个外层 hyperlink 标记。"""
+ if not group:
+ return ""
+ hyperlink = group[0][2]
+ if not cls._is_valid_hyperlink_target(hyperlink):
+ return "".join(
+ cls._format_text_tag(text, cls._get_style_str_from_format(format_obj))
+ for text, format_obj, _ in group
+ if text
+ )
+
+ text_tags = []
+ for text, format_obj, _ in group:
+ if not text:
+ continue
+ style_str = cls._get_style_str_from_format(format_obj)
+ text_tags.append(cls._format_text_tag(text, style_str, force_tag=True))
+ return f"<hyperlink>{''.join(text_tags)}<url>{hyperlink}</url></hyperlink>"
+
+ @classmethod
+ def _build_text_mappings_from_elements(
+ cls,
+ paragraph_elements: list[
+ tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]
+ ],
+ ) -> list[tuple[str, str]]:
+ """按连续同 URL hyperlink 分组,生成原文到富文本标记的映射。"""
+ mappings = []
+ index = 0
+ while index < len(paragraph_elements):
+ text, format_obj, hyperlink = paragraph_elements[index]
+ if not text:
+ index += 1
+ continue
+
+ if cls._is_valid_hyperlink_target(hyperlink):
+ group = [(text, format_obj, hyperlink)]
+ index += 1
+ while index < len(paragraph_elements):
+ next_text, next_format, next_hyperlink = paragraph_elements[index]
+ if (
+ not next_text
+ or not cls._is_valid_hyperlink_target(next_hyperlink)
+ or str(next_hyperlink) != str(hyperlink)
+ ):
+ break
+ group.append((next_text, next_format, next_hyperlink))
+ index += 1
+
+ original_text = "".join(item_text for item_text, _, _ in group)
+ mappings.append((original_text, cls._format_hyperlink_group(group)))
+ continue
+
+ style_str = cls._get_style_str_from_format(format_obj)
+ formatted_text = cls._format_text_with_hyperlink(
+ text,
+ hyperlink,
+ style_str,
+ )
+ mappings.append((text, formatted_text))
+ index += 1
+ return mappings
def _build_text_from_elements(
self,
@@ -274,12 +427,12 @@ class DocxConverter:
Returns:
str: 重组后的文本
"""
- result_parts = []
- for text, format_obj, hyperlink in paragraph_elements:
- if text:
- 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)
+ result_parts = [
+ formatted_text
+ for _, formatted_text in self._build_text_mappings_from_elements(
+ paragraph_elements
+ )
+ ]
return "".join(result_parts) if result_parts else ""
@staticmethod
@@ -370,6 +523,56 @@ class DocxConverter:
return result
+ @staticmethod
+ def _group_paragraph_elements_by_non_eq_segments(
+ paragraph_elements: list,
+ non_eq_segments: list,
+ ) -> list[list]:
+ """按公式切分出的非公式文本片段分组,避免 hyperlink 跨公式合并。"""
+ if len(non_eq_segments) <= 1:
+ return [paragraph_elements]
+
+ concat_elem_text = "".join(text for text, _, _ in paragraph_elements)
+ concat_seg_text = "".join(non_eq_segments)
+ if concat_elem_text != concat_seg_text:
+ return [paragraph_elements]
+
+ groups = []
+ current_group = []
+ current_len = 0
+ segment_index = 0
+
+ while segment_index < len(non_eq_segments) and non_eq_segments[segment_index] == "":
+ groups.append([])
+ segment_index += 1
+
+ for element in paragraph_elements:
+ text = element[0]
+ if segment_index >= len(non_eq_segments):
+ return [paragraph_elements]
+
+ current_group.append(element)
+ current_len += len(text)
+ target_len = len(non_eq_segments[segment_index])
+
+ if current_len == target_len:
+ groups.append(current_group)
+ current_group = []
+ current_len = 0
+ segment_index += 1
+ while (
+ segment_index < len(non_eq_segments)
+ and non_eq_segments[segment_index] == ""
+ ):
+ groups.append([])
+ segment_index += 1
+ elif current_len > target_len:
+ return [paragraph_elements]
+
+ if current_group:
+ groups.append(current_group)
+ return groups
+
def _build_text_with_equations_and_hyperlinks(
self,
paragraph_elements: list[
@@ -401,7 +604,9 @@ class DocxConverter:
# 检查是否有字体样式
has_style = any(
- fmt is not None and (fmt.bold or fmt.italic or fmt.underline or fmt.strikethrough)
+ fmt is not None and (
+ fmt.bold or fmt.italic or fmt.underline or fmt.emphasis or fmt.strikethrough
+ )
for _, fmt, _ in paragraph_elements
)
@@ -423,11 +628,13 @@ class DocxConverter:
# 1. 记录每个元素的原始文本和对应的格式化结果
element_mappings = []
- for text, format_obj, hyperlink in paragraph_elements:
- if text:
- 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))
+ for segment_elements in self._group_paragraph_elements_by_non_eq_segments(
+ paragraph_elements,
+ non_eq_segments,
+ ):
+ element_mappings.extend(
+ self._build_text_mappings_from_elements(segment_elements)
+ )
# 2. 在 text_with_equations 中定位每个元素的原始文本,然后替换为格式化后的文本
result_text = text_with_equations
@@ -1360,8 +1567,9 @@ class DocxConverter:
# 按 run 粒度展开,避免只取首个 run 导致样式丢失。
if c.runs and len(c.runs) > 0:
# 先落盘当前累积的普通文本分组
- prev_has_visible = len(group_text.strip()) > 0 or (
- group_text and self._has_visible_style(previous_format)
+ prev_has_visible = self._should_keep_group_text(
+ group_text,
+ previous_format,
)
if prev_has_visible:
paragraph_elements.append((group_text, previous_format, None))
@@ -1372,7 +1580,11 @@ class DocxConverter:
if self._is_hidden_run(h_run):
continue
h_text = h_run.text or ""
- h_format = self._get_format_from_run(h_run)
+ h_format = self._normalize_format_for_text(
+ self._get_format_from_run(h_run),
+ h_text,
+ preserve_blank_non_visible_style=True,
+ )
# 保留非空文本(含制表符)以及带可见样式的空白 run
if h_text != "" or self._has_visible_style(h_format):
self._append_paragraph_element(
@@ -1449,18 +1661,43 @@ class DocxConverter:
# 普通 run
text = c.text
hyperlink = None
- format = self._get_format_from_run(c)
+ format = self._normalize_format_for_text(
+ self._get_format_from_run(c),
+ text,
+ )
else:
continue
# 当新 run 有可见内容(非空或带可见样式的空白)且格式变化时触发分组
has_visible_content = len(text.strip()) > 0 or self._has_visible_style(format)
- if (has_visible_content and format != previous_format) or (
+ is_blank_text = bool(text) and not text.strip()
+ format_changed = format != previous_format
+ has_visible_boundary = (
+ self._has_visible_style(previous_format)
+ or self._has_visible_style(format)
+ )
+ should_split_blank_boundary = (
+ is_blank_text
+ and bool(group_text)
+ and format_changed
+ and has_visible_boundary
+ )
+ if (has_visible_content and format_changed) or should_split_blank_boundary or (
hyperlink is not None
):
# 前一组有实质内容(非空或带可见样式的空白)时才保存
- prev_has_visible = len(group_text.strip()) > 0 or (
- group_text and self._has_visible_style(previous_format)
+ preserve_plain_blank = (
+ bool(group_text)
+ and not group_text.strip()
+ and (
+ self._has_visible_style(previous_format)
+ or self._has_visible_style(format)
+ )
+ )
+ prev_has_visible = self._should_keep_group_text(
+ group_text,
+ previous_format,
+ preserve_plain_blank=preserve_plain_blank,
)
if prev_has_visible:
paragraph_elements.append(
@@ -1480,8 +1717,9 @@ class DocxConverter:
# 格式化最后一个组
# 注意:使用 previous_format(当前累积组的格式),而非 format(最后一次循环迭代的格式)。
# 最后一次迭代可能是无样式的空 run,若使用 format 会导致样式丢失。
- last_has_visible = len(group_text.strip()) > 0 or (
- group_text and self._has_visible_style(previous_format)
+ last_has_visible = self._should_keep_group_text(
+ group_text,
+ previous_format,
)
if last_has_visible:
paragraph_elements.append((group_text, previous_format, None))
@@ -1593,6 +1831,18 @@ class DocxConverter:
return False
+ @staticmethod
+ def _get_direct_underline_style(run: Run) -> str:
+ """读取 run 级下划线类型,用于区分 words 这类不作用于空格的下划线。"""
+ _W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+ rPr = run._element.find(f"{{{_W}}}rPr")
+ if rPr is None:
+ return ""
+ underline = rPr.find(f"{{{_W}}}u")
+ if underline is None:
+ return ""
+ return underline.get(f"{{{_W}}}val", "single")
+
@classmethod
def _get_format_from_run(cls, run: Run) -> Optional[Formatting]:
"""
@@ -1608,8 +1858,10 @@ class DocxConverter:
is_italic = cls._resolve_run_bool_with_inheritance(run, "italic")
is_strikethrough = cls._resolve_run_bool_with_inheritance(run, "strikethrough")
is_underline = cls._resolve_run_bool_with_inheritance(run, "underline")
+ underline_style = cls._get_direct_underline_style(run)
- # 检测着重符号 (w:em):若存在非 none 的 em 值,则视为下划线样式
+ # 检测着重符号 (w:em):独立保留为 emphasis,避免和真实下划线混淆。
+ is_emphasis = False
_W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
rPr = run._element.find(f'{{{_W}}}rPr')
if rPr is not None:
@@ -1617,7 +1869,7 @@ class DocxConverter:
if em is not None:
em_val = em.get(f'{{{_W}}}val', '')
if em_val and em_val != 'none':
- is_underline = True
+ is_emphasis = True
is_sub = run.font.subscript or False
is_sup = run.font.superscript or False
@@ -1627,6 +1879,8 @@ class DocxConverter:
bold=is_bold,
italic=is_italic,
underline=is_underline,
+ underline_style=underline_style,
+ emphasis=is_emphasis,
strikethrough=is_strikethrough,
script=script,
)
diff --git a/mineru/utils/docx_formatting.py b/mineru/utils/docx_formatting.py
index 7e44840b..c52304fc 100644
--- a/mineru/utils/docx_formatting.py
+++ b/mineru/utils/docx_formatting.py
@@ -18,5 +18,7 @@ class Formatting(BaseModel):
bold: bool = False
italic: bool = False
underline: bool = False
+ underline_style: str = ""
+ emphasis: bool = False
strikethrough: bool = False
script: Script = Script.BASELINE