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

Aperta
#492 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
74/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
cpp, python
Ambito
backend, data

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
C++
Stelle
352
Fork
99
Merge medio
1g 21h
PR unite (30g)
37

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di docling-project/docling-parse

Tutte le issue di docling-project/docling-parse

Issue simili

Altre issue su C++

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.