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 document and glyph declarations
myhlolia0879fa6b3ef
diff --git a/mineru/model/flash/ofd/constants.py b/mineru/model/flash/ofd/constants.pyindex ca298560..cb12864d 100644--- a/mineru/model/flash/ofd/constants.py+++ b/mineru/model/flash/ofd/constants.py@@ -16,10 +16,12 @@ MAX_TOTAL_BYTES: Final = 512 * 1024 * 1024MAX_ENTRY_COUNT: Final = 100_000MAX_XML_DEPTH: Final = 256MAX_XML_NODES: Final = 2_000_000+MAX_DOCUMENT_COUNT: Final = 10_000MAX_PAGE_COUNT: Final = 10_000MAX_ASSET_TOTAL_BYTES: Final = 128 * 1024 * 1024MAX_EXPANDED_TEXT_BYTES: Final = 64 * 1024 * 1024MAX_EXPANDED_GLYPHS: Final = 2_000_000+MAX_GLYPH_TOKENS: Final = 2_000_000MAX_PATH_COMMANDS: Final = 2_000_000MAX_OBJECT_RECURSION: Final = 64MAX_DRAW_PARAM_INHERITANCE: Final = 64@@ -30,12 +32,14 @@ MM_TO_POINTS: Final = 72.0 / 25.4__all__ = ["MAX_ASSET_TOTAL_BYTES",+ "MAX_DOCUMENT_COUNT","MAX_DRAW_PARAM_INHERITANCE","MAX_ENTRY_BYTES","MAX_ENTRY_COUNT","MAX_EXPANDED_GLYPHS","MAX_EXPANDED_TEXT_BYTES","MAX_FONT_BYTES",+ "MAX_GLYPH_TOKENS","MAX_OBJECT_RECURSION","MAX_PAGE_COUNT","MAX_PATH_COMMANDS",diff --git a/mineru/model/flash/ofd/package.py b/mineru/model/flash/ofd/package.pyindex 611944a9..20b1e9c6 100644--- a/mineru/model/flash/ofd/package.py+++ b/mineru/model/flash/ofd/package.py@@ -15,6 +15,7 @@ from lxml import etree # type: ignore[reportMissingImports]from .constants import (MAX_ASSET_TOTAL_BYTES,+ MAX_DOCUMENT_COUNT,MAX_ENTRY_BYTES,MAX_ENTRY_COUNT,MAX_TOTAL_BYTES,@@ -262,6 +263,8 @@ class OfdPackage:for body in self.root():if local_name(body.tag) != "DocBody":continue+ if len(refs) >= MAX_DOCUMENT_COUNT:+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_document_count={MAX_DOCUMENT_COUNT}")doc_root = first_child(body, "DocRoot")document_part = self.resolve_reference("OFD.xml", element_text(doc_root))if document_part is None:diff --git a/mineru/model/flash/ofd/text.py b/mineru/model/flash/ofd/text.pyindex 66267c2c..8418d0d7 100644--- a/mineru/model/flash/ofd/text.py+++ b/mineru/model/flash/ofd/text.py@@ -15,7 +15,7 @@ from lxml import etree # type: ignore[reportMissingImports]from .._shared.spans import text_spansfrom ....types import BBox-from .constants import MAX_EXPANDED_GLYPHS, MAX_EXPANDED_TEXT_BYTES, MAX_FONT_BYTES+from .constants import MAX_EXPANDED_GLYPHS, MAX_EXPANDED_TEXT_BYTES, MAX_FONT_BYTES, MAX_GLYPH_TOKENSfrom .errors import OfdResourceLimitErrorfrom .geometry import (Affine,@@ -34,6 +34,7 @@ from .models import FontResource, GlyphItem, ResourceRegistry, TextLinefrom .package import OfdPackage, element_text, local_name, parse_int_HEX_ESCAPE_RE = re.compile(r"\\([0-9A-Fa-f]{4})")+_GLYPH_TOKEN_RE = re.compile(r"\S+")@dataclass(slots=True)@@ -43,6 +44,7 @@ class OfdTextBudget:text_bytes: int = 0glyph_count: int = 0glyph_mapping_count: int = 0+ glyph_token_count: int = 0def charge(self, text: str) -> None:"""为一次 TextCode 展开计费。"""@@ -59,6 +61,12 @@ class OfdTextBudget:if self.glyph_mapping_count > MAX_EXPANDED_GLYPHS:raise OfdResourceLimitError(f"OFD resource limit exceeded: max_expanded_glyphs={MAX_EXPANDED_GLYPHS}")+ def charge_glyph_token(self) -> None:+ """累计实际扫描的 Glyphs token 数量并限制全文解析量。"""+ self.glyph_token_count += 1+ if self.glyph_token_count > MAX_GLYPH_TOKENS:+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_glyph_tokens={MAX_GLYPH_TOKENS}")+@dataclass(slots=True)class _LoadedFont:@@ -222,6 +230,20 @@ def parse_delta(value: str | None, count: int) -> list[float]:return output[:count]+def _bounded_glyph_ids(glyphs_element: etree._Element, limit: int, budget: OfdTextBudget) -> list[int]:+ """按需迭代 Glyphs token,只保留有效映射所需的有限 ID。"""+ glyph_ids: list[int] = []+ for match in _GLYPH_TOKEN_RE.finditer(element_text(glyphs_element)):+ budget.charge_glyph_token()+ glyph_id = parse_int(match.group())+ if glyph_id is None:+ continue+ glyph_ids.append(glyph_id)+ if len(glyph_ids) >= limit:+ break+ return glyph_ids++def _glyph_map(text_object: etree._Element, position_count: int, budget: OfdTextBudget) -> dict[int, int]:"""把实际 TextCode 字符位置映射到 glyph ID,并限制累计展开量。"""result: dict[int, int] = {}@@ -233,17 +255,16 @@ def _glyph_map(text_object: etree._Element, position_count: int, budget: OfdTextglyphs_element = next((child for child in element if local_name(child.tag) == "Glyphs"), None)if code_position is None or code_count is None or glyphs_element is None:continue- glyph_ids = [parse_int(item) for item in element_text(glyphs_element).split()]- valid_glyph_ids = [item for item in glyph_ids if item is not None]- if not valid_glyph_ids:- continueeffective_count = min(code_count, max(0, position_count - code_position))if effective_count <= 0:continue+ glyph_ids = _bounded_glyph_ids(glyphs_element, effective_count, budget)+ if not glyph_ids:+ continuebudget.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]+ glyph_index = min(offset, len(glyph_ids) - 1)+ result[code_position + offset] = glyph_ids[glyph_index]return resultdiff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.pyindex 83373292..28c51351 100644--- a/tests/unittest/test_flash_ofd.py+++ b/tests/unittest/test_flash_ofd.py@@ -23,7 +23,13 @@ from mineru.model.flash.ofd import OfdParseError, OfdResourceLimitError, detect_from mineru.model.flash.ofd import images as ofd_imagesfrom mineru.model.flash.ofd import metadata as ofd_metadatafrom mineru.model.flash.ofd import scene as ofd_scene-from mineru.model.flash.ofd.constants import MAX_DRAW_PARAM_INHERITANCE, MAX_EXPANDED_GLYPHS, MAX_PAGE_COUNT+from mineru.model.flash.ofd.constants import (+ MAX_DOCUMENT_COUNT,+ MAX_DRAW_PARAM_INHERITANCE,+ MAX_EXPANDED_GLYPHS,+ MAX_GLYPH_TOKENS,+ MAX_PAGE_COUNT,+)from 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@@ -154,6 +160,38 @@ def test_ofd_page_count_budget_is_shared_across_doc_bodies(monkeypatch: pytest.Mofd_metadata.extract_ofd_metadata(BytesIO(payload))+def test_ofd_declared_document_count_is_bounded_before_page_parsing() -> None:+ """验证大量空 DocBody 在物化文档引用前受独立预算限制。"""+ payload = build_ofd_package([("Pages/Page_0/Content.xml", page_xml(""))])+ source_buffer = BytesIO(payload)+ output_buffer = BytesIO()+ with ZipFile(source_buffer) as source, ZipFile(output_buffer, "w", ZIP_DEFLATED) as output:+ ofd_root = etree.fromstring(source.read("OFD.xml"))+ for child in list(ofd_root):+ ofd_root.remove(child)+ namespace = etree.QName(ofd_root).namespace+ for _document_index in range(MAX_DOCUMENT_COUNT + 1):+ doc_body = etree.SubElement(ofd_root, f"{{{namespace}}}DocBody")+ doc_root = etree.SubElement(doc_body, f"{{{namespace}}}DocRoot")+ doc_root.text = "Doc_0/Document.xml"+ document_root = etree.fromstring(source.read("Doc_0/Document.xml"))+ pages = next(element for element in document_root.iter() if etree.QName(element).localname == "Pages")+ pages.clear()+ replacements = {+ "OFD.xml": etree.tostring(ofd_root, xml_declaration=True, encoding="UTF-8"),+ "Doc_0/Document.xml": etree.tostring(document_root, xml_declaration=True, encoding="UTF-8"),+ }+ for info in source.infolist():+ content = replacements[info.filename] if info.filename in replacements else source.read(info.filename)+ output.writestr(info, content)+ oversized = output_buffer.getvalue()++ with pytest.raises(OfdResourceLimitError, match="max_document_count"):+ OfdModel().predict(BytesIO(oversized))+ with pytest.raises(OfdResourceLimitError, match="max_document_count"):+ ofd_metadata.extract_ofd_metadata(BytesIO(oversized))++def test_ofd_textcode_geometry_does_not_use_oversized_boundary() -> None:"""验证 Foxit 风格超大 Boundary 不会成为最终文字 bbox。"""content = text_object(@@ -248,11 +286,14 @@ def test_ofd_textcode_preserves_boundary_whitespace_and_glyph_positions() -> Nondef test_ofd_cgtransform_expands_only_actual_text_positions() -> None:"""验证超大 CodeCount 只映射 TextCode 实际存在的字符位置。"""+ glyphs = "42 " + "999 " * 100_000text_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>"+ (+ '<TextObject ID="10" Boundary="0 0 10 10" Font="1" Size="5">'+ '<TextCode X="1" Y="5">A</TextCode>'+ f'<CGTransform CodePosition="0" CodeCount="1000000000"><Glyphs>{glyphs}</Glyphs></CGTransform>'+ "</TextObject>"+ ).encode())package_buffer = BytesIO()with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:@@ -275,6 +316,7 @@ def test_ofd_cgtransform_expands_only_actual_text_positions() -> None:assert budget.glyph_count == 1assert budget.glyph_mapping_count == 1+ assert budget.glyph_token_count == 1assert len(lines) == 1assert [glyph.glyph_id for glyph in lines[0].glyphs] == [42]@@ -293,6 +335,21 @@ def test_ofd_cgtransform_expands_only_actual_text_positions() -> None:template_id=None,)+ token_exhausted_budget = OfdTextBudget(glyph_token_count=MAX_GLYPH_TOKENS)+ with pytest.raises(OfdResourceLimitError, match="max_glyph_tokens"):+ 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=token_exhausted_budget,+ paint_order=0,+ layer_type="body",+ template_id=None,+ )+def test_ofd_textcode_discards_glyphs_outside_object_boundary() -> None:"""验证 TextObject Boundary 会裁掉完整位于边界外的字符和空行。"""