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: bound OFD glyph mapping and DOCX equation offsets
myhloli2ce0ad042dcf
diff --git a/mineru/model/flash/ofd/text.py b/mineru/model/flash/ofd/text.pyindex c01ff637..66267c2c 100644--- a/mineru/model/flash/ofd/text.py+++ b/mineru/model/flash/ofd/text.py@@ -42,6 +42,7 @@ class OfdTextBudget:text_bytes: int = 0glyph_count: int = 0+ glyph_mapping_count: int = 0def charge(self, text: str) -> None:"""为一次 TextCode 展开计费。"""@@ -52,6 +53,12 @@ class OfdTextBudget:if self.glyph_count > MAX_EXPANDED_GLYPHS:raise OfdResourceLimitError(f"OFD resource limit exceeded: max_expanded_glyphs={MAX_EXPANDED_GLYPHS}")+ def charge_glyph_mapping(self, count: int) -> None:+ """累计 CGTransform 的有效字符映射数量并限制全文展开量。"""+ self.glyph_mapping_count += count+ if self.glyph_mapping_count > MAX_EXPANDED_GLYPHS:+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_expanded_glyphs={MAX_EXPANDED_GLYPHS}")+@dataclass(slots=True)class _LoadedFont:@@ -215,8 +222,8 @@ def parse_delta(value: str | None, count: int) -> list[float]:return output[:count]-def _glyph_map(text_object: etree._Element) -> dict[int, int]:- """把 TextObject 全局字符位置映射到首个绘制 glyph ID。"""+def _glyph_map(text_object: etree._Element, position_count: int, budget: OfdTextBudget) -> dict[int, int]:+ """把实际 TextCode 字符位置映射到 glyph ID,并限制累计展开量。"""result: dict[int, int] = {}for element in text_object:if local_name(element.tag) != "CGTransform":@@ -230,7 +237,11 @@ def _glyph_map(text_object: etree._Element) -> dict[int, int]:valid_glyph_ids = [item for item in glyph_ids if item is not None]if not valid_glyph_ids:continue- for offset in range(code_count):+ effective_count = min(code_count, max(0, position_count - code_position))+ if effective_count <= 0:+ continue+ budget.charge_glyph_mapping(effective_count)+ for offset in range(effective_count):glyph_index = min(offset, len(valid_glyph_ids) - 1)result[code_position + offset] = valid_glyph_ids[glyph_index]return result@@ -310,17 +321,23 @@ def build_text_lines(except ValueError:size, hscale = 1.0, 1.0styles = _styles(text_object, font, style)- glyph_by_position = _glyph_map(text_object)+ decoded_text_codes: list[tuple[etree._Element, str]] = []+ position_count = 0+ for text_code in (element for element in text_object if local_name(element.tag) == "TextCode"):+ text = decode_text_code("".join(text_code.itertext()))+ decoded_text_codes.append((text_code, text))+ if text:+ budget.charge(text)+ position_count += len(text)+ glyph_by_position = _glyph_map(text_object, position_count, budget)global_position = 0inherited_x: float | None = Noneinherited_y: float | None = Nonelines: list[TextLine] = []object_id = parse_int(text_object.get("ID"))- for code_index, text_code in enumerate(element for element in text_object if local_name(element.tag) == "TextCode"):- text = decode_text_code("".join(text_code.itertext()))+ for code_index, (text_code, text) in enumerate(decoded_text_codes):if not text:continue- budget.charge(text)try:if text_code.get("X") is not None:inherited_x = float(text_code.get("X") or "")diff --git a/mineru/model/flash/office/docx/docx_converter.py b/mineru/model/flash/office/docx/docx_converter.pyindex 8e70fa36..1911138b 100644--- a/mineru/model/flash/office/docx/docx_converter.py+++ b/mineru/model/flash/office/docx/docx_converter.py@@ -311,6 +311,7 @@ class DocxConverter:if tag_name is None:return []tag = str(getattr(element, "tag", ""))+ word_namespace = DocxConverter._BLIP_NAMESPACES["w"]if tag_name == "AlternateContent":branch_tokens = [@@ -351,6 +352,15 @@ class DocxConverter:if tag_name == "t" and "officeDocument/2006/math" not in tag:return [("text", element.text)] if isinstance(element.text, str) else []+ if tag in {f"{{{word_namespace}}}tab", f"{{{word_namespace}}}ptab"}:+ return [("text", "\t")]+ if tag == f"{{{word_namespace}}}cr":+ return [("text", "\n")]+ if tag == f"{{{word_namespace}}}br":+ break_type = element.get(f"{{{word_namespace}}}type")+ return [("text", "\n")] if break_type in {None, "textWrapping"} else []+ if tag == f"{{{word_namespace}}}noBreakHyphen":+ return [("text", "-")]tokens: list[tuple[str, str]] = []for child in element:@@ -683,7 +693,7 @@ class DocxConverter:styled_spans = self._build_text_from_elements(paragraph_elements)styled_visible = inline_span_plain_text(styled_spans)plain_visible = "".join(value for kind, value in equations if kind == "text")- if re.sub(r"\s+", "", plain_visible) != re.sub(r"\s+", "", styled_visible):+ if plain_visible != styled_visible:return styled_spansoutput: list[dict[str, Any]] = []@@ -2077,7 +2087,7 @@ class DocxConverter:if not formula_values:return text, []- if re.sub(r"\s+", "", "".join(only_texts)).strip() != re.sub(r"\s+", "", text).strip():+ if "".join(only_texts) != text:# 如果我们无法重构初始原始文本# 不要尝试解析公式并返回原始文本return text, []diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.pyindex ddd31e0a..5c879299 100644--- a/tests/unittest/test_flash_ofd.py+++ b/tests/unittest/test_flash_ofd.py@@ -21,7 +21,7 @@ from mineru.errors import InvalidRequestErrorfrom mineru.model.flash import OfdModelfrom mineru.model.flash.ofd import OfdParseError, OfdResourceLimitError, detect_ofdfrom mineru.model.flash.ofd import images as ofd_images-from mineru.model.flash.ofd.constants import MAX_DRAW_PARAM_INHERITANCE+from mineru.model.flash.ofd.constants import MAX_DRAW_PARAM_INHERITANCE, MAX_EXPANDED_GLYPHSfrom mineru.model.flash.ofd.geometry import Affine, canonical_anglefrom mineru.model.flash.ofd.images import build_image_itemfrom mineru.model.flash.ofd.models import MediaResource, OfdPageScene, ResourceRegistry@@ -185,6 +185,54 @@ def test_ofd_textcode_preserves_boundary_whitespace_and_glyph_positions() -> Nonassert [glyph.origin[0] for glyph in lines[0].glyphs] == pytest.approx([11.0, 16.0, 23.0])+def test_ofd_cgtransform_expands_only_actual_text_positions() -> None:+ """验证超大 CodeCount 只映射 TextCode 实际存在的字符位置。"""+ text_element = etree.fromstring(+ b'<TextObject ID="10" Boundary="0 0 10 10" Font="1" Size="5">'+ b'<TextCode X="1" Y="5">A</TextCode>'+ b'<CGTransform CodePosition="0" CodeCount="1000000000"><Glyphs>42</Glyphs></CGTransform>'+ b"</TextObject>"+ )+ package_buffer = BytesIO()+ with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:+ archive.writestr("OFD.xml", "<OFD/>")+ package = OfdPackage(package_buffer.getvalue())+ budget = OfdTextBudget()++ lines = build_text_lines(+ text_element,+ parent_transform=Affine(),+ parent_clip=(0.0, 0.0, 100.0, 100.0),+ resources=ResourceRegistry(),+ package=package,+ font_metrics=FontMetricResolver(package),+ budget=budget,+ paint_order=0,+ layer_type="body",+ template_id=None,+ )++ assert budget.glyph_count == 1+ assert budget.glyph_mapping_count == 1+ assert len(lines) == 1+ assert [glyph.glyph_id for glyph in lines[0].glyphs] == [42]++ exhausted_budget = OfdTextBudget(glyph_mapping_count=MAX_EXPANDED_GLYPHS)+ with pytest.raises(OfdResourceLimitError, match="max_expanded_glyphs"):+ build_text_lines(+ text_element,+ parent_transform=Affine(),+ parent_clip=(0.0, 0.0, 100.0, 100.0),+ resources=ResourceRegistry(),+ package=package,+ font_metrics=FontMetricResolver(package),+ budget=exhausted_budget,+ paint_order=0,+ layer_type="body",+ template_id=None,+ )++def test_ofd_textcode_discards_glyphs_outside_object_boundary() -> None:"""验证 TextObject Boundary 会裁掉完整位于边界外的字符和空行。"""package_buffer = BytesIO()diff --git a/tests/unittest/test_flash_ooxml_mtef.py b/tests/unittest/test_flash_ooxml_mtef.pyindex 7feaf872..f752b848 100644--- a/tests/unittest/test_flash_ooxml_mtef.py+++ b/tests/unittest/test_flash_ooxml_mtef.py@@ -6,6 +6,9 @@ from io import BytesIOfrom pathlib import Pathfrom typing import Any+from docx import Document+from docx.enum.text import WD_BREAK+from docx.oxml import parse_xmlimport pytestfrom mineru.backend.analyze import aio_doc_analyze, doc_analyze@@ -125,6 +128,43 @@ def test_docx_mtef_flows_inline_table_header_footer_and_omml_precedence() -> Nonassert textbox == [[{"type": BlockType.EQUATION, "content": "x+y"}]][email protected](("separator", "break_type"), [("\t", None), ("\n", WD_BREAK.LINE)])+def test_docx_equation_tokens_preserve_run_whitespace_offsets(separator: str, break_type: WD_BREAK | None) -> None:+ """验证公式旁的 tab 和软换行参与样式 Span 的精确偏移。"""+ document = Document()+ paragraph = document.add_paragraph()+ first = paragraph.add_run("A")+ first.bold = True+ if break_type is None:+ first.add_tab()+ else:+ first.add_break(break_type)+ paragraph._p.append(+ parse_xml(+ '<m:oMath xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><m:r><m:t>x</m:t></m:r></m:oMath>'+ )+ )+ last = paragraph.add_run("B")+ last.italic = True+ output = BytesIO()+ document.save(output)++ pages = DocxModel().predict(BytesIO(output.getvalue()))++ assert pages == [+ [+ {+ "type": BlockType.TEXT,+ "content": [+ *text_spans(f"A{separator}", styles=["bold"]),+ equation("x"),+ *text_spans("B", styles=["italic"]),+ ],+ }+ ]+ ]++def test_omml_precedes_mtef_and_preview_for_the_same_ooxml_object() -> None:"""验证三种 OOXML 兼容对象只输出 OMML 分支且不重复预览。"""