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
fix: address latest native parser review findings
myhloli5029886bf470
diff --git a/mineru/model/flash/_shared/mathml.py b/mineru/model/flash/_shared/mathml.pyindex 9aeadeb1..39c88738 100644--- a/mineru/model/flash/_shared/mathml.py+++ b/mineru/model/flash/_shared/mathml.py@@ -59,6 +59,18 @@ _GREEK_MAP = {"Ω": r"\Omega ",}_LATEX_ESCAPE_RE = re.compile(r"([#$%&_{}])")+_LATEX_MATH_TOKEN_ESCAPES = {+ "\\": r"\backslash{}",+ "#": r"\#",+ "$": r"\$",+ "%": r"\%",+ "&": r"\&",+ "_": r"\_",+ "^": r"\^{}",+ "{": r"\{",+ "}": r"\}",+ "~": r"\~{}",+}def _local_name(element: etree._Element) -> str:@@ -71,6 +83,11 @@ def _escape_text(value: str) -> str:return _LATEX_ESCAPE_RE.sub(r"\\\1", value)+def _escape_math_token(value: str) -> str:+ """转义 MathML 标识符中的 TeX 控制字符,避免字面文本改变公式结构。"""+ return "".join(_LATEX_MATH_TOKEN_ESCAPES.get(char, char) for char in value)++def _children(element: etree._Element) -> list[etree._Element]:"""返回当前元素的全部普通 XML 子元素。"""return [child for child in element if isinstance(child.tag, str)]@@ -93,7 +110,7 @@ def _convert(element: etree._Element) -> str:if name in {"math", "mrow", "mstyle", "mpadded", "mphantom"}:return _join_children(element)if name in {"mi", "mn"}:- return _GREEK_MAP.get(text, text)+ return _GREEK_MAP.get(text, _escape_math_token(text))if name == "mo":return _OPERATOR_MAP.get(text, text)if name == "mtext":diff --git a/mineru/model/flash/epub/styles.py b/mineru/model/flash/epub/styles.pyindex 1c18debb..f1555aaf 100644--- a/mineru/model/flash/epub/styles.py+++ b/mineru/model/flash/epub/styles.py@@ -10,6 +10,7 @@ from lxml import etree # type: ignore[reportMissingImports]_CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)+_CSS_IMPORTANT_RE = re.compile(r"!\s*important\s*$", re.IGNORECASE)_TEXT_STYLE_FIELDS = ("bold", "italic", "underline", "strikethrough", "superscript", "subscript")@@ -101,17 +102,27 @@ class _SelectorCascade:"""按 selector 聚合各属性最后一次声明及其源码顺序。"""priority: int- declarations: dict[str, tuple[int, bool]] = field(default_factory=dict)- hidden: tuple[int, bool] | None = None+ declarations: dict[str, tuple[bool, int, bool]] = field(default_factory=dict)+ hidden: tuple[bool, int, bool] | None = None- def update(self, style: TextStyleDelta, hidden: bool | None, order: int) -> None:- """用同 selector 的较新声明更新逐属性级联结果。"""- for name in _TEXT_STYLE_FIELDS:- value = getattr(style, name)- if value is not None:- self.declarations[name] = (order, value)- if hidden is not None:- self.hidden = (order, hidden)+ def update(self, parsed: _ParsedDeclarations, order: int) -> None:+ """按 importance 和源码顺序更新同 selector 的逐属性级联结果。"""+ for name, (important, value) in parsed.text.items():+ current = self.declarations.get(name)+ if current is None or (important, order) >= current[:2]:+ self.declarations[name] = (important, order, value)+ if parsed.hidden is not None:+ important, value = parsed.hidden+ if self.hidden is None or (important, order) >= self.hidden[:2]:+ self.hidden = (important, order, value)+++@dataclass(frozen=True, slots=True)+class _ParsedDeclarations:+ """保存已投影 CSS 属性的 importance 与布尔值。"""++ text: dict[str, tuple[bool, bool]]+ hidden: tuple[bool, bool] | None = Nonedef _local_name(element: etree._Element) -> str:@@ -127,40 +138,50 @@ def _numeric_font_weight(value: str) -> int | None:return weight if 1 <= weight <= 1_000 else None-def _parse_declarations(value: str) -> tuple[TextStyleDelta, bool | None]:- """从声明串提取字体语义和 display/visibility 隐藏状态。"""- bold = italic = underline = strikethrough = superscript = subscript = None- hidden: bool | None = None+def _parse_declarations(value: str) -> _ParsedDeclarations:+ """从声明串逐属性提取字体语义、隐藏状态和 important 优先级。"""+ text: dict[str, tuple[bool, bool]] = {}+ hidden: tuple[bool, bool] | None = Nonefor raw_declaration in value.split(";"):if ":" not in raw_declaration:continuename, raw_value = raw_declaration.split(":", 1)name = name.strip().casefold()- normalized = raw_value.split("!important", 1)[0].strip().casefold()+ important_match = _CSS_IMPORTANT_RE.search(raw_value)+ important = important_match is not None+ normalized = raw_value[: important_match.start() if important_match is not None else None].strip().casefold()+ text_updates: dict[str, bool] = {}+ hidden_update: bool | None = Noneif name == "font-weight":if normalized in {"bold", "bolder"}:- bold = True+ text_updates["bold"] = Trueelif normalized in {"normal", "lighter"}:- bold = False+ text_updates["bold"] = Falseelif (weight := _numeric_font_weight(normalized)) is not None:- bold = weight >= 600+ text_updates["bold"] = weight >= 600elif name == "font-style":- italic = normalized in {"italic", "oblique"}+ text_updates["italic"] = normalized in {"italic", "oblique"}elif name in {"text-decoration", "text-decoration-line"}:if normalized == "none":- underline = False- strikethrough = False+ text_updates["underline"] = False+ text_updates["strikethrough"] = Falseelse:- underline = "underline" in normalized- strikethrough = "line-through" in normalized+ text_updates["underline"] = "underline" in normalized+ text_updates["strikethrough"] = "line-through" in normalizedelif name == "vertical-align":- superscript = normalized in {"super", "text-top"}- subscript = normalized in {"sub", "text-bottom"}+ text_updates["superscript"] = normalized in {"super", "text-top"}+ text_updates["subscript"] = normalized in {"sub", "text-bottom"}elif name == "display":- hidden = normalized == "none"+ hidden_update = normalized == "none"elif name == "visibility":- hidden = normalized in {"hidden", "collapse"}- return TextStyleDelta(bold, italic, underline, strikethrough, superscript, subscript), hidden+ hidden_update = normalized in {"hidden", "collapse"}+ for field_name, field_value in text_updates.items():+ current = text.get(field_name)+ if current is None or important or not current[0]:+ text[field_name] = (important, field_value)+ if hidden_update is not None and (hidden is None or important or not hidden[0]):+ hidden = (important, hidden_update)+ return _ParsedDeclarations(text=text, hidden=hidden)class EpubStylesheet:@@ -189,8 +210,8 @@ class EpubStylesheet:if "{" not in chunk:continueselectors, declarations = chunk.split("{", 1)- style, hidden = _parse_declarations(declarations)- if style.is_empty() and hidden is None:+ parsed_declarations = _parse_declarations(declarations)+ if not parsed_declarations.text and parsed_declarations.hidden is None:continuefor selector in selectors.split(","):parsed = self._parse_selector(selector)@@ -198,7 +219,7 @@ class EpubStylesheet:continuetag, class_name, priority = parsedcascade = self._selector_cascade(tag, class_name, priority)- cascade.update(style, hidden, self._source_order)+ cascade.update(parsed_declarations, self._source_order)self._source_order += 1@staticmethod@@ -237,30 +258,33 @@ class EpubStylesheet:if cascade := self._tag_class_cascades.get((tag, class_name)):matching.append(cascade)+ inline = _parse_declarations(element.get("style") or "")resolved_values: dict[str, bool] = {}for name in _TEXT_STYLE_FIELDS:candidates = [- (cascade.priority, order, value)+ (important, cascade.priority, order, value)for cascade in matchingif (declaration := cascade.declarations.get(name)) is not None- for order, value in (declaration,)+ for important, order, value in (declaration,)]+ if (inline_declaration := inline.text.get(name)) is not None:+ important, value = inline_declaration+ candidates.append((important, 1_000, self._source_order, value))if candidates:- resolved_values[name] = max(candidates, key=lambda item: (item[0], item[1]))[2]+ resolved_values[name] = max(candidates, key=lambda item: item[:3])[3]style = TextStyleDelta(**resolved_values).apply(style)hidden_candidates = [- (cascade.priority, order, value)+ (important, cascade.priority, order, value)for cascade in matchingif cascade.hidden is not None- for order, value in (cascade.hidden,)+ for important, order, value in (cascade.hidden,)]+ if inline.hidden is not None:+ important, value = inline.hidden+ hidden_candidates.append((important, 1_000, self._source_order, value))if hidden_candidates:- hidden = max(hidden_candidates, key=lambda item: (item[0], item[1]))[2]- inline_style, inline_hidden = _parse_declarations(element.get("style") or "")- style = inline_style.apply(style)- if inline_hidden is not None:- hidden = inline_hidden+ hidden = max(hidden_candidates, key=lambda item: item[:3])[3]return ElementStyle(style, hidden)diff --git a/mineru/model/flash/office/odf/styles.py b/mineru/model/flash/office/odf/styles.pyindex 8ea914ae..37d16e9d 100644--- a/mineru/model/flash/office/odf/styles.py+++ b/mineru/model/flash/office/odf/styles.py@@ -233,13 +233,25 @@ class OdfStyles:return Nonedef is_document_title(self, style_name: str | None) -> bool:- """根据样式名称和 display-name 判断段落是否为文档标题。"""+ """沿段落父样式,根据名称和 display-name 判断是否继承文档标题语义。"""if not style_name:return False- definition = self._styles.get(("paragraph", style_name))- names = {style_name, definition.display_name if definition is not None else ""}- normalized = {name.replace("_20_", " ").replace("_", " ").strip().casefold() for name in names if name}- return bool(normalized & {"title", "document title", "标题"})+ seen: set[str] = set()+ current = style_name+ while current:+ if current in seen:+ logger.warning("ODF style inheritance cycle detected: family=paragraph, style={}", current)+ break+ seen.add(current)+ definition = self._styles.get(("paragraph", current))+ names = {current, definition.display_name if definition is not None else ""}+ normalized = {name.replace("_20_", " ").replace("_", " ").strip().casefold() for name in names if name}+ if normalized & {"title", "document title", "标题"}:+ return True+ if definition is None:+ break+ current = definition.parent or ""+ return Falsedef list_level(self, style_name: str | None, depth: int) -> ListLevel:"""返回指定列表深度的定义,不存在时使用无序默认值。"""diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.pyindex 76c832a1..61d2ea9c 100644--- a/mineru/model/flash/office/odf/text.py+++ b/mineru/model/flash/office/odf/text.py@@ -40,6 +40,7 @@ from .table import OdfTableExpansionBudget, parse_table_grid, table_grid_to_html_WHITESPACE_RE = re.compile(r"[\t\r\n ]+")+_MAX_EXPLICIT_SPACE_COUNT = 10_000@dataclass(slots=True)@@ -288,7 +289,7 @@ class OdfBlockParser:atoms=atoms,)elif child.tag == qname("text", "s"):- count = min(_positive_space_count(child.get(qname("text", "c"))), 10_000)+ count = _positive_space_count(child.get(qname("text", "c")))self._text_expansion_budget.charge(count)self._append_text_atom(atoms,@@ -782,6 +783,8 @@ class OdfBlockParser:load_preview()if preview_uri:return InlineImage(preview_uri, preview_alt), [{"type": BlockType.IMAGE, "image_base64": preview_uri}]+ if preview_alt:+ return InlineText(preview_alt), []return None, []def parse_frame_blocks(self, frame: etree._Element) -> list[dict[str, Any]]:@@ -793,6 +796,9 @@ class OdfBlockParser:return [{"type": BlockType.EQUATION, "content": inline.latex}]if isinstance(inline, InlineImage):return [{"type": BlockType.IMAGE, "image_base64": inline.data_uri}]+ if isinstance(inline, InlineText):+ content = render_atoms_to_model([inline], trim_edges=True)+ return [{"type": BlockType.TEXT, "content": content}] if content else []return []def parse_element(self, element: etree._Element) -> list[dict[str, Any]]:@@ -951,11 +957,19 @@ class OdfBlockParser:def _positive_space_count(value: str | None) -> int:- """把 text:s 的重复空格数解析为至少一。"""- try:- return max(1, int(value or 1))- except ValueError:+ """在整数转换前校验并限制 text:s 重复空格数,非法值按一处理。"""+ normalized = (value or "").strip()+ if normalized.startswith("+"):+ normalized = normalized[1:]+ if not normalized or not normalized.isascii() or not normalized.isdigit():return 1+ significant = normalized.lstrip("0")+ if not significant:+ return 1+ max_digits = len(str(_MAX_EXPLICIT_SPACE_COUNT))+ if len(significant) > max_digits:+ return _MAX_EXPLICIT_SPACE_COUNT+ return min(max(1, int(significant)), _MAX_EXPLICIT_SPACE_COUNT)def flatten_block_text(blocks: list[dict[str, Any]]) -> str:diff --git a/mineru/model/flash/office/rtf/parser.py b/mineru/model/flash/office/rtf/parser.pyindex 5f1ba064..a066f99f 100644--- a/mineru/model/flash/office/rtf/parser.py+++ b/mineru/model/flash/office/rtf/parser.py@@ -470,10 +470,21 @@ def _named_groups(data: bytes, destination: str) -> list[_GroupSpan]:def _decode_group_text(data: bytes, encoding: str) -> str:"""解码定义表或 metadata group 中的可见文本,不解释正文结构。"""parts: list[str] = []+ byte_buffer = bytearray()uc_skip = 1fallback_skip = 0pending_high: int | None = None++ def flush_byte_buffer() -> None:+ """按当前代码页整体解码连续字节,保留多字节字符边界。"""+ if not byte_buffer:+ return+ parts.append(bytes(byte_buffer).decode(encoding, errors="replace"))+ byte_buffer.clear()+for token in RtfLexer(data):+ if not isinstance(token, (RtfHexByte, RtfTextBytes)):+ flush_byte_buffer()if isinstance(token, RtfControlWord):if token.name == "uc":uc_skip = max(token.param or 0, 0)@@ -496,7 +507,7 @@ def _decode_group_text(data: bytes, encoding: str) -> str:if fallback_skip:fallback_skip -= 1else:- parts.append(bytes([token.value]).decode(encoding, errors="replace"))+ byte_buffer.append(token.value)elif isinstance(token, RtfTextBytes):raw = token.data.replace(b"\r", b"").replace(b"\n", b"")if fallback_skip:@@ -504,7 +515,7 @@ def _decode_group_text(data: bytes, encoding: str) -> str:raw = raw[skipped:]fallback_skip -= skippedif raw:- parts.append(raw.decode(encoding, errors="replace"))+ byte_buffer.extend(raw)elif isinstance(token, RtfControlSymbol):if token.symbol in {"\\", "{", "}"}:parts.append(token.symbol)@@ -512,6 +523,7 @@ def _decode_group_text(data: bytes, encoding: str) -> str:parts.append("\u00a0")elif token.symbol == "_":parts.append("-")+ flush_byte_buffer()if pending_high is not None:parts.append("\ufffd")return "".join(parts)diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.pyindex d0802f55..bbb2cd6b 100644--- a/tests/unittest/test_flash_epub.py+++ b/tests/unittest/test_flash_epub.py@@ -605,6 +605,28 @@ def test_epub_stylesheet_indexes_repeated_selectors_and_preserves_cascade_order(assert len(stylesheet._class_cascades) == 3+def test_epub_stylesheet_honors_important_before_specificity_and_source_order() -> None:+ """验证 important 声明优先于后续普通规则和普通 inline,并允许 inline important 覆盖。"""+ stylesheet = EpubStylesheet()+ stylesheet.add(+ ".secret { display: none !important; font-weight: bold !important; }.secret { display: block; font-weight: normal; }"+ )++ normal_inline = stylesheet.resolve(+ etree.fromstring(b'<span class="secret" style="display: block; font-weight: normal"/>'),+ TextStyle(),+ )+ important_inline = stylesheet.resolve(+ etree.fromstring(b'<span class="secret" style="display: block !important; font-weight: normal !important"/>'),+ TextStyle(),+ )++ assert normal_inline.hidden is True+ assert normal_inline.text.bold is True+ assert important_inline.hidden is False+ assert important_inline.text.bold is False++def test_epub_stylesheet_rejects_overlong_numeric_font_weight_before_int() -> None:"""验证超长或越界数字字重作为无效声明忽略且不会覆盖继承样式。"""stylesheet = EpubStylesheet()diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.pyindex c36ac7b3..7b69c1a2 100644--- a/tests/unittest/test_flash_odf.py+++ b/tests/unittest/test_flash_odf.py@@ -116,6 +116,27 @@ def test_odt_promotes_numbered_heading_inside_list() -> None:assert middle.pages[0].blocks[0].content == "1 Chapter" # type: ignore[union-attr]+def test_odt_inherits_document_title_semantics_from_parent_style() -> None:+ """验证自定义段落样式沿 parent-style-name 继承标准文档标题语义。"""+ content = """<office:document-content+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">+ <office:body><office:text><text:p text:style-name="CustomTitle">Inherited title</text:p></office:text></office:body>+</office:document-content>"""+ styles = """<office:document-styles+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"+ xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0">+ <office:styles>+ <style:style style:name="Title" style:display-name="Title" style:family="paragraph"/>+ <style:style style:name="CustomTitle" style:family="paragraph" style:parent-style-name="Title"/>+ </office:styles>+</office:document-styles>"""++ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles)))++ assert pages == [[{"type": BlockType.DOC_TITLE, "level": 1, "content": "Inherited title"}]]++def test_odt_preserves_explicit_space_count() -> None:"""验证 text:s 的显式重复空格不会被普通 XML 空白规则折叠。"""content = """<office:document-content@@ -129,6 +150,13 @@ def test_odt_preserves_explicit_space_count() -> None:assert pages == [[{"type": BlockType.TEXT, "content": "A B"}]]+def test_odt_bounds_overlong_explicit_space_count_before_integer_conversion() -> None:+ """验证超长 text:c 在整数转换前按单节点上限截断,不依赖解释器数字保护。"""+ assert odf_text_module._positive_space_count("9" * 100_000) == 10_000+ assert odf_text_module._positive_space_count("+0004") == 4+ assert odf_text_module._positive_space_count("-4") == 1++def test_odt_explicit_space_expansion_uses_document_budget(monkeypatch: pytest.MonkeyPatch) -> None:"""验证多个 text:s 共享文档级预算,并在超限分配前稳定失败。"""monkeypatch.setattr(odf_text_module, "MAX_EXPANSION_TEXT_BYTES", 5)@@ -943,6 +971,45 @@ def test_odf_inline_image_alt_escapes_literal_hyperlink_protocol() -> None:assert "javascript:alert(1)" not in relationships+ ("href", "extra_parts"),+ [+ ("Pictures/missing.png", None),+ ("https://example.com/external.png", None),+ ("Pictures/corrupt.png", {"Pictures/corrupt.png": b"not-an-image"}),+ ],+)+def test_odf_unavailable_image_preserves_safe_alt_text(+ href: str,+ extra_parts: dict[str, bytes] | None,+) -> None:+ """验证缺失、外部或损坏图片无法物化时仍以安全文本保留 title/desc 语义。"""+ literal = "<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>"+ content = f"""<office:document-content+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"+ xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"+ xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"+ xmlns:xlink="http://www.w3.org/1999/xlink">+ <office:body><office:text><draw:frame><draw:image xlink:href="{href}"/>+ <svg:title>{literal}</svg:title><svg:desc>semantic description</svg:desc>+ </draw:frame></office:text></office:body>+</office:document-content>"""++ middle, model = doc_analyze(+ build_odf_package("odt", content, extra_parts=extra_parts),+ file_suffix="odt",+ )+ raw_content = model.pages[0][0]["content"]+ markdown = render_markdown(middle)++ assert model.pages[0][0]["type"] == BlockType.TEXT+ assert "<hyperlink>" in raw_content+ assert "<hyperlink>" not in raw_content+ assert "semantic description" in raw_content+ assert "](javascript:" not in markdown++def test_odf_annotation_emits_page_footnote_without_metadata_in_body() -> None:"""验证标准 annotation 正文作为页脚注保留,作者日期不拼入周围正文。"""content = """<office:document-contentdiff --git a/tests/unittest/test_flash_rtf.py b/tests/unittest/test_flash_rtf.pyindex 15ee0665..7ee778ed 100644--- a/tests/unittest/test_flash_rtf.py+++ b/tests/unittest/test_flash_rtf.py@@ -105,6 +105,24 @@ def test_rtf_font_codepages_and_unicode_surrogates_are_exact() -> None:assert pages == [[{"type": BlockType.TEXT, "content": "Привет こんにちは 😀"}]]+def test_rtf_metadata_decodes_consecutive_multibyte_hex_as_one_run() -> None:+ """验证 metadata 定义组中的连续 GB18030 hex byte 按完整代码页序列解码。"""+ encoded_title = b"".join(f"\\'{value:02x}".encode("ascii") for value in "中文".encode("gb18030"))+ source = b"".join(+ [+ rb"{\rtf1\ansi\ansicpg936{\info{\title ",+ encoded_title,+ rb"}}Body\par}",+ ]+ )++ metadata = extract_rtf_metadata(BytesIO(source))+ pages = RtfModel().predict(BytesIO(source))++ assert metadata["title"] == "中文"+ assert pages == [[{"type": BlockType.TEXT, "content": "Body"}]]++def test_rtf_unicode_controls_buffer_adjacent_text_without_repeated_run_copy() -> None:"""验证逐字符 Unicode control 只在边界处物化文本 run。"""count = 5_000diff --git a/tests/unittest/test_flash_shared_helpers.py b/tests/unittest/test_flash_shared_helpers.pyindex 0f501c2c..132c0992 100644--- a/tests/unittest/test_flash_shared_helpers.py+++ b/tests/unittest/test_flash_shared_helpers.py@@ -61,6 +61,23 @@ def test_mathml_semantics_ignores_non_tex_alternate_annotations() -> None:assert mathml_to_latex(math) == r"\frac{x}{2}"+ ("token", "value", "expected"),+ [+ ("mi", "a_b", r"a\_b"),+ ("mi", r"\name{x}", r"\backslash{}name\{x\}"),+ ("mn", "12_3", r"12\_3"),+ ("mi", "x^~", r"x\^{}\~{}"),+ ("mi", "α", r"\alpha"),+ ],+)+def test_mathml_literal_identifier_tokens_do_not_become_latex_syntax(token: str, value: str, expected: str) -> None:+ """验证标识符和数字字面量转义 TeX 控制字符,同时保留显式希腊字母映射。"""+ math = etree.fromstring(f'<math xmlns="http://www.w3.org/1998/Math/MathML"><{token}>{value}</{token}></math>'.encode())++ assert mathml_to_latex(math) == expected++@pytest.mark.parametrize("extra_node", ["<!--producer note-->", "<?producer note?>"])def test_mathml_annotation_scan_skips_non_element_nodes(extra_node: str) -> None:"""验证 TeX annotation 扫描跳过 XML comment 与处理指令。"""