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 pages and measure text gaps
myhloli29f0483ceb63
diff --git a/mineru/model/flash/ofd/constants.py b/mineru/model/flash/ofd/constants.pyindex 71c59be6..ca298560 100644--- a/mineru/model/flash/ofd/constants.py+++ b/mineru/model/flash/ofd/constants.py@@ -16,6 +16,7 @@ MAX_TOTAL_BYTES: Final = 512 * 1024 * 1024MAX_ENTRY_COUNT: Final = 100_000MAX_XML_DEPTH: Final = 256MAX_XML_NODES: Final = 2_000_000+MAX_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@@ -36,6 +37,7 @@ __all__ = ["MAX_EXPANDED_TEXT_BYTES","MAX_FONT_BYTES","MAX_OBJECT_RECURSION",+ "MAX_PAGE_COUNT","MAX_PATH_COMMANDS","MAX_TOTAL_BYTES","MAX_XML_DEPTH",diff --git a/mineru/model/flash/ofd/metadata.py b/mineru/model/flash/ofd/metadata.pyindex a85ff2d6..1cb206c4 100644--- a/mineru/model/flash/ofd/metadata.py+++ b/mineru/model/flash/ofd/metadata.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom typing import BinaryIO-from .constants import MAX_TOTAL_BYTES+from .constants import MAX_PAGE_COUNT, MAX_TOTAL_BYTESfrom .errors import OfdResourceLimitErrorfrom .package import OfdPackage, first_descendant, local_name@@ -35,7 +35,12 @@ def extract_ofd_metadata(file_binary: BinaryIO) -> dict[str, object | None]:assert document_root is not Nonepages = first_descendant(document_root, "Pages")if pages is not None:- page_count += sum(local_name(child.tag) == "Page" for child in pages)+ for child in pages:+ if local_name(child.tag) != "Page":+ continue+ page_count += 1+ if page_count > MAX_PAGE_COUNT:+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_page_count={MAX_PAGE_COUNT}")for source_key, target_key in key_map.items():if metadata[target_key] is None and ref.metadata.get(source_key):metadata[target_key] = ref.metadata[source_key]diff --git a/mineru/model/flash/ofd/reading_order.py b/mineru/model/flash/ofd/reading_order.pyindex 459404c6..18f4b581 100644--- a/mineru/model/flash/ofd/reading_order.py+++ b/mineru/model/flash/ofd/reading_order.py@@ -16,6 +16,7 @@ from .table import OfdTableRegion, recover_tablesfrom .text import format_line_spans_PAGE_NUMBER_RE = re.compile(r"^(?:\d+|[IVXLCDM]+)$", re.IGNORECASE)+_ASCII_WORD_GAP_RATIO = 0.2def _same_baseline(first: TextLine, second: TextLine) -> bool:@@ -38,12 +39,27 @@ def _same_baseline(first: TextLine, second: TextLine) -> bool:def _join_text(first: TextLine, second: TextLine) -> str:- """按语言字符边界决定同行片段间是否补空格。"""+ """按语言字符边界和实际字形间距决定同行片段间是否补空格。"""if not first.text or not second.text:return first.text + second.text- needs_space = (+ ascii_word_boundary = (first.text[-1].isascii() and second.text[0].isascii() and first.text[-1].isalnum() and second.text[0].isalnum())+ if not ascii_word_boundary:+ return first.text + second.text+ first_glyph = first.glyphs[-1] if first.glyphs else None+ second_glyph = second.glyphs[0] if second.glyphs else None+ first_right = first_glyph.bbox[2] if first_glyph is not None else first.bbox[2]+ second_left = second_glyph.bbox[0] if second_glyph is not None else second.bbox[0]+ gap = second_left - first_right+ glyph_widths = [+ glyph.bbox[2] - glyph.bbox[0]+ for glyph in (first_glyph, second_glyph)+ if glyph is not None and glyph.bbox[2] > glyph.bbox[0]+ ]+ reference_width = statistics.median(glyph_widths) if glyph_widths else 0.0+ spacing_threshold = _ASCII_WORD_GAP_RATIO * max(min(first.font_size, second.font_size), reference_width, 0.5)+ needs_space = gap >= spacing_thresholdreturn f"{first.text}{' ' if needs_space else ''}{second.text}"diff --git a/mineru/model/flash/ofd/scene.py b/mineru/model/flash/ofd/scene.pyindex 023b1884..2b402177 100644--- a/mineru/model/flash/ofd/scene.py+++ b/mineru/model/flash/ofd/scene.py@@ -9,7 +9,7 @@ from loguru import loggerfrom lxml import etree # type: ignore[reportMissingImports]from ....types import BBox-from .constants import MAX_OBJECT_RECURSION, OFD_NAMESPACES+from .constants import MAX_OBJECT_RECURSION, MAX_PAGE_COUNT, OFD_NAMESPACESfrom .errors import OfdParseError, OfdResourceLimitErrorfrom .geometry import Affine, bbox_intersection, parse_affine, parse_st_box, transform_bboxfrom .images import build_image_item@@ -30,6 +30,7 @@ class OfdSceneBuilder:self.path_budget = OfdPathBudget()self.font_metrics = FontMetricResolver(package)self._paint_order = 0+ self._page_count = 0def build(self) -> list[OfdPageScene]:"""按 DocBody 和 Pages 声明顺序构造全部页面。"""@@ -100,6 +101,9 @@ class OfdSceneBuilder:for element in pages:if local_name(element.tag) != "Page":continue+ self._page_count += 1+ if self._page_count > MAX_PAGE_COUNT:+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_page_count={MAX_PAGE_COUNT}")page_part = self.package.resolve_reference(document_part, element.get("BaseLoc"))if page_part is None or not self.package.has_part(page_part):raise OfdParseError(f"Malformed OFD package: invalid page BaseLoc in {document_part!r}")diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.pyindex 5c879299..83373292 100644--- a/tests/unittest/test_flash_ofd.py+++ b/tests/unittest/test_flash_ofd.py@@ -21,7 +21,9 @@ 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, MAX_EXPANDED_GLYPHS+from mineru.model.flash.ofd import metadata as ofd_metadata+from 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_COUNTfrom 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@@ -112,6 +114,46 @@ def test_ofd_multiple_doc_bodies_flatten_in_declared_order() -> None:assert [inline_text(page[0]["content"]) for page in model.pages] == ["doc-zero", "doc-one"]+def test_ofd_declared_page_count_is_bounded_for_parser_and_metadata() -> None:+ """验证重复引用同一页面 part 也受全文页数预算限制。"""+ 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:+ 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()+ namespace = etree.QName(document_root).namespace+ for page_index in range(MAX_PAGE_COUNT + 1):+ etree.SubElement(+ pages,+ f"{{{namespace}}}Page",+ ID=str(page_index + 1),+ BaseLoc="Pages/Page_0/Content.xml",+ )+ replacement = etree.tostring(document_root, xml_declaration=True, encoding="UTF-8")+ for info in source.infolist():+ output.writestr(info, replacement if info.filename == "Doc_0/Document.xml" else source.read(info.filename))+ oversized = output_buffer.getvalue()++ with pytest.raises(OfdResourceLimitError, match="max_page_count"):+ OfdModel().predict(BytesIO(oversized))+ with pytest.raises(OfdResourceLimitError, match="max_page_count"):+ ofd_metadata.extract_ofd_metadata(BytesIO(oversized))+++def test_ofd_page_count_budget_is_shared_across_doc_bodies(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证多个 DocBody 共用解析和元数据页数预算。"""+ monkeypatch.setattr(ofd_scene, "MAX_PAGE_COUNT", 1)+ monkeypatch.setattr(ofd_metadata, "MAX_PAGE_COUNT", 1)+ payload = build_multi_document_ofd()++ with pytest.raises(OfdResourceLimitError, match="max_page_count"):+ OfdModel().predict(BytesIO(payload))+ with pytest.raises(OfdResourceLimitError, match="max_page_count"):+ ofd_metadata.extract_ofd_metadata(BytesIO(payload))++def test_ofd_textcode_geometry_does_not_use_oversized_boundary() -> None:"""验证 Foxit 风格超大 Boundary 不会成为最终文字 bbox。"""content = text_object(@@ -153,6 +195,25 @@ def test_ofd_cardinal_text_directions_keep_geometry_and_angle() -> None:assert model.pages[0][0]["bbox"][3] > model.pages[0][0]["bbox"][1][email protected](("second_x", "expected"), [(16.0, "Hello"), (17.0, "Hel lo")])+def test_ofd_same_baseline_ascii_fragments_use_measured_gap(second_x: float, expected: str) -> None:+ """验证相邻英文 run 仅在存在可见词间距时补空格。"""+ content = "".join(+ [+ text_object(1, "Hel", boundary="10 10 10 10", size=4, y=5, delta_x="2 2"),+ text_object(2, "lo", boundary=f"{second_x} 10 10 10", size=4, y=5, delta_x="2"),+ ]+ )++ _middle, model = doc_analyze(+ build_ofd_package([("Pages/Page_0/Content.xml", page_xml(content))]),+ file_suffix="ofd",+ )++ assert len(model.pages[0]) == 1+ assert inline_text(model.pages[0][0]["content"]) == expected++def test_ofd_textcode_preserves_boundary_whitespace_and_glyph_positions() -> None:"""验证 TextCode 首尾空格参与 Delta 展开和 CGTransform 全局位置映射。"""text_element = etree.fromstring(