Persian and Arabic-Indic numbers come out reversed in right-to-left text (`۱۴۰۱` → `۱۰۴۱`, `۹٬۰۳۹٬۰۰۰` → `۰۰۰٬۹۳۰٬۹`)

Open
#492 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
74/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
cpp, python
Domain
backend, data

Research direction

Start with page_item_sanitators/cells.h, especially append_cell() and finish_text(), to trace how right-to-left cells are joined. The issue includes a Python reproduction and expected output; use it to verify digit runs and footnote references, then add a regression test. Done means Persian and Arabic-Indic numbers retain their order while surrounding right-to-left text and [۶][۷] remain correct.

Written by the indexing model from the issue text.

Description

Summary

In Persian and Arabic text, docling-parse reverses the digits of every number written with Persian (U+06F0–U+06F9) or Arabic-Indic (U+0660–U+0669) digits. The words, the text lines and the Docling output all have the wrong numbers, so years, amounts and populations are wrong in the text.

On the Persian Wikipedia article «تهران» exported as PDF (63 pages), page 1:

In the PDF docling-parse 7.28.0
برآورد سال ۱۴۰۱ برآورد سال ۱۰۴۱
۹٬۰۳۹٬۰۰۰ تن جمعیت ۰۰۰٬۹۳۰٬۹ تن جمعیت
۲۰۱۸ سازمان ملل متحد ۸۱۰۲ سازمان ملل متحد
در نوروز سال ۱۱۶۵، در نوروز سال ۵۶۱۱،

Over the whole document, 2,511 of the 11,071 numbers (by the count of pypdfium2's text) do not match. pypdfium2 reads all of them correctly from the same file. Numbers written with European digits (0–9) between spaces are not affected.

The PDF: https://fa.wikipedia.org/api/rest_v1/page/pdf/%D8%AA%D9%87%D8%B1%D8%A7%D9%86 (revision 44979853, CC BY-SA 4.0).

Cause

The page paints right-to-left text in visual order, so append_cell() in page_item_sanitators/cells.h prepends each right-to-left cell and finish_text() joins them in reverse. That gives the logical order for letters. A number inside right-to-left text is still written left to right (bidi classes EN and AN), but is_rtl_char() counts U+0600–U+06FF as right to left, and the digits are in that block. So their order is reversed together with the letters.

Taking the digits out of is_rtl_char() alone is not enough: a number next to an Arabic comma (۱۱۶۵،) is still in a right-to-left word, and footnote references such as [۶][۷] then stop being reversed and come out as ]۷[]۶[.

Reproduction

The script writes a one-page PDF itself (no PDF library needed) and prints the words and the line docling-parse decodes.

"""docling-parse reverses Persian and Arabic-Indic numbers in right-to-left text.

Writes a one-page PDF (no third-party PDF library) that paints Persian text in
visual order, as browsers and word processors do, and prints the words and the
line docling-parse decodes.
"""

import sys
from importlib.metadata import version
from pathlib import Path

from docling_parse.pdf_parser import DoclingPdfParser

# code -> Unicode
GLYPHS = {
    "1": "06F1", "4": "06F4", "0": "06F0", "9": "06F9", "3": "06F3",
    "k": "066C", ",": "060C", "s": "0633", "A": "0627", "l": "0644", " ": "0020",
}
# Left to right on the page. In logical order: "سال ۱۴۰۱ ۹٬۰۳۹٬۰۰۰ ۱۴۰۱،"
VISUAL = ",1401 9k039k000 1401 lAs"


def write_pdf(path: Path) -> None:
    codes = sorted(GLYPHS, key=ord)
    first, last = ord(codes[0]), ord(codes[-1])
    widths = " ".join("500" if chr(c) in GLYPHS else "0" for c in range(first, last + 1))
    bfchars = "\n".join(f"<{ord(c):02X}> <{GLYPHS[c]}>" for c in codes)
    cmap = (
        "/CIDInit /ProcSet findresource begin 12 dict begin begincmap\n"
        "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n"
        "/CMapName /Repro-UCS def /CMapType 2 def\n"
        "1 begincodespacerange <00> <FF> endcodespacerange\n"
        f"{len(codes)} beginbfchar\n{bfchars}\nendbfchar\n"
        "endcmap CMapName currentdict /CMap defineresource pop end end"
    )
    content = f"BT /F1 12 Tf 40 50 Td ({VISUAL}) Tj ET"
    objects = [
        "<< /Type /Catalog /Pages 2 0 R >>",
        "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
        "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] "
        "/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
        f"<< /Length {len(content)} >>\nstream\n{content}\nendstream",
        "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica "
        f"/FirstChar {first} /LastChar {last} /Widths [{widths}] /ToUnicode 6 0 R >>",
        f"<< /Length {len(cmap)} >>\nstream\n{cmap}\nendstream",
    ]
    out = b"%PDF-1.7\n"
    offsets = []
    for number, body in enumerate(objects, start=1):
        offsets.append(len(out))
        out += f"{number} 0 obj\n{body}\nendobj\n".encode("latin-1")
    xref = len(out)
    out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode()
    out += "".join(f"{o:010d} 00000 n \n" for o in offsets).encode()
    out += f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()
    path.write_bytes(out)


sys.stdout.reconfigure(encoding="utf-8")
pdf = Path("rtl_digits.pdf")
write_pdf(pdf)
page = DoclingPdfParser(loglevel="fatal").load(str(pdf)).get_page(1)
print("docling-parse", version("docling-parse"))
print("words:", [cell.text for cell in page.word_cells])
print("line: ", [cell.text for cell in page.textline_cells])
print("expected line: ", ["سال ۱۴۰۱ ۹٬۰۳۹٬۰۰۰ ۱۴۰۱،"])

Output with 7.28.0:

words: ['۱۰۴۱،', '۰۰۰٬۹۳۰٬۹', '۱۰۴۱', 'سال']
line:  ['سال ۱۰۴۱ ۰۰۰٬۹۳۰٬۹ ۱۰۴۱،']

Expected:

words: ['۱۴۰۱،', '۹٬۰۳۹٬۰۰۰', '۱۴۰۱', 'سال']
line:  ['سال ۱۴۰۱ ۹٬۰۳۹٬۰۰۰ ۱۴۰۱،']
Proposed fix

In finish_text(), after the prepended cells are joined in reverse, put every run of digit cells (with a single separator such as ٬, ٫, ., ,, / or : between two digits) back in visual order. Only aggregates that were prepended change, so left-to-right text is not affected. With this change all 11,071 numbers of the document above match, and [۶][۷] stays as it is.

I have this working with a unit test and can open a pull request. None of the documents in the regression dataset has Persian or Arabic-Indic digits, so I would first open a dataset pull request that adds this document.

Environment: docling-parse 7.28.0, Python 3.12, Linux x86_64.

Dominant language
C++
Stars
352
Forks
99
Avg merge
1d 21h
Merged PRs (30d)
37

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from docling-project/docling-parse

All issues in docling-project/docling-parse

Similar issues

More C++ issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.