Skip to content

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

feat: implement surrogate pair restoration for improved Unicode handling in PDF text extraction

myhloli7a282d06153f
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index c6b1dd72..73b1c612 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -315,10 +315,11 @@ class PDFDocument:
except Exception:
pass
chars = get_chars(textpage, page_bbox, page_rotation)
+ chars = _deduplicate_pdftext_chars(chars)
+ chars = _ensure_legacy_chars(chars)
+ chars = _restore_pdfium_surrogate_pairs(chars, textpage)
finally:
_try_close(textpage)
- chars = _deduplicate_pdftext_chars(chars)
- chars = _ensure_legacy_chars(chars)
return _deduplicate_near_identical_chars(chars)
def get_page_lines(self, page_idx: int) -> list[Line]:
@@ -1765,6 +1766,84 @@ def _ensure_legacy_chars(chars: Any) -> list[Char]:
return cast(list[Char], chars)
+def _restore_pdfium_surrogate_pairs(
+ chars: list[Char],
+ textpage: pdfium.PdfTextPage,
+) -> list[Char]:
+ """利用 PDFium 原始 UTF-16 code unit 恢复 pdftext 丢失的补充平面字符。"""
+ if not any(
+ len(text := str(char.get("char", ""))) == 1
+ and (text == "\uFFFD" or 0xD800 <= ord(text) <= 0xDFFF)
+ for char in chars
+ ):
+ return chars
+
+ try:
+ textpage_raw = textpage.raw
+ char_count = int(textpage.count_chars())
+ except Exception:
+ textpage_raw = None
+ char_count = 0
+
+ restored_chars: list[Char] = []
+ consumed_char_indices: set[int] = set()
+ get_unicode = pdfium_c.FPDFText_GetUnicode
+
+ for char in chars:
+ text = str(char.get("char", ""))
+ raw_char_idx = char.get("char_idx")
+ try:
+ char_idx = int(raw_char_idx) if raw_char_idx is not None else -1
+ except (TypeError, ValueError):
+ char_idx = -1
+
+ if char_idx in consumed_char_indices:
+ continue
+
+ raw_code = None
+ if (
+ textpage_raw is not None
+ and 0 <= char_idx < char_count
+ and len(text) == 1
+ and (text == "\uFFFD" or 0xD800 <= ord(text) <= 0xDFFF)
+ ):
+ raw_code = int(get_unicode(textpage_raw, char_idx))
+
+ high_surrogate = None
+ low_surrogate = None
+ if raw_code is not None and 0xD800 <= raw_code <= 0xDBFF and char_idx + 1 < char_count:
+ next_code = int(get_unicode(textpage_raw, char_idx + 1))
+ if 0xDC00 <= next_code <= 0xDFFF:
+ high_surrogate = raw_code
+ low_surrogate = next_code
+ consumed_char_indices.add(char_idx + 1)
+ elif raw_code is not None and 0xDC00 <= raw_code <= 0xDFFF and char_idx > 0:
+ previous_code = int(get_unicode(textpage_raw, char_idx - 1))
+ if 0xD800 <= previous_code <= 0xDBFF:
+ high_surrogate = previous_code
+ low_surrogate = raw_code
+
+ if high_surrogate is not None and low_surrogate is not None:
+ restored_char = cast(Char, dict(char))
+ restored_char["char"] = chr(
+ 0x10000
+ + ((high_surrogate - 0xD800) << 10)
+ + (low_surrogate - 0xDC00)
+ )
+ restored_chars.append(restored_char)
+ continue
+
+ if len(text) == 1 and 0xD800 <= ord(text) <= 0xDFFF:
+ restored_char = cast(Char, dict(char))
+ restored_char["char"] = "\uFFFD"
+ restored_chars.append(restored_char)
+ continue
+
+ restored_chars.append(char)
+
+ return restored_chars
+
+
def _char_bbox_values(bbox: object) -> tuple[float, float, float, float] | None:
"""将 tuple/list 或 pdftext Bbox 对象统一转换为四元组坐标。"""
if bbox is None:
diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.py
index e60532a1..9a2c7160 100644
--- a/tests/unittest/test_pdf_document.py
+++ b/tests/unittest/test_pdf_document.py
@@ -420,6 +420,41 @@ def test_pdf_document_does_not_expose_legacy_compat_hooks() -> None:
assert pdf_document.PDFDocument._pdf_doc.fset is None
+def test_restore_pdfium_surrogate_pairs_recovers_supplementary_unicode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证合法 surrogate pair 可恢复,真实替换符与孤立 surrogate 不被误判。"""
+
+ raw_codes = [ord("A"), 0xD835, 0xDF03, 0xFFFD, 0xD835, ord("B")]
+
+ class _FakeTextPage:
+ raw = object()
+
+ def count_chars(self) -> int:
+ return len(raw_codes)
+
+ monkeypatch.setattr(
+ pdf_document.pdfium_c,
+ "FPDFText_GetUnicode",
+ lambda _textpage, char_idx: raw_codes[char_idx],
+ )
+ chars = [
+ {
+ "char": text,
+ "bbox": Bbox([float(char_idx), 0.0, float(char_idx + 1), 1.0]),
+ "rotation": 0,
+ "font": {},
+ "char_idx": char_idx,
+ }
+ for char_idx, text in enumerate(["A", "\uFFFD", "\uFFFD", "\uFFFD", "\ud835", "B"])
+ ]
+
+ restored = pdf_document._restore_pdfium_surrogate_pairs(chars, _FakeTextPage())
+
+ assert [char["char"] for char in restored] == ["A", "𝜃", "\uFFFD", "\uFFFD", "B"]
+ assert [char["char_idx"] for char in restored] == [0, 1, 3, 4, 5]
+
+
def test_get_page_drawing_lines_extracts_forms_filled_rectangles_and_merges_segments() -> None:
"""验证绘图线接口支持 Form、细长填充矩形、共线合并并过滤斜线。"""
with pdf_document.PDFDocument(_build_drawing_pdf()) as doc: