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: harden document fallback and inline semantics
myhloli5ea00d222d5a
diff --git a/mineru/model/flash/_shared/mathml.py b/mineru/model/flash/_shared/mathml.pyindex 77c079da..3337434a 100644--- a/mineru/model/flash/_shared/mathml.py+++ b/mineru/model/flash/_shared/mathml.py@@ -86,7 +86,11 @@ def _convert(element: etree._Element) -> str:name = _local_name(element)children = _children(element)text = (element.text or "").strip()- if name in {"math", "mrow", "mstyle", "mpadded", "mphantom", "semantics"}:+ if name == "semantics":+ if not children or _local_name(children[0]) in {"annotation", "annotation-xml"}:+ return ""+ return _convert(children[0])+ if name in {"math", "mrow", "mstyle", "mpadded", "mphantom"}:return _join_children(element)if name in {"mi", "mn"}:return _GREEK_MAP.get(text, text)diff --git a/mineru/model/flash/epub/package.py b/mineru/model/flash/epub/package.pyindex 334c7d5c..2c07270a 100644--- a/mineru/model/flash/epub/package.py+++ b/mineru/model/flash/epub/package.py@@ -417,7 +417,7 @@ class EpubPackage:item = self.manifest.get(current_id)if item is None:return None- if item.media_type in XHTML_MEDIA_TYPES or item.media_type == SVG_MEDIA_TYPE:+ if item.path and (item.media_type in XHTML_MEDIA_TYPES or item.media_type == SVG_MEDIA_TYPE):return itemcurrent_id = item.fallbackreturn Nonediff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.pyindex 34f301e8..ef887bfb 100644--- a/mineru/model/flash/office/odf/text.py+++ b/mineru/model/flash/office/odf/text.py@@ -990,7 +990,8 @@ def flatten_block_text(blocks: list[dict[str, Any]]) -> str:visible = re.sub(r"<url>.*?</url>", "", content, flags=re.DOTALL)visible = re.sub(r"<[^>]+>", "", visible)if visible.strip():- parts.append(html.unescape(visible).strip())+ decoded = html.unescape(visible).strip()+ parts.append(decoded.replace("<", "<").replace(">", ">"))elif isinstance(content, list):children = [child for child in content if isinstance(child, dict)]nested = flatten_block_text(children)diff --git a/mineru/model/flash/office/rtf/converter.py b/mineru/model/flash/office/rtf/converter.pyindex 3e489ef7..c4897752 100644--- a/mineru/model/flash/office/rtf/converter.py+++ b/mineru/model/flash/office/rtf/converter.py@@ -318,7 +318,8 @@ class RtfConverter:if not isinstance(inline, (RtfInlineEquation, RtfLineBreak, RtfNoteReference))and (not isinstance(inline, RtfTextRun) or bool(inline.text.strip()))]- if equations and not ordinary:+ has_note_reference = any(isinstance(inline, RtfNoteReference) for inline in non_image)+ if equations and not ordinary and not has_note_reference:return [{"type": BlockType.EQUATION, "content": equation.latex} for equation in equations]blocks: list[dict[str, Any]] = []@@ -690,7 +691,7 @@ class RtfConverter:)for note in ordered:number = self._note_numbers.get(note.id)- content = self._blocks_plain_text(note.blocks).strip()+ content = escape(self._blocks_plain_text(note.blocks).strip(), quote=False)if number is None or not content:continueresult.append(diff --git a/tests/unittest/_epub_test_utils.py b/tests/unittest/_epub_test_utils.pyindex 25664a9c..86e14b4c 100644--- a/tests/unittest/_epub_test_utils.py+++ b/tests/unittest/_epub_test_utils.py@@ -17,6 +17,7 @@ def build_epub_fixture(omit_mimetype: bool = False,unsafe_member: str | None = None,use_foreign_fallback: bool = False,+ use_missing_supported_fallback: bool = False,include_nav: bool = True,include_ncx: bool = True,corrupt_nav: bool = False,@@ -61,6 +62,12 @@ def build_epub_fixture('<item id="c2" href="missing.bin" media-type="application/octet-stream" fallback="c2-fallback"/>''<item id="c2-fallback" href="text/ch2.xhtml" media-type="application/xhtml+xml"/>',)+ if use_missing_supported_fallback:+ opf = opf.replace(+ '<item id="c2" href="text/ch2.xhtml" media-type="application/xhtml+xml"/>',+ '<item id="c2" href="missing.xhtml" media-type="application/xhtml+xml" fallback="c2-fallback"/>'+ '<item id="c2-fallback" href="text/ch2.xhtml" media-type="application/xhtml+xml"/>',+ )chapter_one = """<?xml version="1.0" encoding="UTF-8"?><html xmlns="http://www.w3.org/1999/xhtml"><head><link rel="stylesheet" href="../styles/book.css"/>diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.pyindex 881f9392..abb54079 100644--- a/tests/unittest/test_flash_epub.py+++ b/tests/unittest/test_flash_epub.py@@ -391,6 +391,12 @@ def test_epub_spine_foreign_resource_uses_xhtml_fallback_chain() -> None:assert middle.pages[1].blocks[0].content == "Section Two" # type: ignore[union-attr]+def test_epub_spine_missing_supported_resource_uses_xhtml_fallback_chain() -> None:+ """验证缺失的 XHTML 主资源不会阻断可用 fallback 链。"""+ middle, _ = doc_analyze(build_epub_fixture(use_missing_supported_fallback=True), file_suffix="epub")+ assert middle.pages[1].blocks[0].content == "Section Two" # type: ignore[union-attr]++def test_epub_nav_and_ncx_outside_spine_do_not_create_synthetic_page() -> None:"""验证 spine 外的损坏 nav 与有效 NCX 都不会生成合成目录页。"""middle, _ = doc_analyze(build_epub_fixture(corrupt_nav=True), file_suffix="epub")diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.pyindex 4f0d0a17..028bc54d 100644--- a/tests/unittest/test_flash_odf.py+++ b/tests/unittest/test_flash_odf.py@@ -601,6 +601,47 @@ def test_odf_malformed_image_and_object_references_degrade_locally() -> None:assert pages == [[{"type": BlockType.TEXT, "content": "visible"}]]+def test_odf_flattened_titles_and_notes_keep_literal_protocol_escaped() -> None:+ """验证标题、演讲者备注和行内脚注压平后不会重建内部协议标签。"""+ literal = "<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>"+ odp_content = f"""<office:document-content+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"+ xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"+ xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">+ <office:body><office:presentation><draw:page draw:name="Slide 1">+ <draw:frame presentation:class="title"><draw:text-box><text:p>{literal}</text:p></draw:text-box></draw:frame>+ <presentation:notes><draw:frame><draw:text-box><text:p>{literal}</text:p></draw:text-box></draw:frame></presentation:notes>+ </draw:page></office:presentation></office:body></office:document-content>"""+ odt_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">+ <office:body><office:text><text:p>Body<text:note><text:note-citation>1</text:note-citation>+ <text:note-body><text:p>{literal}</text:p></text:note-body>+ </text:note></text:p></office:text></office:body></office:document-content>"""++ for suffix, payload in (+ ("odp", build_odf_package("odp", odp_content)),+ ("odt", build_odf_package("odt", odt_content)),+ ):+ middle, model = doc_analyze(payload, file_suffix=suffix) # type: ignore[arg-type]+ flattened = [+ block["content"]+ for page in model.pages+ for block in page+ if block.get("type") in {BlockType.DOC_TITLE, BlockType.PAGE_FOOTNOTE}+ ]+ markdown = render_markdown(middle)+ docx = render_docx(middle)+ with ZipFile(BytesIO(docx)) as package:+ relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")++ assert flattened+ assert all("<hyperlink>" in content and "<hyperlink>" not in content for content in flattened)+ assert "](javascript:alert(1))" not in markdown+ assert "javascript:alert(1)" not in relationships++def test_odf_style_cycle_is_bounded_and_preserves_text() -> None:"""验证循环 parent-style-name 在有限链路内降级,不阻塞正文解析。"""content = """<office:document-contentdiff --git a/tests/unittest/test_flash_rtf.py b/tests/unittest/test_flash_rtf.pyindex a9273be2..e56069e2 100644--- a/tests/unittest/test_flash_rtf.py+++ b/tests/unittest/test_flash_rtf.py@@ -7,6 +7,7 @@ import sysimport tracemallocfrom pathlib import Pathfrom unittest.mock import patch+from zipfile import ZipFileimport pytest@@ -414,6 +415,40 @@ def test_rtf_literal_inline_protocol_is_escaped_before_rendering() -> None:assert "](javascript:alert(1))" not in markdown+def test_rtf_footnote_literal_protocol_is_escaped_before_rendering() -> None:+ """验证 RTF 脚注压平文本不能注入 equation 或 hyperlink 内部协议。"""+ source = (+ rb"{\rtf1\ansi Body{\footnote <eq>x</eq> and "+ rb"<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>}\par}"+ )++ middle, model = doc_analyze(source, file_suffix="rtf")+ footnote = next(block for block in model.pages[0] if block.get("type") == BlockType.PAGE_FOOTNOTE)+ markdown = render_markdown(middle)+ docx = render_docx(middle)+ with ZipFile(BytesIO(docx)) as package:+ relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")++ assert "<eq>x</eq>" in footnote["content"]+ assert "<hyperlink>" in footnote["content"]+ assert "<eq>" not in footnote["content"]+ assert "<hyperlink>" not in footnote["content"]+ assert "](javascript:alert(1))" not in markdown+ assert "javascript:alert(1)" not in relationships+++def test_rtf_equation_only_paragraph_preserves_note_reference() -> None:+ """验证纯公式段落仍保留脚注引用,不生成孤立脚注正文。"""+ source = rb"{\rtf1\ansi\pard {\mmath{\*\moMath{\mr x}}}{\footnote Foot.}\par}"++ pages = RtfModel().predict(BytesIO(source))++ assert pages[0][0]["type"] == BlockType.TEXT+ assert "<eq>x</eq>" in pages[0][0]["content"]+ assert "[1]" in pages[0][0]["content"]+ assert pages[0][1] == {"type": BlockType.PAGE_FOOTNOTE, "content": "[1] Foot."}++def test_rtf_object_keeps_safe_result_and_suppresses_objdata() -> None:"""验证对象载荷不执行不泄漏,但显式 result 文本仍可恢复。"""pages = RtfModel().predict(BytesIO(rb"{\rtf1 before {\object{\*\objdata 41424344}{\result Visible object}} after\par}"))diff --git a/tests/unittest/test_flash_shared_helpers.py b/tests/unittest/test_flash_shared_helpers.pyindex 1fc370bb..be3e4dd4 100644--- a/tests/unittest/test_flash_shared_helpers.py+++ b/tests/unittest/test_flash_shared_helpers.py@@ -7,8 +7,10 @@ from zipfile import ZIP_DEFLATED, ZipFile, ZipInfofrom PIL import Imageimport pytest+from lxml import etreefrom mineru.model.flash._shared.image import image_to_b64str, image_to_bytes+from mineru.model.flash._shared.mathml import mathml_to_latexfrom mineru.model.flash.office.doc import records as doc_recordsfrom mineru.model.flash.office.legacy.binary import bounded_slice, get_f64, get_i16, get_u16, get_u32from mineru.model.flash.office.opc import relationship_source_base_dir, write_zip_package@@ -42,6 +44,17 @@ def test_shared_image_encoding_preserves_format_and_data_uri(assert decoded.size == (2, 3)+def test_mathml_semantics_ignores_non_tex_alternate_annotations() -> None:+ """验证 semantics 只转换主展示分支,不重复拼接非 TeX annotation。"""+ math = etree.fromstring(+ b'<math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mfrac><mi>x</mi><mn>2</mn></mfrac>'+ b'<annotation-xml encoding="MathML-Content"><apply><divide/><ci>x</ci><cn>2</cn></apply></annotation-xml>'+ b"</semantics></math>"+ )++ assert mathml_to_latex(math) == r"\frac{x}{2}"++def test_legacy_binary_readers_preserve_bounds_and_values() -> None:"""验证旧版 Office 共用读取器只在完整边界内返回小端数值。"""data = struct.pack("<HhId", 0xABCD, -123, 0x1234_5678, 1.25)