Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix: bound PDF formulas and OFD text decoding

myhloli463dd1354c98
diff --git a/mineru/model/flash/ofd/text.py b/mineru/model/flash/ofd/text.py
index c30452e0..db5050ec 100644
--- a/mineru/model/flash/ofd/text.py
+++ b/mineru/model/flash/ofd/text.py
@@ -8,7 +8,7 @@ import math
import re
from collections import deque
from dataclasses import dataclass
-from io import BytesIO
+from io import BytesIO, StringIO
from fontTools.pens.boundsPen import BoundsPen
from loguru import logger
@@ -37,6 +37,8 @@ from .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+")
_DELTA_TOKEN_RE = re.compile(r"[^,\s]+")
+_HEX_DIGITS = frozenset("0123456789abcdefABCDEF")
+_TEXT_CODE_DECODE_CHUNK_SIZE = 64 * 1024
@dataclass(slots=True)
@@ -51,12 +53,14 @@ class OfdTextBudget:
def charge(self, text: str) -> None:
"""为一次 TextCode 展开计费。"""
- self.text_bytes += len(text.encode("utf-8"))
- self.glyph_count += len(text)
- if self.text_bytes > MAX_EXPANDED_TEXT_BYTES:
- raise OfdResourceLimitError(f"OFD resource limit exceeded: max_expanded_text_bytes={MAX_EXPANDED_TEXT_BYTES}")
- if self.glyph_count > MAX_EXPANDED_GLYPHS:
+ glyph_count = self.glyph_count + len(text)
+ if glyph_count > MAX_EXPANDED_GLYPHS:
raise OfdResourceLimitError(f"OFD resource limit exceeded: max_expanded_glyphs={MAX_EXPANDED_GLYPHS}")
+ text_bytes = self.text_bytes + len(text.encode("utf-8"))
+ if text_bytes > MAX_EXPANDED_TEXT_BYTES:
+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_expanded_text_bytes={MAX_EXPANDED_TEXT_BYTES}")
+ self.glyph_count = glyph_count
+ self.text_bytes = text_bytes
def charge_glyph_mapping(self, count: int) -> None:
"""累计 CGTransform 的有效字符映射数量并限制全文展开量。"""
@@ -206,6 +210,41 @@ def decode_text_code(value: str) -> str:
return _HEX_ESCAPE_RE.sub(lambda match: chr(int(match.group(1), 16)), value)
+def _incomplete_hex_escape_length(value: str) -> int:
+ """返回末尾可能跨分片的反斜杠十六进制前缀长度。"""
+ for length in range(min(4, len(value)), 0, -1):
+ suffix = value[-length:]
+ if suffix[0] == "\\" and all(character in _HEX_DIGITS for character in suffix[1:]):
+ return length
+ return 0
+
+
+def _decode_text_code_element(text_code: etree._Element, budget: OfdTextBudget) -> str:
+ """分片解码一个 TextCode,并在写入完整字符串前累计文字预算。"""
+ output = StringIO()
+ carry = ""
+ for part in text_code.itertext():
+ for offset in range(0, len(part), _TEXT_CODE_DECODE_CHUNK_SIZE):
+ chunk = part[offset : offset + _TEXT_CODE_DECODE_CHUNK_SIZE]
+ value = f"{carry}{chunk}" if carry else chunk
+ carry_length = _incomplete_hex_escape_length(value)
+ if carry_length:
+ complete = value[:-carry_length]
+ carry = value[-carry_length:]
+ else:
+ complete = value
+ carry = ""
+ if not complete:
+ continue
+ decoded = decode_text_code(complete)
+ budget.charge(decoded)
+ output.write(decoded)
+ if carry:
+ budget.charge(carry)
+ output.write(carry)
+ return output.getvalue()
+
+
def parse_delta(value: str | None, count: int, budget: OfdTextBudget) -> list[float]:
"""流式展开普通与 g-count-value 压缩 Delta,并补齐不足项。"""
if count <= 0:
@@ -382,10 +421,9 @@ def build_text_lines(
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()))
+ text = _decode_text_code_element(text_code, budget)
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 = 0
diff --git a/mineru/render/_internal/pdf/formula.py b/mineru/render/_internal/pdf/formula.py
index 08cb996a..d986163d 100644
--- a/mineru/render/_internal/pdf/formula.py
+++ b/mineru/render/_internal/pdf/formula.py
@@ -77,13 +77,15 @@ class FormulaRenderer:
raise PdfFormulaError("formula must contain non-blank LaTeX")
if not isinstance(font_size, (int, float)) or isinstance(font_size, bool) or font_size <= 0:
raise PdfFormulaError("font_size must be a positive number")
+ if len(latex) > MAX_FORMULA_CHARACTERS:
+ raise PdfFormulaError(f"formula exceeds max_formula_characters={MAX_FORMULA_CHARACTERS}")
key = (latex, inline, float(font_size), color)
- if len(latex) <= MAX_FORMULA_CHARACTERS and key in self._cache:
+ if key in self._cache:
return self._cache[key]
vector = _render_ziamath_formula(latex, inline=inline, font_size=float(font_size), color=color)
- if len(latex) <= MAX_FORMULA_CHARACTERS and len(self._cache) < MAX_CACHED_FORMULAS:
+ if len(self._cache) < MAX_CACHED_FORMULAS:
self._cache[key] = vector
return vector
diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.py
index 46b19b83..61a96c7d 100644
--- a/tests/unittest/test_flash_ofd.py
+++ b/tests/unittest/test_flash_ofd.py
@@ -26,6 +26,7 @@ from mineru.model.flash.ofd import images as ofd_images
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 import table as ofd_table
+from mineru.model.flash.ofd import text as ofd_text
from mineru.model.flash.ofd.constants import (
MAX_DELTA_TOKENS,
MAX_DOCUMENT_COUNT,
@@ -383,6 +384,33 @@ def test_ofd_delta_tokens_are_streamed_and_bounded() -> None:
parse_delta("invalid 1", 1, exhausted)
+def test_ofd_textcode_is_decoded_and_charged_in_bounded_chunks(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证十六进制转义可跨分片恢复,超限时不会先解码完整 TextCode。"""
+ monkeypatch.setattr(ofd_text, "_TEXT_CODE_DECODE_CHUNK_SIZE", 3)
+ escaped = etree.fromstring(b"<TextCode>before\\00<Part>41</Part>after</TextCode>")
+ budget = OfdTextBudget()
+
+ assert ofd_text._decode_text_code_element(escaped, budget) == "beforeAafter"
+ assert budget.glyph_count == len("beforeAafter")
+
+ monkeypatch.setattr(ofd_text, "_TEXT_CODE_DECODE_CHUNK_SIZE", 16)
+ oversized = etree.fromstring(f"<TextCode>{'A' * 100_000}</TextCode>".encode())
+ original_decode = ofd_text.decode_text_code
+ decoded_chunk_lengths: list[int] = []
+
+ def record_decode(value: str) -> str:
+ """记录单次解码规模并委托真实转义实现。"""
+ decoded_chunk_lengths.append(len(value))
+ return original_decode(value)
+
+ monkeypatch.setattr(ofd_text, "decode_text_code", record_decode)
+ exhausted = OfdTextBudget(glyph_count=MAX_EXPANDED_GLYPHS)
+ with pytest.raises(OfdResourceLimitError, match="max_expanded_glyphs"):
+ ofd_text._decode_text_code_element(oversized, exhausted)
+
+ assert decoded_chunk_lengths == [16]
+
+
def test_ofd_textcode_discards_glyphs_outside_object_boundary() -> None:
"""验证 TextObject Boundary 会裁掉完整位于边界外的字符和空行。"""
package_buffer = BytesIO()
diff --git a/tests/unittest/test_pdf_render.py b/tests/unittest/test_pdf_render.py
index f3c912a0..a7211c63 100644
--- a/tests/unittest/test_pdf_render.py
+++ b/tests/unittest/test_pdf_render.py
@@ -231,8 +231,8 @@ def test_ziamath_vector_corpus_covers_inline_and_display_constructs(source: str,
assert vector.drawing.contents
-def test_formula_cache_is_bounded_and_skips_oversized_entries(monkeypatch: pytest.MonkeyPatch) -> None:
- """验证公式超长或唯一项超过预算时继续渲染但不扩张文档级缓存。"""
+def test_formula_cache_is_bounded_and_rejects_oversized_entries(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证超长公式在 ZiaMath 前失败,唯一项超过预算时不扩张缓存。"""
calls: list[str] = []
def fake_render(latex: str, *, inline: bool, font_size: float, color: str) -> FormulaVector:
@@ -243,12 +243,12 @@ def test_formula_cache_is_bounded_and_skips_oversized_entries(monkeypatch: pytes
monkeypatch.setattr(formula_module, "_render_ziamath_formula", fake_render)
renderer = FormulaRenderer()
oversized = "x" * (formula_module.MAX_FORMULA_CHARACTERS + 1)
- renderer.render(oversized, inline=True, font_size=10)
- renderer.render(oversized, inline=True, font_size=10)
+ with pytest.raises(PdfFormulaError, match="max_formula_characters"):
+ renderer.render(oversized, inline=True, font_size=10)
for index in range(formula_module.MAX_CACHED_FORMULAS + 3):
renderer.render(f"x_{index}", inline=True, font_size=10)
- assert calls.count(oversized) == 2
+ assert oversized not in calls
assert len(renderer._cache) == formula_module.MAX_CACHED_FORMULAS # noqa: SLF001