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 text formatting capabilities by adding support for superscript and subscript styles in DOCX processing
myhlolid3a513f7b2c7
diff --git a/mineru/backend/office/mkcontent/__init__.py b/mineru/backend/office/mkcontent/__init__.pynew file mode 100644index 00000000..1e17167c--- /dev/null+++ b/mineru/backend/office/mkcontent/__init__.py@@ -0,0 +1 @@+# Copyright (c) Opendatalab. All rights reserved.diff --git a/mineru/backend/office/mkcontent/inline_renderer.py b/mineru/backend/office/mkcontent/inline_renderer.pynew file mode 100644index 00000000..6e7160db--- /dev/null+++ b/mineru/backend/office/mkcontent/inline_renderer.py@@ -0,0 +1,942 @@+# Copyright (c) Opendatalab. All rights reserved.+from dataclasses import dataclass, field+import unicodedata+from html import escape++from mineru.backend.utils.markdown_utils import (+ escape_conservative_markdown_text,+ escape_text_block_markdown_prefix,+)+from mineru.utils.config_reader import get_latex_delimiter_config+from mineru.utils.enum_class import BlockType, ContentType++latex_delimiters_config = get_latex_delimiter_config()++default_delimiters = {+ 'display': {'left': '$$', 'right': '$$'},+ 'inline': {'left': '$', 'right': '$'}+}++delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters++display_left_delimiter = delimiters['display']['left']+display_right_delimiter = delimiters['display']['right']+inline_left_delimiter = delimiters['inline']['left']+inline_right_delimiter = delimiters['inline']['right']++OFFICE_INLINE_SYNTAX_HTML = 'html'+OFFICE_INLINE_SYNTAX_MARKDOWN = 'markdown'+OFFICE_SIMPLE_MARKDOWN_STYLES = {'bold', 'italic', 'strikethrough'}+OFFICE_COMPLEX_HTML_STYLES = {+ 'underline',+ 'emphasis',+ 'superscript',+ 'subscript',+}+OFFICE_EMPHASIS_STYLE = 'text-emphasis: dot; text-emphasis-position: under;'+STYLE_WRAPPER_OPEN = {+ 'emphasis': f'<span style="{OFFICE_EMPHASIS_STYLE}">',+ 'strikethrough': '<del>',+ 'italic': '<em>',+ 'bold': '<strong>',+ 'underline': '<u>',+ 'superscript': '<sup>',+ 'subscript': '<sub>',+}+STYLE_WRAPPER_CLOSE = {+ 'emphasis': '</span>',+ 'strikethrough': '</del>',+ 'italic': '</em>',+ 'bold': '</strong>',+ 'underline': '</u>',+ 'superscript': '</sup>',+ 'subscript': '</sub>',+}+++@dataclass+class RenderedPart:+ """保存一个已渲染行内片段及其原始元数据,供段落拼接阶段使用。"""++ span_type: str+ rendered_content: str+++@dataclass+class StyleRangeToken:+ """保存 HTML 样式范围合并所需的片段内容和样式集合。"""++ content: str+ style: set[str] = field(default_factory=set)+++def _apply_markdown_style(content: str, style: list) -> str:+ """只渲染 auto 简单 block 允许的单一 Markdown wrapper。"""+ if not style or not content:+ return content++ style_set = {name for name in style if name}+ if style_set == {'bold'}:+ return f'**{content}**'+ if style_set == {'italic'}:+ return f'*{content}*'+ if style_set == {'strikethrough'}:+ return f'~~{content}~~'+ return content+++def _apply_html_style(content: str, style: list) -> str:+ """用 HTML 标签渲染 Office 行内样式,适配不宜使用 Markdown wrapper 的场景。"""+ if not style or not content:+ return content++ if 'superscript' in style:+ content = f'<sup>{content}</sup>'+ elif 'subscript' in style:+ content = f'<sub>{content}</sub>'++ if 'underline' in style:+ content = f'<u>{content}</u>'++ if 'bold' in style:+ content = f'<strong>{content}</strong>'++ if 'italic' in style:+ content = f'<em>{content}</em>'++ if 'strikethrough' in style:+ content = f'<del>{content}</del>'++ if 'emphasis' in style:+ content = f'<span style="{OFFICE_EMPHASIS_STYLE}">{content}</span>'++ return content+++def _apply_configured_style(content: str, style: list, inline_syntax: str) -> str:+ """按 block 级 auto 选择出来的语法渲染行内样式。"""+ if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:+ return _apply_markdown_style(content, style)+ return _apply_html_style(content, style)+++def _render_link(text: str, url: str, inline_syntax: str) -> str:+ """按 block 级语法渲染链接,复杂 HTML block 内统一使用 <a>。"""+ if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:+ return f'[{text}]({url})'+ return f'<a href="{escape(url, quote=True)}">{text}</a>'+++def _escape_office_inline_text(content: str, inline_syntax: str) -> str:+ """根据当前 block 语法转义普通文本,HTML block 内同时避开标签和 Markdown delimiter。"""+ if not content:+ return content+ if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:+ return escape_conservative_markdown_text(content)+ return escape_conservative_markdown_text(escape(content, quote=False))+++def get_title_level(para_block):+ title_level = para_block.get('level', 2)+ return title_level+++def _make_rendered_part(+ span_type,+ rendered_content: str,+) -> RenderedPart:+ """构造段落渲染中间片段,只保留拼接阶段实际需要的数据。"""+ return RenderedPart(+ span_type=span_type,+ rendered_content=rendered_content,+ )+++def _get_first_non_whitespace_char(text: str):+ """返回文本中第一个非空白字符,用于 block 级 Markdown 风险判定。"""+ for ch in text:+ if not ch.isspace():+ return ch+ return None+++def _get_last_non_whitespace_char(text: str):+ """返回文本中最后一个非空白字符,用于 block 级 Markdown 风险判定。"""+ for ch in reversed(text):+ if not ch.isspace():+ return ch+ return None+++def _is_punctuation_or_symbol(ch: str) -> bool:+ """判断字符是否属于 Unicode 标点或符号类别。"""+ return unicodedata.category(ch).startswith(('P', 'S'))+++def _is_boundary_text_char(ch: str) -> bool:+ """判断字符是否是会和 Markdown delimiter 紧贴产生歧义的普通文本字符。"""+ if ch.isspace():+ return False+ return not _is_punctuation_or_symbol(ch)+++def _join_rendered_parts(parts: list[RenderedPart]) -> str:+ """按 Office 段落规则拼接行内片段,并为行内公式补必要空格。"""+ rendered_parts = []++ for i, part in enumerate(parts):+ span_type = part.span_type+ content = part.rendered_content+ is_last = i == len(parts) - 1++ if span_type == ContentType.INLINE_EQUATION:+ if rendered_parts and not rendered_parts[-1].endswith(' '):+ rendered_parts.append(' ')+ rendered_parts.append(content)+ if not is_last:+ rendered_parts.append(' ')+ else:+ rendered_parts.append(content)++ return ''.join(rendered_parts)+++def _strip_text_block_markdown_edges(content: str) -> str:+ """去掉 Markdown 文本块首尾普通空白,避免段首缩进被渲染成代码块。"""+ if not content:+ return content+ return content.strip()+++def _get_visible_space_marker(style: list) -> str | None:+ """根据可见空格样式选择 Markdown marker,下划线优先于删除线。"""+ if not style:+ return None+ if 'underline' in style:+ return '_'+ if 'strikethrough' in style:+ return '-'+ return None+++def _is_ascii_space_only(content: str) -> bool:+ """判断文本是否只由普通 ASCII 空格组成。"""+ return bool(content) and all(char == ' ' for char in content)+++def _replace_ascii_spaces_with_marker(+ content: str,+ marker: str,+ inline_syntax: str,+) -> str:+ """将普通 ASCII 空格替换为指定 marker,其他文本按当前 block 语法转义。"""+ rendered_parts = []+ text_buffer = []++ def flush_text_buffer():+ if text_buffer:+ rendered_parts.append(+ _escape_office_inline_text(''.join(text_buffer), inline_syntax)+ )+ text_buffer.clear()++ for char in content:+ if char == ' ':+ flush_text_buffer()+ rendered_parts.append(marker)+ else:+ text_buffer.append(char)++ flush_text_buffer()+ return ''.join(rendered_parts)+++def _render_text_with_edge_space_markers(+ content: str,+ marker: str,+ inline_syntax: str,+) -> str:+ """渲染非空文本:只把首尾 ASCII 空格转成 marker,中间普通空格保持原样。"""+ leading_space_count = len(content) - len(content.lstrip(' '))+ trailing_space_count = len(content) - len(content.rstrip(' '))+ text_end = len(content) - trailing_space_count if trailing_space_count else len(content)+ core_text = content[leading_space_count:text_end]+ return (+ marker * leading_space_count+ + _escape_office_inline_text(core_text, inline_syntax)+ + marker * trailing_space_count+ )+++def _render_visible_space_marker_text(+ content: str,+ style: list,+ inline_syntax: str,+ render_style: list | None = None,+) -> str:+ """渲染可见样式空格:纯空白用 marker,非空文本只处理边缘空格。"""+ marker = _get_visible_space_marker(style)+ render_style = style if render_style is None else render_style+ if marker is None:+ return _apply_configured_style(+ _escape_office_inline_text(content, inline_syntax),+ render_style or [],+ inline_syntax,+ )++ style = style or []+ if marker == '-' and not _is_ascii_space_only(content):+ return _apply_configured_style(+ _render_text_with_edge_space_markers(content, marker, inline_syntax),+ render_style,+ inline_syntax,+ )++ if _is_ascii_space_only(content):+ rendered_content = _replace_ascii_spaces_with_marker(+ content,+ marker,+ inline_syntax,+ )+ ignored_style = 'underline' if marker == '_' else 'strikethrough'+ render_style = [name for name in (render_style or []) if name != ignored_style]+ return _apply_configured_style(rendered_content, render_style, inline_syntax)++ rendered_content = _render_text_with_edge_space_markers(+ content,+ marker,+ inline_syntax,+ )+ return _apply_configured_style(rendered_content, render_style, inline_syntax)+++def _render_styled_inline_text(content: str, style: list, inline_syntax: str) -> str:+ """渲染行内文本内容,统一复用可见空格 marker 规则。"""+ if content and _get_visible_space_marker(style):+ return _render_visible_space_marker_text(content, style, inline_syntax)++ escaped_content = _escape_office_inline_text(content, inline_syntax)+ return _apply_configured_style(escaped_content, style, inline_syntax)+++def _escape_standalone_marker_rule(content: str) -> str:+ """独立一行全是 marker 时转义首个字符,避免被 Markdown 当作分隔线。"""+ if content and all(char == '_' for char in content):+ return f'\\{content}'+ if content and all(char == '-' for char in content):+ return f'\\{content}'+ return content+++def _append_text_part(+ parts: list[RenderedPart],+ original_content: str,+ span_style: list,+ inline_syntax: str,+ render_style: list | None = None,+):+ render_style = span_style if render_style is None else render_style+ if original_content and _get_visible_space_marker(span_style):+ parts.append(+ _make_rendered_part(+ ContentType.TEXT,+ _render_visible_space_marker_text(+ original_content,+ span_style,+ inline_syntax,+ render_style,+ ),+ )+ )+ return++ escaped_content = _escape_office_inline_text(original_content, inline_syntax)+ content_stripped = escaped_content.strip()+ if content_stripped:+ styled = _apply_configured_style(+ content_stripped,+ render_style,+ inline_syntax,+ )+ leading = escaped_content[+ :len(escaped_content) - len(escaped_content.lstrip())+ ]+ trailing = escaped_content[len(escaped_content.rstrip()):]+ parts.append(+ _make_rendered_part(+ ContentType.TEXT,+ leading + styled + trailing,+ )+ )+ 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 = _apply_configured_style(+ _escape_office_inline_text(rendered_content, inline_syntax),+ render_style,+ inline_syntax,+ )+ parts.append(+ _make_rendered_part(+ ContentType.TEXT,+ rendered_content,+ )+ )+++def _split_plain_blank_edges(+ text_spans: list[dict],+) -> tuple[list[dict], list[dict], list[dict]]:+ """拆出首尾纯空白 span,避免把段首 emphasis-only 空格包进 HTML 外层后无法 trim。"""+ start = 0+ end = len(text_spans)+ while start < end and not str(text_spans[start].get('content', '')).strip():+ start += 1+ while end > start and not str(text_spans[end - 1].get('content', '')).strip():+ end -= 1+ return text_spans[:start], text_spans[start:end], text_spans[end:]+++def _simple_markdown_style_name(style: list | tuple | set | None) -> str | None:+ """返回可安全使用 Markdown 的单一样式名;空样式返回 None,复杂样式返回空串。"""+ style_set = {name for name in (style or []) if name}+ if not style_set:+ return None+ if style_set & OFFICE_COMPLEX_HTML_STYLES:+ return ''+ if len(style_set) == 1:+ style_name = next(iter(style_set))+ if style_name in OFFICE_SIMPLE_MARKDOWN_STYLES:+ return style_name+ return ''+++def _is_simple_markdown_style(style: list | tuple | set | None) -> bool:+ """判断样式是否适合保留为简单 Markdown 输出。"""+ return _simple_markdown_style_name(style) != ''+++def _iter_para_inline_spans(para_block):+ """按 block 原始顺序遍历行内 span,供 auto 语法判定复用。"""+ for line in para_block.get('lines', []):+ for span in line.get('spans', []):+ yield span+++def _hyperlink_requires_html(span: dict) -> bool:+ """判断 hyperlink 是否存在混合或复杂样式,需要整块切到 HTML。"""+ children = span.get('children') or []+ if not children:+ return not _is_simple_markdown_style(span.get('style', []))++ child_style_keys = set()+ for child in children:+ if child.get('type') != ContentType.TEXT:+ return True+ content = str(child.get('content', ''))+ if not content.strip():+ continue+ child_style = child.get('style', [])+ if not _is_simple_markdown_style(child_style):+ return True+ child_style_keys.add(tuple(child_style or []))++ return len(child_style_keys) > 1+++def _iter_block_inline_units(para_block):+ """把 block 展开为线性文本单元,用于判断 Markdown 边界风险。"""+ if para_block.get('type') == BlockType.TITLE:+ section_number = para_block.get('section_number', '')+ if para_block.get('is_numbered_style', False) and section_number:+ yield {+ 'span_type': ContentType.TEXT,+ 'content': f'{section_number} ',+ 'style': [],+ }++ for span in _iter_para_inline_spans(para_block):+ span_type = span.get('type')+ if span_type == ContentType.TEXT:+ yield {+ 'span_type': ContentType.TEXT,+ 'content': str(span.get('content', '')),+ 'style': span.get('style', []),+ }+ elif span_type == ContentType.HYPERLINK:+ children = span.get('children') or []+ if children:+ for child in children:+ if child.get('type') != ContentType.TEXT:+ continue+ yield {+ 'span_type': ContentType.HYPERLINK,+ 'content': str(child.get('content', '')),+ 'style': child.get('style', []),+ }+ else:+ yield {+ 'span_type': ContentType.HYPERLINK,+ 'content': str(span.get('content', '')),+ 'style': span.get('style', []),+ }+ elif span_type in {ContentType.INLINE_EQUATION, ContentType.INTERLINE_EQUATION}:+ yield {+ 'span_type': span_type,+ 'content': str(span.get('content', '')),+ 'style': [],+ }+++def _has_markdown_boundary_risk(units: list[dict]) -> bool:+ """复用原有补空格风险:命中时直接切 HTML,避免运行期修补 Markdown。"""+ previous_unit = None+ boundary_span_types = {+ ContentType.HYPERLINK,+ ContentType.INLINE_EQUATION,+ ContentType.INTERLINE_EQUATION,+ }+ for unit in units:+ if previous_unit is None:+ previous_unit = unit+ continue+ previous_style_name = _simple_markdown_style_name(previous_unit.get('style'))+ current_style_name = _simple_markdown_style_name(unit.get('style'))+ if (+ not (previous_style_name or current_style_name)+ or previous_unit.get('span_type') in boundary_span_types+ or unit.get('span_type') in boundary_span_types+ ):+ previous_unit = unit+ continue++ previous_content = previous_unit.get('content', '')+ next_content = unit.get('content', '')+ if not previous_content.strip() or not next_content.strip():+ previous_unit = unit+ continue+ if previous_content[-1].isspace() or next_content[0].isspace():+ previous_unit = unit+ continue++ previous_char = _get_last_non_whitespace_char(previous_content)+ next_char = _get_first_non_whitespace_char(next_content)+ if (+ previous_char is not None+ and next_char is not None+ and _is_punctuation_or_symbol(previous_char)+ and _is_boundary_text_char(next_char)+ ):+ return True+ if (+ previous_char is not None+ and next_char is not None+ and _is_boundary_text_char(previous_char)+ and _is_punctuation_or_symbol(next_char)+ ):+ return True+ previous_unit = unit+ return False+++def _select_block_inline_syntax(para_block) -> str:+ """按 block 粒度选择 inline 输出语法:简单样式用 Markdown,复杂样式统一 HTML。"""+ units = list(_iter_block_inline_units(para_block))+ simple_style_names = set()++ for span in _iter_para_inline_spans(para_block):+ span_type = span.get('type')+ if span_type == ContentType.HYPERLINK and _hyperlink_requires_html(span):+ return OFFICE_INLINE_SYNTAX_HTML++ for unit in units:+ content = unit.get('content', '')+ if not content:+ continue+ style_name = _simple_markdown_style_name(unit.get('style'))+ if style_name == '':+ return OFFICE_INLINE_SYNTAX_HTML+ if style_name is not None:+ simple_style_names.add(style_name)+ if len(simple_style_names) > 1:+ return OFFICE_INLINE_SYNTAX_HTML++ if _has_markdown_boundary_risk(units):+ return OFFICE_INLINE_SYNTAX_HTML+ return OFFICE_INLINE_SYNTAX_MARKDOWN+++def _append_style_range_token(+ tokens: list[StyleRangeToken],+ rendered_content: str,+ style: list | set | None,+):+ """追加一个可参与 HTML 范围合并的文本 token,空内容不进入 wrapper diff。"""+ if not rendered_content:+ return+ tokens.append(+ StyleRangeToken(+ content=rendered_content,+ style=set(style or []),+ )+ )+++def _extend_style_range_tokens(+ tokens: list[StyleRangeToken],+ original_content: str,+ span_style: list,+ inline_syntax: str,+):+ """把原始 text span 拆成 HTML 合并 token,并保留现有可见空格 marker 规则。"""+ if not original_content:+ return++ marker = _get_visible_space_marker(span_style)+ if marker:+ render_style = list(span_style or [])+ if marker == '-' and not _is_ascii_space_only(original_content):+ rendered_content = _render_text_with_edge_space_markers(+ original_content,+ marker,+ inline_syntax,+ )+ elif _is_ascii_space_only(original_content):+ rendered_content = _replace_ascii_spaces_with_marker(+ original_content,+ marker,+ inline_syntax,+ )+ ignored_style = 'underline' if marker == '_' else 'strikethrough'+ render_style = [+ name for name in render_style+ if name != ignored_style+ ]+ else:+ rendered_content = _render_text_with_edge_space_markers(+ original_content,+ marker,+ inline_syntax,+ )+ _append_style_range_token(+ tokens,+ rendered_content,+ render_style,+ )+ return++ escaped_content = _escape_office_inline_text(original_content, inline_syntax)+ content_stripped = escaped_content.strip()+ if content_stripped:+ leading = escaped_content[:len(escaped_content) - len(escaped_content.lstrip())]+ trailing = escaped_content[len(escaped_content.rstrip()):]+ if leading:+ _append_style_range_token(+ tokens,+ leading,+ [],+ )+ _append_style_range_token(+ tokens,+ content_stripped,+ span_style,+ )+ if trailing:+ _append_style_range_token(+ tokens,+ trailing,+ [],+ )+ else:+ _append_style_range_token(tokens, original_content, [])+++def _build_style_range_tokens(+ text_spans: list[dict],+ inline_syntax: str,+) -> list[StyleRangeToken]:+ """将连续文本 span 标准化为 HTML token 序列,供统一 wrapper writer 渲染。"""+ tokens = []+ for span in text_spans:+ _extend_style_range_tokens(+ tokens,+ str(span.get('content', '')),+ span.get('style', []),+ inline_syntax,+ )+ return tokens+++def _style_range_stack(token: StyleRangeToken) -> list[str]:+ """按外到内顺序生成 HTML block 需要打开的 wrapper 栈。"""+ style = token.style+ stack = []+ if 'emphasis' in style:+ stack.append('emphasis')+ if 'strikethrough' in style:+ stack.append('strikethrough')+ if 'italic' in style:+ stack.append('italic')+ if 'bold' in style:+ stack.append('bold')+ if 'underline' in style:+ stack.append('underline')+ if 'superscript' in style:+ stack.append('superscript')+ elif 'subscript' in style:+ stack.append('subscript')+ return stack+++def _style_wrapper_open(wrapper: str) -> str:+ """返回指定 wrapper 的打开标记。"""+ return STYLE_WRAPPER_OPEN.get(wrapper, '')+++def _style_wrapper_close(wrapper: str) -> str:+ """返回指定 wrapper 的关闭标记。"""+ return STYLE_WRAPPER_CLOSE.get(wrapper, '')+++def _common_stack_prefix_len(+ current_stack: list[str],+ next_stack: list[str],+) -> int:+ """计算两个 wrapper 栈从外到内的共同前缀长度。"""+ prefix_len = 0+ for current, next_item in zip(current_stack, next_stack):+ if current != next_item:+ break+ prefix_len += 1+ return prefix_len+++def _render_style_range_tokens(tokens: list[StyleRangeToken]) -> str:+ """使用 HTML wrapper stack diff 渲染连续文本 token,合并可连续表达的共同样式。"""+ rendered_parts = []+ current_stack = []++ for token in tokens:+ next_stack = _style_range_stack(token)+ prefix_len = _common_stack_prefix_len(current_stack, next_stack)++ for wrapper in reversed(current_stack[prefix_len:]):+ rendered_parts.append(_style_wrapper_close(wrapper))+ for wrapper in next_stack[prefix_len:]:+ rendered_parts.append(_style_wrapper_open(wrapper))++ rendered_parts.append(token.content)+ current_stack = next_stack++ for wrapper in reversed(current_stack):+ rendered_parts.append(_style_wrapper_close(wrapper))++ return ''.join(rendered_parts)+++def _append_markdown_grouped_text_parts(+ parts: list[RenderedPart],+ text_spans: list[dict],+):+ """渲染简单 Markdown block,只合并相邻完全同样式片段。"""+ pending_content = []+ pending_style = None++ def flush_pending():+ nonlocal pending_content, pending_style+ if pending_content:+ _append_text_part(+ parts,+ ''.join(pending_content),+ list(pending_style or []),+ OFFICE_INLINE_SYNTAX_MARKDOWN,+ )+ pending_content = []+ pending_style = None++ for span in text_spans:+ span_style = tuple(span.get('style', []))+ if pending_style is None:+ pending_style = span_style+ if span_style != pending_style:+ flush_pending()+ pending_style = span_style+ pending_content.append(str(span.get('content', '')))+ flush_pending()+++def _append_style_grouped_text_parts(+ parts: list[RenderedPart],+ text_spans: list[dict],+ inline_syntax: str,+):+ """按 block 语法渲染连续文本 span:简单 Markdown,复杂 HTML。"""+ if inline_syntax == OFFICE_INLINE_SYNTAX_MARKDOWN:+ _append_markdown_grouped_text_parts(parts, text_spans)+ return++ leading_spans, core_spans, trailing_spans = _split_plain_blank_edges(text_spans)+ for span in leading_spans:+ _append_text_part(+ parts,+ span.get('content', ''),+ span.get('style', []),+ inline_syntax,+ )++ tokens = _build_style_range_tokens(core_spans, inline_syntax)+ if tokens:+ rendered_content = _render_style_range_tokens(tokens)+ parts.append(+ _make_rendered_part(+ ContentType.TEXT,+ rendered_content,+ )+ )++ for span in trailing_spans:+ _append_text_part(+ parts,+ span.get('content', ''),+ span.get('style', []),+ inline_syntax,+ )+++def _render_hyperlink_children_label(children: list[dict], inline_syntax: str) -> str:+ """渲染 hyperlink 的子文本片段,保留各自样式后再组成同一个链接 label。"""+ child_parts = []+ child_text_spans = []+ for child in children or []:+ if child.get('type') != ContentType.TEXT:+ continue+ child_text_spans.append({+ 'content': child.get('content', ''),+ 'style': child.get('style', []),+ })+ _append_style_grouped_text_parts(child_parts, child_text_spans, inline_syntax)+ return _join_rendered_parts(child_parts).strip()+++def _append_hyperlink_part(+ parts: list[RenderedPart],+ original_content: str,+ span_style: list,+ inline_syntax: str,+ url: str = '',+ plain_text_only: bool = False,+ children: list[dict] | None = None,+):+ """渲染 hyperlink 片段;HTML block 使用 <a>,Markdown block 使用 []()。"""+ if children:+ styled_text = _render_hyperlink_children_label(children, inline_syntax)+ if not styled_text:+ return+ rendered_content = (+ styled_text+ if plain_text_only+ else _render_link(styled_text, url, inline_syntax)+ )+ else:+ stripped_content = original_content.strip()+ if not stripped_content:+ return++ styled_text = _render_styled_inline_text(+ stripped_content,+ span_style,+ inline_syntax,+ )+ 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+ else:+ rendered_content = _render_link(styled_text, url, inline_syntax)++ parts.append(+ _make_rendered_part(+ ContentType.HYPERLINK,+ rendered_content,+ )+ )+++def merge_para_with_text(para_block, escape_text_block_prefix=True):+ """将 Office 段落 block 渲染为 Markdown/HTML 混合文本,按 block 自动选择行内语法。"""+ inline_syntax = _select_block_inline_syntax(para_block)+ parts = []+ text_span_buffer = []++ def flush_text_span_buffer():+ """遇到公式、超链接等边界时落盘连续文本 span,避免跨语义边界合并。"""+ if not text_span_buffer:+ return+ _append_style_grouped_text_parts(parts, text_span_buffer, inline_syntax)+ text_span_buffer.clear()++ if para_block['type'] == BlockType.TITLE:+ if para_block.get('is_numbered_style', False):+ section_number = para_block.get('section_number', '')+ if section_number:+ parts.append(+ _make_rendered_part(+ ContentType.TEXT,+ f"{section_number} ",+ )+ )++ for line in para_block['lines']:+ for span in line['spans']:+ span_type = span['type']+ span_style = span.get('style', [])++ if span_type == ContentType.TEXT:+ text_span_buffer.append({+ 'content': span.get('content', ''),+ 'style': span_style,+ })+ elif span_type == ContentType.INLINE_EQUATION:+ flush_text_span_buffer()+ content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"+ content = content.strip()+ if content:+ parts.append(+ _make_rendered_part(+ span_type,+ content,+ )+ )+ elif span_type == ContentType.INTERLINE_EQUATION:+ flush_text_span_buffer()+ content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"+ content = content.strip()+ if content:+ parts.append(+ _make_rendered_part(+ span_type,+ content,+ )+ )+ elif span_type == ContentType.HYPERLINK:+ flush_text_span_buffer()+ _append_hyperlink_part(+ parts,+ span['content'],+ span_style,+ inline_syntax,+ url=span.get('url', ''),+ children=span.get('children'),+ )+ else:+ flush_text_span_buffer()++ flush_text_span_buffer()+ para_text = _join_rendered_parts(parts)+ if para_block.get('type') == BlockType.TEXT:+ para_text = _strip_text_block_markdown_edges(para_text)+ para_text = _escape_standalone_marker_rule(para_text)+ if escape_text_block_prefix:+ para_text = escape_text_block_markdown_prefix(para_text)+ return para_textdiff --git a/mineru/backend/office/mkcontent/output_builders.py b/mineru/backend/office/mkcontent/output_builders.pynew file mode 100644index 00000000..62d68df4--- /dev/null+++ b/mineru/backend/office/mkcontent/output_builders.py@@ -0,0 +1,776 @@+# Copyright (c) Opendatalab. All rights reserved.+import re++from mineru.utils.enum_class import MakeMode, BlockType, ContentType, ContentTypeV2+from mineru.backend.office.mkcontent.inline_renderer import (+ _append_hyperlink_part,+ _append_text_part,+ _apply_configured_style,+ _escape_office_inline_text,+ _join_rendered_parts,+ _make_rendered_part,+ _render_link,+ _select_block_inline_syntax,+ get_title_level,+ inline_left_delimiter,+ inline_right_delimiter,+ merge_para_with_text,+)+++def _prefix_table_img_src(html: str, img_buket_path: str) -> str:+ """给表格 HTML 内的本地图片 src 加上输出图片目录前缀。"""+ 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 _replace_eq_tags_in_table_html(html: str) -> str:+ """把表格或图表 HTML 中的 <eq> 标签替换为当前配置的行内公式定界符。"""+ if not html:+ return html+ return re.sub(+ r'<eq>(.*?)</eq>',+ lambda m: f' {inline_left_delimiter}{m.group(1)}{inline_right_delimiter} ',+ html,+ flags=re.DOTALL,+ )+++def _format_embedded_html(html: str, img_buket_path: str) -> str:+ """统一处理 Office 嵌入 HTML 的图片路径和行内公式标签。"""+ return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_buket_path))+++def _build_media_path(img_buket_path: str, image_path: str) -> str:+ """构造图片展示路径,空图片路径保持为空。"""+ if not image_path:+ return ''+ if not img_buket_path:+ return image_path+ return f"{img_buket_path}/{image_path}"+++def _get_ordered_list_start(list_block):+ """读取有序列表起始编号,兼容旧版数据缺少 start 字段的情况。"""+ try:+ return int(list_block.get('start', 1))+ except (TypeError, ValueError):+ return 1+++def _flatten_list_items(list_block):+ """Recursively flatten nested list blocks into a list of prefixed item strings."""+ items = []+ ilevel = list_block.get('ilevel', 0)+ attribute = list_block.get('attribute', 'unordered')+ indent = ' ' * ilevel+ ordered_counter = _get_ordered_list_start(list_block)++ for block in list_block.get('blocks', []):+ if block['type'] in [BlockType.LIST, BlockType.INDEX]:+ items.extend(_flatten_list_items(block))+ else:+ item_text = merge_para_with_text(block, escape_text_block_prefix=False)+ if item_text.strip():+ if attribute == 'ordered':+ items.append(f"{indent}{ordered_counter}. {item_text}")+ ordered_counter += 1+ else:+ items.append(f"{indent}- {item_text}")++ return items+++def _flatten_list_items_v2(list_block):+ """Recursively flatten nested list blocks into v2-structured item dicts."""+ items = []+ ilevel = list_block.get('ilevel', 0)+ attribute = list_block.get('attribute', 'unordered')+ ordered_counter = _get_ordered_list_start(list_block)++ for block in list_block.get('blocks', []):+ if block['type'] in [BlockType.LIST, BlockType.INDEX]:+ items.extend(_flatten_list_items_v2(block))+ else:+ item_content = merge_para_with_text_v2(block)+ if item_content:+ if attribute == 'ordered':+ prefix = f"{' ' * ilevel}{ordered_counter}."+ ordered_counter += 1+ else:+ prefix = f"{' ' * ilevel}-"+ item = {+ 'item_type': 'text',+ 'ilevel': ilevel,+ 'prefix': prefix,+ 'item_content': item_content,+ }+ anchor = block.get("anchor")+ if isinstance(anchor, str) and anchor.strip():+ item["anchor"] = anchor.strip()+ items.append(item)++ return items+++def merge_list_to_markdown(list_block):+ """Recursively convert a nested list block to markdown text."""+ return '\n'.join(_flatten_list_items(list_block)) + '\n'+++def _collect_index_span_items(text_block):+ """按原始顺序收集目录叶子节点中的 span 三元组。"""+ span_items = []+ for line in text_block.get('lines', []):+ for span in line.get('spans', []):+ span_items.append((+ span.get('content', ''),+ span.get('type'),+ span.get('style', []),+ ))+ return span_items+++def _normalize_anchor(block) -> str | None:+ """规范化 block 锚点,空值返回 None。"""+ anchor = block.get('anchor')+ if not isinstance(anchor, str) or not anchor.strip():+ return None+ return anchor.strip()+++def _looks_like_index_page_token(token: str) -> bool:+ """判断目录 tab 后缀是否像页码,避免误删正文内容。"""+ token = token.strip()+ if not token:+ return False+ if len(token) > 12:+ return False+ if re.search(r'[\u4e00-\u9fff]', token):+ return False+ if re.fullmatch(r'\d+', token):+ return True+ if re.fullmatch(r'[ivxlcdm]+', token.lower()):+ return True+ if re.fullmatch(r'[a-zA-Z]', token):+ return True+ return False+++def _strip_index_page_tail(span_items):+ """去掉目录叶子末尾 tab+页码,并把剩余 tab 转成普通空格。"""+ last_tab_span_idx = -1+ for i, (content, span_type, _) in enumerate(span_items):+ if span_type != ContentType.INLINE_EQUATION and '\t' in content:+ last_tab_span_idx = i++ should_strip_page_tail = False+ if last_tab_span_idx != -1:+ last_tab_content = span_items[last_tab_span_idx][0]+ tab_tail = last_tab_content.rsplit('\t', 1)[1]+ should_strip_page_tail = _looks_like_index_page_token(tab_tail)++ stripped_span_items = []+ for i, (content, span_type, span_style) in enumerate(span_items):+ if span_type != ContentType.INLINE_EQUATION:+ if i == last_tab_span_idx and should_strip_page_tail:+ content = content.rsplit('\t', 1)[0]+ content = content.replace('\t', ' ')+ stripped_span_items.append((content, span_type, span_style))+ return stripped_span_items+++def _get_uniform_index_style(span_items) -> list | None:+ """如果目录叶子所有非公式 span 样式完全一致,则返回统一样式。"""+ non_eq_styles = [+ tuple(span_style)+ for content, span_type, span_style in span_items+ if content and span_type != ContentType.INLINE_EQUATION+ ]+ if not non_eq_styles:+ return None+ first_style = non_eq_styles[0]+ if first_style and all(style == first_style for style in non_eq_styles):+ return list(first_style)+ return None+++def _render_uniform_index_item(span_items, uniform_style, inline_syntax) -> str:+ """用统一样式渲染目录叶子,避免同样式片段产生碎片化 marker。"""+ raw_parts = []+ for content, span_type, _span_style in span_items:+ if not content:+ continue+ if span_type == ContentType.INLINE_EQUATION:+ raw_parts.append(+ f'{inline_left_delimiter}{content}{inline_right_delimiter}'+ )+ else:+ raw_parts.append(_escape_office_inline_text(content, inline_syntax))+ item_text = ''.join(raw_parts).strip()+ if not item_text:+ return ''+ return _apply_configured_style(item_text, uniform_style, inline_syntax)+++def _render_mixed_index_item(span_items, inline_syntax) -> str:+ """逐 span 渲染目录叶子,超链接 span 在目录中仅保留可见文本。"""+ rendered_parts = []+ for content, span_type, span_style in span_items:+ if not content:+ continue+ if span_type == ContentType.INLINE_EQUATION:+ rendered_parts.append(+ _make_rendered_part(+ span_type,+ f'{inline_left_delimiter}{content}{inline_right_delimiter}',+ )+ )+ elif span_type == ContentType.HYPERLINK:+ _append_hyperlink_part(+ rendered_parts,+ content,+ span_style,+ inline_syntax,+ plain_text_only=True,+ )+ else:+ _append_text_part(+ rendered_parts,+ content,+ span_style,+ inline_syntax,+ )+ return _join_rendered_parts(rendered_parts).strip()+++def _render_index_leaf_item(text_block, indent: str) -> str | None:+ """渲染单个目录叶子节点,并在有锚点时挂载内部链接。"""+ inline_syntax = _select_block_inline_syntax(text_block)+ span_items = _collect_index_span_items(text_block)+ if not span_items:+ return None++ span_items = _strip_index_page_tail(span_items)+ uniform_style = _get_uniform_index_style(span_items)+ if uniform_style:+ item_text = _render_uniform_index_item(+ span_items,+ uniform_style,+ inline_syntax,+ )+ else:+ item_text = _render_mixed_index_item(span_items, inline_syntax)+ if not item_text:+ return None++ anchor = _normalize_anchor(text_block)+ if anchor is not None:+ item_text = _render_link(item_text, f"#{anchor}", inline_syntax)+ return f"{indent}- {item_text}"+++def _flatten_index_items(index_block):+ """递归展平目录 block,保留目录锚点和目录项样式。"""+ items = []+ indent = ' ' * index_block.get('ilevel', 0)+ for child in index_block.get('blocks', []):+ if child.get('type') == BlockType.INDEX:+ items.extend(_flatten_index_items(child))+ elif child.get('type') == BlockType.TEXT:+ item_text = _render_index_leaf_item(child, indent)+ if item_text:+ items.append(item_text)+ return items+++def merge_index_to_markdown(index_block):+ """Convert a nested index (TOC) block to markdown with hyperlinks."""+ return '\n'.join(_flatten_index_items(index_block)) + '\n'+++def _iter_child_blocks(para_block, block_type: str):+ """按原始顺序遍历指定类型的子 block。"""+ for block in para_block.get('blocks', []):+ if block.get('type') == block_type:+ yield block+++def _iter_block_spans(block):+ """按原始顺序遍历 block 下所有 span。"""+ for line in block.get('lines', []):+ for span in line.get('spans', []):+ yield span+++def _iter_body_spans(para_block, body_type: str, span_type: str):+ """遍历视觉类 block 的 body span,统一 image/table/chart 的查找方式。"""+ for block in _iter_child_blocks(para_block, body_type):+ for span in _iter_block_spans(block):+ if span.get('type') == span_type:+ yield span+++def _collect_caption_texts(para_block, caption_type: str) -> list[str]:+ """收集 legacy markdown/content_list 使用的 caption 文本。"""+ return [+ merge_para_with_text(block)+ for block in _iter_child_blocks(para_block, caption_type)+ ]+++def _collect_caption_v2(para_block, caption_type: str) -> list[dict]:+ """收集 content_list_v2 使用的结构化 caption spans。"""+ caption_content = []+ for block in _iter_child_blocks(para_block, caption_type):+ caption_content.extend(merge_para_with_text_v2(block))+ return caption_content+++def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=None):+ page_markdown = []+ for para_block in para_blocks:+ para_text = ''+ para_type = para_block['type']+ if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:+ para_text = merge_para_with_text(para_block)+ if para_type == BlockType.TEXT:+ bookmark_anchor = para_block.get("anchor")+ if (+ isinstance(bookmark_anchor, str)+ and bookmark_anchor.strip()+ and bookmark_anchor.strip().startswith("_Toc")+ ):+ para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{para_text}'+ elif para_type == BlockType.LIST:+ para_text = merge_list_to_markdown(para_block)+ elif para_type == BlockType.INDEX:+ para_text = merge_index_to_markdown(para_block)+ elif para_type == BlockType.TITLE:+ title_level = get_title_level(para_block)+ title_text = merge_para_with_text(para_block)+ bookmark_anchor = para_block.get("anchor")+ if isinstance(bookmark_anchor, str) and bookmark_anchor.strip():+ para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{"#" * title_level} {title_text}'+ else:+ para_text = f'{"#" * title_level} {title_text}'+ elif para_type == BlockType.IMAGE:+ if make_mode == MakeMode.NLP_MD:+ continue+ elif make_mode == MakeMode.MM_MD:+ for span in _iter_body_spans(+ para_block,+ BlockType.IMAGE_BODY,+ ContentType.IMAGE,+ ):+ if span.get('image_path', ''):+ para_text += f""+ for caption_text in _collect_caption_texts(+ para_block,+ BlockType.IMAGE_CAPTION,+ ):+ para_text += ' \n' + caption_text++ elif para_type == BlockType.TABLE:+ if make_mode == MakeMode.NLP_MD:+ continue+ elif make_mode == MakeMode.MM_MD:+ for span in _iter_body_spans(+ para_block,+ BlockType.TABLE_BODY,+ ContentType.TABLE,+ ):+ para_text += f"\n{_format_embedded_html(span['html'], img_buket_path)}\n"+ for caption_text in _collect_caption_texts(+ para_block,+ BlockType.TABLE_CAPTION,+ ):+ para_text += ' \n' + caption_text+ elif para_type == BlockType.CHART:+ if make_mode == MakeMode.NLP_MD:+ continue+ elif make_mode == MakeMode.MM_MD:+ image_path, chart_content = get_body_data(para_block)+ if chart_content:+ para_text += f"\n{_format_embedded_html(chart_content, img_buket_path)}\n"+ elif image_path:+ para_text += f"})"+ else:+ continue+ for caption_text in _collect_caption_texts(+ para_block,+ BlockType.CHART_CAPTION,+ ):+ para_text += ' \n' + caption_text+ if para_text.strip() == '':+ continue+ else:+ # page_markdown.append(para_text.strip())+ page_markdown.append(para_text.strip('\r\n'))++ return page_markdown+++def make_blocks_to_content_list(para_block, img_buket_path, page_idx):+ para_type = para_block['type']+ para_content = {}+ if para_type in [+ BlockType.TEXT,+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_FOOTNOTE,+ ]:+ para_content = {+ 'type': para_type,+ 'text': merge_para_with_text(para_block),+ }+ elif para_type == BlockType.LIST:+ para_content = {+ 'type': para_type,+ 'list_items': _flatten_list_items(para_block),+ }+ elif para_type == BlockType.INDEX:+ para_content = {+ 'type': para_type,+ 'list_items': _flatten_index_items(para_block),+ }+ elif para_type == BlockType.TITLE:+ title_level = get_title_level(para_block)+ para_content = {+ 'type': ContentType.TEXT,+ 'text': merge_para_with_text(para_block),+ }+ if title_level != 0:+ para_content['text_level'] = title_level+ elif para_type == BlockType.INTERLINE_EQUATION:+ para_content = {+ 'type': ContentType.EQUATION,+ 'text': merge_para_with_text(para_block),+ 'text_format': 'latex',+ }+ elif para_type == BlockType.IMAGE:+ para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: []}+ for span in _iter_body_spans(+ para_block,+ BlockType.IMAGE_BODY,+ ContentType.IMAGE,+ ):+ if span.get('image_path', ''):+ para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"+ para_content[BlockType.IMAGE_CAPTION].extend(+ _collect_caption_texts(para_block, BlockType.IMAGE_CAPTION)+ )+ elif para_type == BlockType.TABLE:+ para_content = {'type': ContentType.TABLE, BlockType.TABLE_CAPTION: []}+ for span in _iter_body_spans(+ para_block,+ BlockType.TABLE_BODY,+ ContentType.TABLE,+ ):+ if span.get('html', ''):+ para_content[BlockType.TABLE_BODY] = _format_embedded_html(+ span['html'],+ img_buket_path,+ )+ para_content[BlockType.TABLE_CAPTION].extend(+ _collect_caption_texts(para_block, BlockType.TABLE_CAPTION)+ )+ elif para_type == BlockType.CHART:+ para_content = {+ 'type': ContentType.CHART,+ 'img_path': '',+ 'content': '',+ BlockType.CHART_CAPTION: [],+ }+ for span in _iter_body_spans(+ para_block,+ BlockType.CHART_BODY,+ ContentType.CHART,+ ):+ para_content['img_path'] = _build_media_path(+ img_buket_path,+ span.get('image_path', ''),+ )+ if span.get('content', ''):+ para_content['content'] = _format_embedded_html(+ span['content'],+ img_buket_path,+ )+ para_content[BlockType.CHART_CAPTION].extend(+ _collect_caption_texts(para_block, BlockType.CHART_CAPTION)+ )++ para_content['page_idx'] = page_idx+ anchor = para_block.get("anchor")+ if isinstance(anchor, str) and anchor.strip():+ para_content["anchor"] = anchor.strip()++ return para_content+++def make_blocks_to_content_list_v2(para_block, img_buket_path):+ para_type = para_block['type']+ para_content = {}+ if para_type in [+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_FOOTNOTE,+ ]:+ if para_type == BlockType.HEADER:+ content_type = ContentTypeV2.PAGE_HEADER+ elif para_type == BlockType.FOOTER:+ content_type = ContentTypeV2.PAGE_FOOTER+ elif para_type == BlockType.PAGE_FOOTNOTE:+ content_type = ContentTypeV2.PAGE_FOOTNOTE+ else:+ raise ValueError(f"Unknown para_type: {para_type}")+ para_content = {+ 'type': content_type,+ 'content': {+ f"{content_type}_content": merge_para_with_text_v2(para_block),+ }+ }+ elif para_type == BlockType.TITLE:+ title_level = get_title_level(para_block)+ if title_level != 0:+ para_content = {+ 'type': ContentTypeV2.TITLE,+ 'content': {+ "title_content": merge_para_with_text_v2(para_block),+ "level": title_level+ }+ }+ else:+ para_content = {+ 'type': ContentTypeV2.PARAGRAPH,+ 'content': {+ "paragraph_content": merge_para_with_text_v2(para_block),+ }+ }+ elif para_type in [+ BlockType.TEXT,+ ]:+ para_content = {+ 'type': ContentTypeV2.PARAGRAPH,+ 'content': {+ 'paragraph_content': merge_para_with_text_v2(para_block),+ }+ }+ elif para_type == BlockType.INTERLINE_EQUATION:+ _, math_content = get_body_data(para_block)+ para_content = {+ 'type': ContentTypeV2.EQUATION_INTERLINE,+ 'content': {+ 'math_content': math_content,+ 'math_type': 'latex',+ }+ }+ elif para_type == BlockType.IMAGE:+ image_path, _ = get_body_data(para_block)+ image_source = {+ 'path': f"{img_buket_path}/{image_path}",+ }+ para_content = {+ 'type': ContentTypeV2.IMAGE,+ 'content': {+ 'image_source': image_source,+ 'image_caption': _collect_caption_v2(+ para_block,+ BlockType.IMAGE_CAPTION,+ ),+ }+ }+ elif para_type == BlockType.TABLE:+ _, html = get_body_data(para_block)+ if html.count("<table") > 1:+ table_nest_level = 2+ else:+ table_nest_level = 1+ if (+ "colspan" in html or+ "rowspan" in html or+ table_nest_level > 1+ ):+ table_type = ContentTypeV2.TABLE_COMPLEX+ else:+ table_type = ContentTypeV2.TABLE_SIMPLE++ para_content = {+ 'type': ContentTypeV2.TABLE,+ 'content': {+ 'table_caption': _collect_caption_v2(+ para_block,+ BlockType.TABLE_CAPTION,+ ),+ 'html': _format_embedded_html(html, img_buket_path),+ 'table_type': table_type,+ 'table_nest_level': table_nest_level,+ }+ }+ elif para_type == BlockType.CHART:+ image_path, chart_content = get_body_data(para_block)+ para_content = {+ 'type': ContentTypeV2.CHART,+ 'content': {+ 'image_source': {+ 'path': _build_media_path(img_buket_path, image_path),+ },+ 'content': _format_embedded_html(chart_content, img_buket_path),+ 'chart_caption': _collect_caption_v2(+ para_block,+ BlockType.CHART_CAPTION,+ ),+ }+ }+ elif para_type == BlockType.LIST:+ list_type = ContentTypeV2.LIST_TEXT+ attribute = para_block.get('attribute', 'unordered')+ para_content = {+ 'type': ContentTypeV2.LIST,+ 'content': {+ 'list_type': list_type,+ 'attribute': attribute,+ 'list_items': _flatten_list_items_v2(para_block),+ }+ }+ elif para_type == BlockType.INDEX:+ para_content = {+ 'type': ContentTypeV2.INDEX,+ 'content': {+ 'list_type': ContentTypeV2.LIST_TEXT,+ 'list_items': _flatten_list_items_v2(para_block),+ }+ }++ anchor = para_block.get("anchor")+ if isinstance(anchor, str) and anchor.strip():+ para_content["anchor"] = anchor.strip()++ return para_content+++def get_body_data(para_block):+ """+ Extract image_path and body content from para_block+ Returns:+ - For IMAGE/INTERLINE_EQUATION: (image_path, '')+ - For TABLE: (image_path, html)+ - For CHART: (image_path, content)+ - Default: ('', '')+ """++ def get_data_from_spans(lines):+ synthetic_block = {'lines': lines}+ for span in _iter_block_spans(synthetic_block):+ span_type = span.get('type')+ if span_type == ContentType.TABLE:+ return span.get('image_path', ''), span.get('html', '')+ elif span_type == ContentType.CHART:+ return span.get('image_path', ''), span.get('content', '')+ elif span_type == ContentType.IMAGE:+ return span.get('image_path', ''), ''+ elif span_type == ContentType.INTERLINE_EQUATION:+ return span.get('image_path', ''), span.get('content', '')+ elif span_type == ContentType.TEXT:+ return '', span.get('content', '')+ return '', ''++ # 处理嵌套的 blocks 结构+ if 'blocks' in para_block:+ for block in para_block['blocks']:+ block_type = block.get('type')+ if block_type in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY, BlockType.CODE_BODY]:+ result = get_data_from_spans(block.get('lines', []))+ if result != ('', ''):+ return result+ if block_type == BlockType.CHART_BODY:+ return result+ return '', ''++ # 处理直接包含 lines 的结构+ 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):+ """将 Office 段落转换为 content_list_v2 spans,避免原地修改 middle_json。"""+ _visible_styles = {'underline', 'strikethrough'}+ para_content = []+ if para_block.get('type') == BlockType.TITLE:+ section_number = para_block.get('section_number', '')+ if section_number:+ # v2 保持结构化 spans,同时补上 middle_json 已生成的自动标题编号。+ para_content.append({+ 'type': ContentTypeV2.SPAN_TEXT,+ 'content': f'{section_number} ',+ })+ for line in para_block['lines']:+ for span in line['spans']:+ if _span_has_content_for_v2(span, _visible_styles):+ rendered_span = dict(span)+ if rendered_span['type'] == ContentType.INLINE_EQUATION:+ rendered_span['type'] = ContentTypeV2.SPAN_EQUATION_INLINE+ para_content.append(rendered_span)+ return para_content+++def union_make(pdf_info_dict: list,+ make_mode: str,+ img_buket_path: str = '',+ ):++ output_content = []+ for page_info in pdf_info_dict:+ paras_of_layout = page_info.get('para_blocks')+ paras_of_discarded = page_info.get('discarded_blocks')+ page_idx = page_info.get('page_idx')+ if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:+ if not paras_of_layout:+ continue+ page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, img_buket_path,+ page_idx=page_idx)+ output_content.extend(page_markdown)+ elif make_mode == MakeMode.CONTENT_LIST:+ para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])+ if not para_blocks:+ continue+ for para_block in para_blocks:+ para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx)+ output_content.append(para_content)+ elif make_mode == MakeMode.CONTENT_LIST_V2:+ # https://github.com/drunkpig/llm-webkit-mirror/blob/dev6/docs/specification/output_format/content_list_spec.md+ para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])+ page_contents = []+ if para_blocks:+ for para_block in para_blocks:+ para_content = make_blocks_to_content_list_v2(para_block, img_buket_path)+ page_contents.append(para_content)+ output_content.append(page_contents)++ if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:+ return '\n\n'.join(output_content)+ elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:+ return output_content+ return Nonediff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.pyindex d84aae96..6b6d42b3 100644--- a/mineru/backend/office/office_magic_model.py+++ b/mineru/backend/office/office_magic_model.py@@ -231,7 +231,7 @@ def parse_text_block_spans(content: str) -> list:- <hyperlink><text [style="..."]>...</text><url>...</url></hyperlink>: 超链接(支持样式)- <text style="...">...</text>: 带字体样式的普通文本- 字体样式值(逗号分隔):bold, italic, underline, strikethrough+ 字体样式值(逗号分隔):bold, italic, underline, emphasis, strikethrough, superscript, subscriptArgs:content: 文本块的content字符串,可能包含特殊标签diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.pyindex e8be506e..2ff33d92 100644--- a/mineru/backend/office/office_middle_json_mkcontent.py+++ b/mineru/backend/office/office_middle_json_mkcontent.py@@ -1,1232 +1,36 @@# Copyright (c) Opendatalab. All rights reserved.-import os-import re-import unicodedata-from html import escape--from loguru import logger--from mineru.backend.utils.markdown_utils import (- escape_conservative_markdown_text,- escape_text_block_markdown_prefix,+from mineru.backend.office.mkcontent.inline_renderer import (+ display_left_delimiter,+ display_right_delimiter,+ get_title_level,+ inline_left_delimiter,+ inline_right_delimiter,+ merge_para_with_text,+)+from mineru.backend.office.mkcontent.output_builders import (+ get_body_data,+ make_blocks_to_content_list,+ make_blocks_to_content_list_v2,+ merge_index_to_markdown,+ merge_list_to_markdown,+ merge_para_with_text_v2,+ mk_blocks_to_markdown,+ union_make,)-from mineru.utils.config_reader import get_latex_delimiter_config-from mineru.utils.enum_class import MakeMode, BlockType, ContentType, ContentTypeV2--latex_delimiters_config = get_latex_delimiter_config()--default_delimiters = {- 'display': {'left': '$$', 'right': '$$'},- 'inline': {'left': '$', 'right': '$'}-}--delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters--display_left_delimiter = delimiters['display']['left']-display_right_delimiter = delimiters['display']['right']-inline_left_delimiter = delimiters['inline']['left']-inline_right_delimiter = delimiters['inline']['right']--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, 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 标记解析而导致样式失效的问题,- 改为输出 `<u>~~**text**~~</u>`,兼容性更好。-- Args:- content: 待格式化的文本内容- style: 样式列表,如 ["bold", "italic"]-- Returns:- str: 应用 Markdown 格式后的文本- """- if not style or not content:- return content-- # 第一层(最内层):bold / italic —— 纯 Markdown 符号,放最里面兼容性最好- 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~~,包裹纯 Markdown 内容,广泛支持- if 'strikethrough' in style:- content = f'~~{content}~~'-- # 第三层(最外层):underline —— markdown 无原生语法,使用 HTML <u> 标签- # 作为外层 HTML 容器,不会干扰内部 Markdown 标记的解析- 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---def _apply_html_style(content: str, style: list) -> str:- """Apply inline styles with HTML tags for markdown-hostile contexts."""- if not style or not content:- return content-- if 'bold' in style and 'italic' in style:- content = f'<strong><em>{content}</em></strong>'- elif 'bold' in style:- content = f'<strong>{content}</strong>'- elif 'italic' in style:- content = f'<em>{content}</em>'-- if 'strikethrough' in style:- content = f'<del>{content}</del>'-- if 'underline' in style:- content = f'<u>{content}</u>'-- if 'emphasis' in style:- content = f'<span style="{OFFICE_EMPHASIS_STYLE}">{content}</span>'-- return content---def _get_office_style_render_mode() -> str:- mode = os.getenv(- OFFICE_STYLE_RENDER_MODE_ENV,- OFFICE_STYLE_RENDER_MODE_MARKDOWN,- ).strip().lower()- if mode in {- OFFICE_STYLE_RENDER_MODE_HTML,- OFFICE_STYLE_RENDER_MODE_MARKDOWN,- }:- return mode- logger.warning(- f"Invalid {OFFICE_STYLE_RENDER_MODE_ENV}={mode!r}, "- f"fallback to {OFFICE_STYLE_RENDER_MODE_MARKDOWN!r}"- )- return OFFICE_STYLE_RENDER_MODE_MARKDOWN---def _apply_configured_style(content: str, style: list) -> str:- if _get_office_style_render_mode() == OFFICE_STYLE_RENDER_MODE_MARKDOWN:- return _apply_markdown_style(content, style)- return _apply_html_style(content, style)---def _render_link(text: str, url: str) -> str:- if _get_office_style_render_mode() == OFFICE_STYLE_RENDER_MODE_MARKDOWN:- return f'[{text}]({url})'- return f'<a href="{escape(url, quote=True)}">{text}</a>'---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 _replace_eq_tags_in_table_html(html: str) -> str:- """Replace <eq>...</eq> tags in table HTML with inline math delimiters."""- if not html:- return html- return re.sub(- r'<eq>(.*?)</eq>',- lambda m: f' {inline_left_delimiter}{m.group(1)}{inline_right_delimiter} ',- html,- flags=re.DOTALL,- )---def _format_embedded_html(html: str, img_buket_path: str) -> str:- """Apply image-path prefixing and equation replacement for HTML-like content."""- return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_buket_path))---def _build_media_path(img_buket_path: str, image_path: str) -> str:- """Build a display path while keeping empty image references empty."""- if not image_path:- return ''- if not img_buket_path:- return image_path- return f"{img_buket_path}/{image_path}"---def _escape_office_markdown_text(content: str) -> str:- """Escape plain-text Office content before applying Markdown wrappers."""- if not content:- return content- if _get_office_style_render_mode() != OFFICE_STYLE_RENDER_MODE_MARKDOWN:- return content- return escape_conservative_markdown_text(content)---def get_title_level(para_block):- title_level = para_block.get('level', 2)- return title_level---def _make_rendered_part(- span_type,- rendered_content: str,- raw_content: str = '',- style: list | None = None,- has_markdown_wrapper: bool = False,-):- return {- 'span_type': span_type,- 'rendered_content': rendered_content,- 'raw_content': raw_content,- 'style': style or [],- 'has_markdown_wrapper': has_markdown_wrapper,- }---def _has_markdown_wrapper(style: list) -> bool:- if _get_office_style_render_mode() != OFFICE_STYLE_RENDER_MODE_MARKDOWN:- return False- if not style or 'underline' in style:- return False- return any(name in OFFICE_MARKDOWN_WRAPPER_STYLES for name in style)---def _get_first_non_whitespace_char(text: str):- for ch in text:- if not ch.isspace():- return ch- return None---def _get_last_non_whitespace_char(text: str):- for ch in reversed(text):- if not ch.isspace():- return ch- return None---def _is_punctuation_or_symbol(ch: str) -> bool:- return unicodedata.category(ch).startswith(('P', 'S'))---def _is_boundary_text_char(ch: str) -> bool:- if ch.isspace():- return False- return not _is_punctuation_or_symbol(ch)---def _needs_markdown_it_boundary_space(prev_part: dict, next_part: dict) -> bool:- if _get_office_style_render_mode() != OFFICE_STYLE_RENDER_MODE_MARKDOWN:- return False- if not prev_part.get('has_markdown_wrapper', False):- return False- if next_part.get('span_type') in {- ContentType.HYPERLINK,- ContentType.INLINE_EQUATION,- ContentType.INTERLINE_EQUATION,- }:- return False-- prev_raw = prev_part.get('raw_content', '')- next_raw = next_part.get('raw_content', '')- if not prev_raw.strip() or not next_raw.strip():- return False- if prev_raw[-1].isspace() or next_raw[0].isspace():- return False-- prev_char = _get_last_non_whitespace_char(prev_raw)- next_char = _get_first_non_whitespace_char(next_raw)- if prev_char is None or next_char is None:- return False- if not _is_punctuation_or_symbol(prev_char):- return False- if not _is_boundary_text_char(next_char):- return False- return True---def _join_rendered_parts(parts: list[dict]) -> str:- para_text = ''- prev_part = None-- for i, part in enumerate(parts):- span_type = part['span_type']- content = part['rendered_content']- is_last = i == len(parts) - 1-- if span_type == ContentType.INLINE_EQUATION:- if para_text and not para_text.endswith(' '):- para_text += ' '- para_text += content- if not is_last:- para_text += ' '- else:- if prev_part is not None and _needs_markdown_it_boundary_space(prev_part, part):- para_text += ' '- para_text += content-- prev_part = part-- return para_text---def _strip_text_block_markdown_edges(content: str) -> str:- """去掉 Markdown 文本块首尾普通空白,避免段首缩进被渲染成代码块。"""- if not content:- return content- return content.strip()---def _get_visible_space_marker(style: list) -> str | None:- """根据可见空格样式选择 Markdown marker,下划线优先于删除线。"""- if not style:- return None- if 'underline' in style:- return '_'- if 'strikethrough' in style:- return '-'- return None---def _is_ascii_space_only(content: str) -> bool:- """判断文本是否只由普通 ASCII 空格组成。"""- return bool(content) and all(char == ' ' for char in content)---def _replace_ascii_spaces_with_marker(content: str, marker: str) -> str:- """将普通 ASCII 空格替换为指定 marker,其他文本继续做保守 Markdown 转义。"""- rendered_parts = []- text_buffer = []-- def flush_text_buffer():- if text_buffer:- rendered_parts.append(- escape_conservative_markdown_text(''.join(text_buffer))- )- text_buffer.clear()-- for char in content:- if char == ' ':- flush_text_buffer()- rendered_parts.append(marker)- else:- text_buffer.append(char)-- flush_text_buffer()- return ''.join(rendered_parts)---def _render_text_with_edge_space_markers(content: str, marker: str) -> str:- """渲染非空文本:只把首尾 ASCII 空格转成 marker,中间普通空格保持原样。"""- leading_space_count = len(content) - len(content.lstrip(' '))- trailing_space_count = len(content) - len(content.rstrip(' '))- text_end = len(content) - trailing_space_count if trailing_space_count else len(content)- core_text = content[leading_space_count:text_end]- return (- marker * leading_space_count- + escape_conservative_markdown_text(core_text)- + marker * trailing_space_count- )---def _render_visible_space_marker_text(content: str, style: list) -> str:- """渲染可见样式空格:纯空白用 marker,非空文本只处理边缘空格。"""- marker = _get_visible_space_marker(style)- if marker is None:- return _apply_markdown_style(- escape_conservative_markdown_text(content),- style or [],- )-- style = style or []- if marker == '-' and not _is_ascii_space_only(content):- return _apply_markdown_style(- _render_text_with_edge_space_markers(content, marker),- style,- )-- if _is_ascii_space_only(content):- rendered_content = _replace_ascii_spaces_with_marker(content, marker)- ignored_style = 'underline' if marker == '_' else 'strikethrough'- style = [name for name in style if name != ignored_style]- return _apply_markdown_style(rendered_content, style)-- rendered_content = _render_text_with_edge_space_markers(content, marker)- return _apply_markdown_style(rendered_content, style)---def _has_visible_marker_markdown_wrapper(style: list) -> bool:- """判断可见空格 marker 渲染结果是否包含 Markdown 包裹符。"""- return _has_markdown_wrapper(style)---def _render_styled_inline_text(content: str, style: list) -> str:- """渲染行内文本内容,统一复用可见空格 marker 规则。"""- if (- content- and _get_office_style_render_mode() == OFFICE_STYLE_RENDER_MODE_MARKDOWN- and _get_visible_space_marker(style)- ):- return _render_visible_space_marker_text(content, style)-- escaped_content = _escape_office_markdown_text(content)- return _apply_configured_style(escaped_content, style)---def _escape_standalone_marker_rule(content: str) -> str:- """独立一行全是 marker 时转义首个字符,避免被 Markdown 当作分隔线。"""- if content and all(char == '_' for char in content):- return f'\\{content}'- if content and all(char == '-' for char in content):- return f'\\{content}'- return content---def _append_text_part(parts: list[dict], original_content: str, span_style: list):- if (- original_content- and _get_office_style_render_mode() == OFFICE_STYLE_RENDER_MODE_MARKDOWN- and _get_visible_space_marker(span_style)- ):- parts.append(- _make_rendered_part(- ContentType.TEXT,- _render_visible_space_marker_text(original_content, span_style),- raw_content=original_content,- style=span_style,- has_markdown_wrapper=_has_visible_marker_markdown_wrapper(span_style),- )- )- return-- escaped_content = _escape_office_markdown_text(original_content)- content_stripped = escaped_content.strip()- if content_stripped:- styled = _apply_configured_style(content_stripped, span_style)- leading = escaped_content[:len(escaped_content) - len(escaped_content.lstrip())]- trailing = escaped_content[len(escaped_content.rstrip()):]- parts.append(- _make_rendered_part(- ContentType.TEXT,- leading + styled + trailing,- raw_content=original_content,- style=span_style,- has_markdown_wrapper=_has_markdown_wrapper(span_style),- )- )- 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 = _apply_configured_style(rendered_content, span_style)- parts.append(- _make_rendered_part(- ContentType.TEXT,- rendered_content,- raw_content=original_content,- style=span_style,- )- )---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,-):- 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(- ContentType.HYPERLINK,- rendered_content,- raw_content=original_content,- style=span_style,- has_markdown_wrapper=has_markdown_wrapper,- )- )---def merge_para_with_text(para_block, escape_text_block_prefix=True):- # First pass: collect rendered parts with raw boundary metadata.- parts = []- if para_block['type'] == BlockType.TITLE:- if para_block.get('is_numbered_style', False):- section_number = para_block.get('section_number', '')- if section_number:- parts.append(- _make_rendered_part(- ContentType.TEXT,- f"{section_number} ",- raw_content=f"{section_number} ",- )- )-- for line in para_block['lines']:- for span in line['spans']:- span_type = span['type']- span_style = span.get('style', [])-- if span_type == ContentType.TEXT:- _append_text_part(parts, span['content'], span_style)- elif span_type == ContentType.INLINE_EQUATION:- content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"- content = content.strip()- if content:- parts.append(- _make_rendered_part(- span_type,- content,- raw_content=span['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(- _make_rendered_part(- span_type,- content,- raw_content=span['content'],- )- )- elif span_type == ContentType.HYPERLINK:- _append_hyperlink_part(- parts,- span['content'],- span_style,- url=span.get('url', ''),- children=span.get('children'),- )-- para_text = _join_rendered_parts(parts)- if para_block.get('type') == BlockType.TEXT:- para_text = _strip_text_block_markdown_edges(para_text)- para_text = _escape_standalone_marker_rule(para_text)- if escape_text_block_prefix:- para_text = escape_text_block_markdown_prefix(para_text)- return para_text---def _get_ordered_list_start(list_block):- """读取有序列表起始编号,兼容旧版数据缺少 start 字段的情况。"""- try:- return int(list_block.get('start', 1))- except (TypeError, ValueError):- return 1---def _flatten_list_items(list_block):- """Recursively flatten nested list blocks into a list of prefixed item strings."""- items = []- ilevel = list_block.get('ilevel', 0)- attribute = list_block.get('attribute', 'unordered')- indent = ' ' * ilevel- ordered_counter = _get_ordered_list_start(list_block)-- for block in list_block.get('blocks', []):- if block['type'] in [BlockType.LIST, BlockType.INDEX]:- items.extend(_flatten_list_items(block))- else:- item_text = merge_para_with_text(block, escape_text_block_prefix=False)- if item_text.strip():- if attribute == 'ordered':- items.append(f"{indent}{ordered_counter}. {item_text}")- ordered_counter += 1- else:- items.append(f"{indent}- {item_text}")-- return items---def _flatten_list_items_v2(list_block):- """Recursively flatten nested list blocks into v2-structured item dicts."""- items = []- ilevel = list_block.get('ilevel', 0)- attribute = list_block.get('attribute', 'unordered')- ordered_counter = _get_ordered_list_start(list_block)-- for block in list_block.get('blocks', []):- if block['type'] in [BlockType.LIST, BlockType.INDEX]:- items.extend(_flatten_list_items_v2(block))- else:- item_content = merge_para_with_text_v2(block)- if item_content:- if attribute == 'ordered':- prefix = f"{' ' * ilevel}{ordered_counter}."- ordered_counter += 1- else:- prefix = f"{' ' * ilevel}-"- item = {- 'item_type': 'text',- 'ilevel': ilevel,- 'prefix': prefix,- 'item_content': item_content,- }- anchor = block.get("anchor")- if isinstance(anchor, str) and anchor.strip():- item["anchor"] = anchor.strip()- items.append(item)-- return items---def merge_list_to_markdown(list_block):- """Recursively convert a nested list block to markdown text."""- return '\n'.join(_flatten_list_items(list_block)) + '\n'---def _flatten_index_items(index_block):- """Recursively flatten index (TOC) blocks into markdown list items.-- Strips the trailing tab+page-number from span content and, when target- location fields are present on the leaf text block, wraps the text in- a markdown hyperlink pointing to the body-block anchor.-- Styling (bold, italic, underline, strikethrough) is applied via the- configured office style render mode. HYPERLINK spans are rendered as- plain styled text (without the URL) because TOC entries use- document-internal bookmark links, not external URLs.-- The tab+page-number is stripped from the raw content BEFORE markdown- style markers are applied, so that closing markers (e.g. ``**``) are- never inadvertently removed by the tab-stripping step.- """- items = []- ilevel = index_block.get('ilevel', 0)- indent = ' ' * ilevel-- for child in index_block.get('blocks', []):- if child.get('type') == BlockType.INDEX:- items.extend(_flatten_index_items(child))- elif child.get('type') == BlockType.TEXT:- span_items = [] # list of (content, span_type, span_style)- anchor = child.get('anchor')- if not isinstance(anchor, str) or not anchor.strip():- anchor = None- else:- anchor = anchor.strip()-- for line in child.get('lines', []):- for span in line.get('spans', []):- content = span.get('content', '')- span_style = span.get('style', [])- span_type = span.get('type')- span_items.append((content, span_type, span_style))-- if not span_items:- continue-- # ----------------------------------------------------------- # Step 1: Strip the trailing tab+page-number from the raw- # (unstyled) content BEFORE applying markdown markers.- #- # Find the last non-equation span that contains a tab; strip- # everything after its last tab ONLY when the trailing token- # actually looks like a page number.- # Then replace any remaining internal tabs with spaces so that- # "1.1\t研究对象" → "1.1 研究对象".- # ----------------------------------------------------------- def _looks_like_page_token(token: str) -> bool:- token = token.strip()- if not token:- return False- # Page tokens are usually short and contain no CJK characters.- if len(token) > 12:- return False- if re.search(r'[\u4e00-\u9fff]', token):- return False- # Arabic / Roman / single-letter page styles.- if re.fullmatch(r'\d+', token):- return True- if re.fullmatch(r'[ivxlcdm]+', token.lower()):- return True- if re.fullmatch(r'[a-zA-Z]', token):- return True- return False-- last_tab_span_idx = -1- for i, (content, span_type, _) in enumerate(span_items):- if span_type != ContentType.INLINE_EQUATION and '\t' in content:- last_tab_span_idx = i-- should_strip_page_tail = False- if last_tab_span_idx != -1:- last_tab_content = span_items[last_tab_span_idx][0]- tab_tail = last_tab_content.rsplit('\t', 1)[1]- should_strip_page_tail = _looks_like_page_token(tab_tail)-- # Build stripped span_items- stripped_span_items = []- for i, (content, span_type, span_style) in enumerate(span_items):- if span_type != ContentType.INLINE_EQUATION:- if i == last_tab_span_idx and should_strip_page_tail:- # Strip from last tab onwards (removes tab + page number)- content = content.rsplit('\t', 1)[0]- # Replace remaining internal tabs with spaces- content = content.replace('\t', ' ')- stripped_span_items.append((content, span_type, span_style))-- # ----------------------------------------------------------- # Step 2: Apply markdown styles and build the final text.- #- # If all non-equation spans share the same non-empty style- # (common in TOC entries like all-bold), apply style once to- # the whole item to avoid fragmented markers such as- # "**foo****bar**".- # ----------------------------------------------------------- non_eq_styles = [- tuple(span_style)- for content, span_type, span_style in stripped_span_items- if content and span_type != ContentType.INLINE_EQUATION- ]- uniform_style = None- if non_eq_styles:- first_style = non_eq_styles[0]- if first_style and all(s == first_style for s in non_eq_styles):- uniform_style = list(first_style)-- if uniform_style:- raw_parts = []- for content, span_type, _span_style in stripped_span_items:- if not content:- continue- if span_type == ContentType.INLINE_EQUATION:- raw_parts.append(- f'{inline_left_delimiter}{content}{inline_right_delimiter}'- )- else:- # For TOC rendering, hyperlink spans output as plain text.- raw_parts.append(_escape_office_markdown_text(content))- item_text = ''.join(raw_parts).strip()- if item_text:- item_text = _apply_configured_style(item_text, uniform_style)- else:- rendered_parts = []- for content, span_type, span_style in stripped_span_items:- if not content:- continue- if span_type == ContentType.INLINE_EQUATION:- rendered_parts.append(- _make_rendered_part(- span_type,- f'{inline_left_delimiter}{content}{inline_right_delimiter}',- raw_content=content,- )- )- elif span_type == ContentType.HYPERLINK:- _append_hyperlink_part(- rendered_parts,- content,- span_style,- plain_text_only=True,- )- else:- _append_text_part(rendered_parts, content, span_style)-- item_text = _join_rendered_parts(rendered_parts).strip()- if not item_text:- continue-- if anchor is not None:- item_text = _render_link(item_text, f"#{anchor}")-- items.append(f"{indent}- {item_text}")-- return items---def merge_index_to_markdown(index_block):- """Convert a nested index (TOC) block to markdown with hyperlinks."""- return '\n'.join(_flatten_index_items(index_block)) + '\n'---def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=None):- page_markdown = []- for para_block in para_blocks:- para_text = ''- para_type = para_block['type']- if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:- para_text = merge_para_with_text(para_block)- if para_type == BlockType.TEXT:- bookmark_anchor = para_block.get("anchor")- if (- isinstance(bookmark_anchor, str)- and bookmark_anchor.strip()- and bookmark_anchor.strip().startswith("_Toc")- ):- para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{para_text}'- elif para_type == BlockType.LIST:- para_text = merge_list_to_markdown(para_block)- elif para_type == BlockType.INDEX:- para_text = merge_index_to_markdown(para_block)- elif para_type == BlockType.TITLE:- title_level = get_title_level(para_block)- title_text = merge_para_with_text(para_block)- bookmark_anchor = para_block.get("anchor")- if isinstance(bookmark_anchor, str) and bookmark_anchor.strip():- para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{"#" * title_level} {title_text}'- else:- para_text = f'{"#" * title_level} {title_text}'- elif para_type == BlockType.IMAGE:- if make_mode == MakeMode.NLP_MD:- continue- elif make_mode == MakeMode.MM_MD:- for block in para_block['blocks']: # 1st.拼image_body- if block['type'] == BlockType.IMAGE_BODY:- for line in block['lines']:- for span in line['spans']:- if span['type'] == ContentType.IMAGE:- if span.get('image_path', ''):- para_text += f""- for block in para_block['blocks']: # 2nd.拼image_caption- if block['type'] == BlockType.IMAGE_CAPTION:- para_text += ' \n' + merge_para_with_text(block)-- elif para_type == BlockType.TABLE:- if make_mode == MakeMode.NLP_MD:- continue- elif make_mode == MakeMode.MM_MD:- for block in para_block['blocks']: # 1st.拼table_body- if block['type'] == BlockType.TABLE_BODY:- for line in block['lines']:- for span in line['spans']:- if span['type'] == ContentType.TABLE:- para_text += f"\n{_format_embedded_html(span['html'], img_buket_path)}\n"- for block in para_block['blocks']: # 2nd.拼table_caption- if block['type'] == BlockType.TABLE_CAPTION:- para_text += ' \n' + merge_para_with_text(block)- elif para_type == BlockType.CHART:- if make_mode == MakeMode.NLP_MD:- continue- elif make_mode == MakeMode.MM_MD:- image_path, chart_content = get_body_data(para_block)- if chart_content:- para_text += f"\n{_format_embedded_html(chart_content, img_buket_path)}\n"- elif image_path:- para_text += f"})"- else:- continue- for block in para_block['blocks']:- if block['type'] == BlockType.CHART_CAPTION:- para_text += ' \n' + merge_para_with_text(block)- if para_text.strip() == '':- continue- else:- # page_markdown.append(para_text.strip())- page_markdown.append(para_text.strip('\r\n'))-- return page_markdown---def make_blocks_to_content_list(para_block, img_buket_path, page_idx):- para_type = para_block['type']- para_content = {}- if para_type in [- BlockType.TEXT,- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_FOOTNOTE,- ]:- para_content = {- 'type': para_type,- 'text': merge_para_with_text(para_block),- }- elif para_type == BlockType.LIST:- attribute = para_block.get('attribute', 'unordered')- para_content = {- 'type': para_type,- 'list_items': _flatten_list_items(para_block),- }- elif para_type == BlockType.INDEX:- para_content = {- 'type': para_type,- 'list_items': _flatten_index_items(para_block),- }- elif para_type == BlockType.TITLE:- title_level = get_title_level(para_block)- para_content = {- 'type': ContentType.TEXT,- 'text': merge_para_with_text(para_block),- }- if title_level != 0:- para_content['text_level'] = title_level- elif para_type == BlockType.INTERLINE_EQUATION:- para_content = {- 'type': ContentType.EQUATION,- 'text': merge_para_with_text(para_block),- 'text_format': 'latex',- }- elif para_type == BlockType.IMAGE:- para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: []}- for block in para_block['blocks']:- if block['type'] == BlockType.IMAGE_BODY:- for line in block['lines']:- for span in line['spans']:- if span['type'] == ContentType.IMAGE:- if span.get('image_path', ''):- para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"- if block['type'] == BlockType.IMAGE_CAPTION:- para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))- elif para_type == BlockType.TABLE:- para_content = {'type': ContentType.TABLE, BlockType.TABLE_CAPTION: []}- for block in para_block['blocks']:- if block['type'] == BlockType.TABLE_BODY:- for line in block['lines']:- for span in line['spans']:- if span['type'] == ContentType.TABLE:- if span.get('html', ''):- para_content[BlockType.TABLE_BODY] = _format_embedded_html(span['html'], img_buket_path)- if block['type'] == BlockType.TABLE_CAPTION:- para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))- elif para_type == BlockType.CHART:- para_content = {- 'type': ContentType.CHART,- 'img_path': '',- 'content': '',- BlockType.CHART_CAPTION: [],- }- for block in para_block['blocks']:- if block['type'] == BlockType.CHART_BODY:- for line in block['lines']:- for span in line['spans']:- if span['type'] == ContentType.CHART:- para_content['img_path'] = _build_media_path(- img_buket_path,- span.get('image_path', ''),- )- if span.get('content', ''):- para_content['content'] = _format_embedded_html(- span['content'],- img_buket_path,- )- if block['type'] == BlockType.CHART_CAPTION:- para_content[BlockType.CHART_CAPTION].append(merge_para_with_text(block))-- para_content['page_idx'] = page_idx- anchor = para_block.get("anchor")- if isinstance(anchor, str) and anchor.strip():- para_content["anchor"] = anchor.strip()-- return para_content---def make_blocks_to_content_list_v2(para_block, img_buket_path):- para_type = para_block['type']- para_content = {}- if para_type in [- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_FOOTNOTE,- ]:- if para_type == BlockType.HEADER:- content_type = ContentTypeV2.PAGE_HEADER- elif para_type == BlockType.FOOTER:- content_type = ContentTypeV2.PAGE_FOOTER- elif para_type == BlockType.PAGE_FOOTNOTE:- content_type = ContentTypeV2.PAGE_FOOTNOTE- else:- raise ValueError(f"Unknown para_type: {para_type}")- para_content = {- 'type': content_type,- 'content': {- f"{content_type}_content": merge_para_with_text_v2(para_block),- }- }- elif para_type == BlockType.TITLE:- title_level = get_title_level(para_block)- if title_level != 0:- para_content = {- 'type': ContentTypeV2.TITLE,- 'content': {- "title_content": merge_para_with_text_v2(para_block),- "level": title_level- }- }- else:- para_content = {- 'type': ContentTypeV2.PARAGRAPH,- 'content': {- "paragraph_content": merge_para_with_text_v2(para_block),- }- }- elif para_type in [- BlockType.TEXT,- ]:- para_content = {- 'type': ContentTypeV2.PARAGRAPH,- 'content': {- 'paragraph_content': merge_para_with_text_v2(para_block),- }- }- elif para_type == BlockType.INTERLINE_EQUATION:- _, math_content = get_body_data(para_block)- para_content = {- 'type': ContentTypeV2.EQUATION_INTERLINE,- 'content': {- 'math_content': math_content,- 'math_type': 'latex',- }- }- elif para_type == BlockType.IMAGE:- image_caption = []- image_path, _ = get_body_data(para_block)- image_source = {- 'path': f"{img_buket_path}/{image_path}",- }- for block in para_block['blocks']:- if block['type'] == BlockType.IMAGE_CAPTION:- image_caption.extend(merge_para_with_text_v2(block))- para_content = {- 'type': ContentTypeV2.IMAGE,- 'content': {- 'image_source': image_source,- 'image_caption': image_caption,- }- }- elif para_type == BlockType.TABLE:- table_caption = []- _, html = get_body_data(para_block)- if html.count("<table") > 1:- table_nest_level = 2- else:- table_nest_level = 1- if (- "colspan" in html or- "rowspan" in html or- table_nest_level > 1- ):- table_type = ContentTypeV2.TABLE_COMPLEX- else:- table_type = ContentTypeV2.TABLE_SIMPLE-- for block in para_block['blocks']:- if block['type'] == BlockType.TABLE_CAPTION:- table_caption.extend(merge_para_with_text_v2(block))- para_content = {- 'type': ContentTypeV2.TABLE,- 'content': {- 'table_caption': table_caption,- 'html': _format_embedded_html(html, img_buket_path),- 'table_type': table_type,- 'table_nest_level': table_nest_level,- }- }- elif para_type == BlockType.CHART:- chart_caption = []- image_path, chart_content = get_body_data(para_block)- for block in para_block['blocks']:- if block['type'] == BlockType.CHART_CAPTION:- chart_caption.extend(merge_para_with_text_v2(block))- para_content = {- 'type': ContentTypeV2.CHART,- 'content': {- 'image_source': {- 'path': _build_media_path(img_buket_path, image_path),- },- 'content': _format_embedded_html(chart_content, img_buket_path),- 'chart_caption': chart_caption,- }- }- elif para_type == BlockType.LIST:- list_type = ContentTypeV2.LIST_TEXT- attribute = para_block.get('attribute', 'unordered')- para_content = {- 'type': ContentTypeV2.LIST,- 'content': {- 'list_type': list_type,- 'attribute': attribute,- 'list_items': _flatten_list_items_v2(para_block),- }- }- elif para_type == BlockType.INDEX:- para_content = {- 'type': ContentTypeV2.INDEX,- 'content': {- 'list_type': ContentTypeV2.LIST_TEXT,- 'list_items': _flatten_list_items_v2(para_block),- }- }-- anchor = para_block.get("anchor")- if isinstance(anchor, str) and anchor.strip():- para_content["anchor"] = anchor.strip()-- return para_content---def get_body_data(para_block):- """- Extract image_path and body content from para_block- Returns:- - For IMAGE/INTERLINE_EQUATION: (image_path, '')- - For TABLE: (image_path, html)- - For CHART: (image_path, content)- - Default: ('', '')- """-- def get_data_from_spans(lines):- for line in lines:- for span in line.get('spans', []):- span_type = span.get('type')- if span_type == ContentType.TABLE:- return span.get('image_path', ''), span.get('html', '')- elif span_type == ContentType.CHART:- return span.get('image_path', ''), span.get('content', '')- elif span_type == ContentType.IMAGE:- return span.get('image_path', ''), ''- elif span_type == ContentType.INTERLINE_EQUATION:- return span.get('image_path', ''), span.get('content', '')- elif span_type == ContentType.TEXT:- return '', span.get('content', '')- return '', ''-- # 处理嵌套的 blocks 结构- if 'blocks' in para_block:- for block in para_block['blocks']:- block_type = block.get('type')- if block_type in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY, BlockType.CODE_BODY]:- result = get_data_from_spans(block.get('lines', []))- if result != ('', ''):- return result- if block_type == BlockType.CHART_BODY:- return result- return '', ''-- # 处理直接包含 lines 的结构- 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 = []- if para_block.get('type') == BlockType.TITLE:- section_number = para_block.get('section_number', '')- if section_number:- # v2 保持结构化 spans,同时补上 middle_json 已生成的自动标题编号。- para_content.append({- 'type': ContentTypeV2.SPAN_TEXT,- 'content': f'{section_number} ',- })- for i, line in enumerate(para_block['lines']):- for j, span in enumerate(line['spans']):- 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)- return para_content---def union_make(pdf_info_dict: list,- make_mode: str,- img_buket_path: str = '',- ):-- output_content = []- for page_info in pdf_info_dict:- paras_of_layout = page_info.get('para_blocks')- paras_of_discarded = page_info.get('discarded_blocks')- page_idx = page_info.get('page_idx')- if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:- if not paras_of_layout:- continue- page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, img_buket_path,- page_idx=page_idx)- output_content.extend(page_markdown)- elif make_mode == MakeMode.CONTENT_LIST:- para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])- if not para_blocks:- continue- for para_block in para_blocks:- para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx)- output_content.append(para_content)- elif make_mode == MakeMode.CONTENT_LIST_V2:- # https://github.com/drunkpig/llm-webkit-mirror/blob/dev6/docs/specification/output_format/content_list_spec.md- para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])- page_contents = []- if para_blocks:- for para_block in para_blocks:- para_content = make_blocks_to_content_list_v2(para_block, img_buket_path)- page_contents.append(para_content)- output_content.append(page_contents)- if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:- return '\n\n'.join(output_content)- elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:- return output_content- return None+__all__ = [+ 'display_left_delimiter',+ 'display_right_delimiter',+ 'get_body_data',+ 'get_title_level',+ 'inline_left_delimiter',+ 'inline_right_delimiter',+ 'make_blocks_to_content_list',+ 'make_blocks_to_content_list_v2',+ 'merge_index_to_markdown',+ 'merge_list_to_markdown',+ 'merge_para_with_text',+ 'merge_para_with_text_v2',+ 'mk_blocks_to_markdown',+ 'union_make',+]diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.pyindex c5f2a543..49a0b5e4 100644--- a/mineru/model/docx/docx_converter.py+++ b/mineru/model/docx/docx_converter.py@@ -548,7 +548,12 @@ class DocxConverter:# 检查是否有字体样式has_style = any(fmt is not None and (- fmt.bold or fmt.italic or fmt.underline or fmt.emphasis or fmt.strikethrough+ fmt.bold+ or fmt.italic+ or fmt.underline+ or fmt.emphasis+ or fmt.strikethrough+ or fmt.script != Script.BASELINE)for _, fmt, _ in paragraph_elements)diff --git a/mineru/utils/office_rich_text.py b/mineru/utils/office_rich_text.pyindex f0567a8a..80e52579 100644--- a/mineru/utils/office_rich_text.py+++ b/mineru/utils/office_rich_text.py@@ -30,6 +30,17 @@ def _style_str(style: str | list[str] | tuple[str, ...] | None) -> Optional[str]return ",".join(styles) if styles else None+def _script_to_style_name(format_obj: Any) -> Optional[str]:+ """把 DOCX 上下标脚本位置转换为 Office 内部富文本样式名。"""+ script = getattr(format_obj, "script", None)+ script_value = getattr(script, "value", script)+ if script_value == "super":+ return "superscript"+ if script_value == "sub":+ return "subscript"+ return None++def formatting_to_style_str(format_obj: Any) -> Optional[str]:"""从 Formatting-like 对象提取 Office 内部富文本样式字符串。"""if format_obj is None:@@ -45,6 +56,9 @@ def formatting_to_style_str(format_obj: Any) -> Optional[str]:styles.append("emphasis")if getattr(format_obj, "strikethrough", False):styles.append("strikethrough")+ script_style = _script_to_style_name(format_obj)+ if script_style:+ styles.append(script_style)return ",".join(styles) if styles else None