Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(server): restore Docling "u" glyph names that docling-parse leaves unmapped (#962)

Krisztian Gajdardbfda27934f4
diff --git a/packages/sie_server/src/sie_server/adapters/docling/adapter.py b/packages/sie_server/src/sie_server/adapters/docling/adapter.py
index a12ef01a4..51789b24e 100644
--- a/packages/sie_server/src/sie_server/adapters/docling/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/docling/adapter.py
@@ -53,6 +53,15 @@ def _processed_page_count(result: Any) -> int:
_LEAKED_SIGN_GLYPH_NAME = re.compile(r"/(?P<word>[A-Za-z]+?)sign")
+# An Adobe Glyph List ``u`` name (``/u1D465``) spells its code point in uppercase
+# hex, and a leaked name runs into the text that follows it, so its length is a
+# guess. Five digits are read only inside Mathematical Alphanumeric Symbols
+# (U+1D400 to U+1D7FF), the block of the leaked math letters; any other name is
+# four digits, so ``/u20132`` is an en dash followed by ``2`` and ``/u1ECCC`` is
+# U+1ECC followed by ``C``.
+_LEAKED_UNICODE_GLYPH_NAME = re.compile(r"/u(?P<digits>[0-9A-F]{4,5})")
+
+
def _sign_character(match: re.Match[str]) -> str:
try:
character = unicodedata.lookup(f"{match.group('word')} SIGN")
@@ -61,14 +70,29 @@ def _sign_character(match: re.Match[str]) -> str:
return character if len(character) == 1 else match.group(0)
+def _unicode_character(match: re.Match[str]) -> str:
+ digits = match.group("digits")
+ if len(digits) == 5 and 0x1D400 <= int(digits, 16) <= 0x1D7FF:
+ return chr(int(digits, 16))
+ code = int(digits[:4], 16)
+ if 0xD800 <= code <= 0xDFFF:
+ return match.group(0)
+ return chr(code) + digits[4:]
+
+
+def _restore_glyph_text(text: str) -> str:
+ text = _LEAKED_SIGN_GLYPH_NAME.sub(_sign_character, text)
+ return _LEAKED_UNICODE_GLYPH_NAME.sub(_unicode_character, text)
+
+
def _restore_glyph_names(doc: Any) -> None:
"""Replace leaked glyph names in the document's text and table cells with their characters."""
for item in doc.texts:
- item.text = _LEAKED_SIGN_GLYPH_NAME.sub(_sign_character, item.text)
- item.orig = _LEAKED_SIGN_GLYPH_NAME.sub(_sign_character, item.orig)
+ item.text = _restore_glyph_text(item.text)
+ item.orig = _restore_glyph_text(item.orig)
for table in doc.tables:
for cell in table.data.table_cells:
- cell.text = _LEAKED_SIGN_GLYPH_NAME.sub(_sign_character, cell.text)
+ cell.text = _restore_glyph_text(cell.text)
_ERR_REQUIRES_DOCUMENT = "Document or image input is required"
diff --git a/packages/sie_server/tests/adapters/test_docling.py b/packages/sie_server/tests/adapters/test_docling.py
index a9d2641fa..e5052e50c 100644
--- a/packages/sie_server/tests/adapters/test_docling.py
+++ b/packages/sie_server/tests/adapters/test_docling.py
@@ -126,6 +126,53 @@ class TestDoclingExtract:
assert [(text["text"], text["orig"]) for text in texts] == [(restored, restored), (untouched, untouched)]
assert payload["document"]["tables"][0]["data"]["table_cells"][0]["text"] == "$1,200"
+ @pytest.mark.parametrize(
+ ("leaked", "restored"),
+ [
+ pytest.param("1990 /u2014 2000", "1990 — 2000", id="four-digit"),
+ pytest.param("let /u1D465 be", "let \U0001d465 be", id="five-digit"),
+ pytest.param("2/u1D4652 + /u1D466/u1D467", "2\U0001d4652 + \U0001d466\U0001d467", id="glued-to-digits"),
+ pytest.param(
+ "/u20142 and pages 10/u201320", "\u20142 and pages 10\u201320", id="four-digit-glued-to-digits"
+ ),
+ pytest.param("/u1D465C or /u1D465x", "\U0001d465C or \U0001d465x", id="glued-to-letters"),
+ pytest.param("H/u1ECCC and /u1F002", "H\u1eccC and \u1f002", id="bmp-glued-to-hex-digits"),
+ pytest.param("/u0041BC", "ABC", id="four-digit-glued-to-hex-letters"),
+ pytest.param("/uD835/uDC65", "/uD835/uDC65", id="surrogates"),
+ pytest.param("/u12, /u1d465, /uFFG0", "/u12, /u1d465, /uFFG0", id="invalid"),
+ ],
+ )
+ def test_restores_unicode_glyph_names(self, leaked: str, restored: str) -> None:
+ document = DoclingDocument(name="paper")
+ document.add_text(label=DocItemLabel.TEXT, text=leaked)
+ cell = TableCell(
+ text=leaked,
+ start_row_offset_idx=0,
+ end_row_offset_idx=1,
+ start_col_offset_idx=0,
+ end_col_offset_idx=1,
+ )
+ document.add_table(data=TableData(num_rows=1, num_cols=1, table_cells=[cell]))
+ converter = MagicMock()
+ converter.convert.return_value = SimpleNamespace(
+ status=ConversionStatus.SUCCESS,
+ document=document,
+ pages=[object()],
+ input=SimpleNamespace(format=InputFormat.PDF),
+ )
+ adapter, _ = _make_adapter()
+ adapter._make_converter = MagicMock(return_value=converter) # type: ignore[method-assign]
+
+ out = adapter.extract([Item(document={"data": b"pdf", "format": "pdf"})])
+
+ assert out.errors is None
+ assert out.data is not None
+ payload = out.data[0]
+ assert restored in payload["text"]
+ text = payload["document"]["texts"][0]
+ assert (text["text"], text["orig"]) == (restored, restored)
+ assert payload["document"]["tables"][0]["data"]["table_cells"][0]["text"] == restored
+
@pytest.mark.parametrize("input_format", [InputFormat.HTML, InputFormat.DOCX, InputFormat.IMAGE])
def test_keeps_glyph_name_text_from_non_pdf_inputs(self, input_format: InputFormat) -> None:
literal = "Static files live under /dollarsign-assets"
diff --git a/packages/sie_server/tests/adapters/test_docling_smoke.py b/packages/sie_server/tests/adapters/test_docling_smoke.py
index 96fd935d4..a2ba6668a 100644
--- a/packages/sie_server/tests/adapters/test_docling_smoke.py
+++ b/packages/sie_server/tests/adapters/test_docling_smoke.py
@@ -68,16 +68,21 @@ def test_extract_real_document(loaded_adapter: DoclingAdapter, format_hint: str,
assert "document" in item
-def _make_glyph_name_pdf_bytes() -> bytes:
- """One page whose font maps ``$`` and ``%`` to the non-standard glyph names ``/dollarsign`` and ``/percentsign``."""
- content = b"BT /F1 12 Tf 72 700 Td (Net sales $209,586, up 5%) Tj ET"
+def _make_glyph_name_pdf_bytes(
+ text: bytes = b"Net sales $209,586, up 5%", differences: bytes = b"36 /dollarsign /percentsign"
+) -> bytes:
+ """One page of ``text`` whose font renames character codes per the encoding ``differences``.
+
+ The defaults map ``$`` and ``%`` to the non-standard glyph names ``/dollarsign`` and ``/percentsign``.
+ """
+ content = b"BT /F1 12 Tf 72 700 Td (%s) Tj ET" % text
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> "
b"/Contents 5 0 R >>",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Type /Encoding "
- b"/BaseEncoding /WinAnsiEncoding /Differences [36 /dollarsign /percentsign] >> >>",
+ b"/BaseEncoding /WinAnsiEncoding /Differences [%s] >> >>" % differences,
b"<< /Length %d >>\nstream\n%s\nendstream" % (len(content), content),
]
out = bytearray(b"%PDF-1.4\n")
@@ -104,6 +109,20 @@ def test_extract_pdf_restores_unmapped_glyph_names(loaded_adapter: DoclingAdapte
assert "sign" not in rendered
+def test_extract_pdf_restores_unicode_glyph_names(loaded_adapter: DoclingAdapter) -> None:
+ pdf = _make_glyph_name_pdf_bytes(text=b"let x2 = y", differences=b"120 /u1D465 /u1D466")
+
+ out = loaded_adapter.extract([Item(document={"data": pdf, "format": "pdf"})])
+
+ assert out.errors is None
+ assert out.data is not None
+ for output_format in ("text", "markdown"):
+ rendered = out.data[0][output_format]
+ assert "let \U0001d4652 = \U0001d466" in rendered
+ assert "/u" not in rendered
+
+
def test_extract_html_keeps_literal_glyph_name_text(loaded_adapter: DoclingAdapter) -> None:
html = b"<html><body><p>Static files live under /dollarsign-assets.</p></body></html>"