File size: 7,014 Bytes
a81d94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#!/usr/bin/env python3
"""ArShape — when does the standard Arabic rendering recipe break Arabic?

Author: Syamjith NK

REBUILT after the first version measured the wrong thing. Recording why, because the
mistake is the finding.

I assumed Arabic needs `arabic_reshaper` + `python-bidi` applied before drawing, and
that plain rendering would come out disconnected. That is the advice you find
everywhere. Rendering it proved the opposite: on a modern text stack, plain output was
correct (مرحبا بكم) and the reshaped output was mangled (مكب ابحرم).

The reason is that Pillow 12 links **Raqm/HarfBuzz**, which already performs shaping
and the bidi algorithm. Pre-reshaping hands it text that has been shaped once and
reordered once, and it does both again. Two rights make a wrong.

So the real question is not "does Arabic need reshaping" but:

    Does this rendering path ALREADY do complex-text layout?
      yes -> reshaping breaks it
      no  -> reshaping is required

This benchmark measures that 2x2 directly, plus the font-coverage trap that bit the
first run: SFArabic.ttf has no Latin digit glyphs, so "في عام 2026" renders the digits
as .notdef boxes while looking perfectly fine to anyone not reading the numbers.
"""
import json
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFont

HERE = Path(__file__).parent
OUT = HERE / "out"; OUT.mkdir(parents=True, exist_ok=True)
SIZE = (900, 170)
PT = 60

FONTS = {
    "SFArabic": "/System/Library/Fonts/SFArabic.ttf",
    "GeezaPro": "/System/Library/Fonts/GeezaPro.ttc",
    "IBMPlexSansArabic": str(Path.home() / "Library/Fonts/IBMPlexSansArabic-Regular.ttf"),
}

CASES = [
    ("greeting",    "مرحبا بكم"),
    ("sentence",    "التزامنا بالنزاهة"),
    ("with_digits", "في عام 2026"),
    ("mixed_latin", "شركة Pixelogik للإنتاج"),
    ("diacritics",  "مَرْحَبًا بِكُمْ"),
]


def reshape(text: str) -> str:
    import arabic_reshaper
    from bidi.algorithm import get_display
    return get_display(arabic_reshaper.reshape(text))


def draw(text: str, font_path: str, engine, pre_reshape: bool) -> Image.Image:
    if pre_reshape:
        text = reshape(text)
    im = Image.new("L", SIZE, 255)
    f = ImageFont.truetype(font_path, PT, layout_engine=engine)
    ImageDraw.Draw(im).text((SIZE[0] - 30, 45), text, font=f, fill=0, anchor="ra")
    return im


def ink_iou(a: Image.Image, b: Image.Image) -> float:
    """Shape similarity, INVARIANT to where the text sits.

    A raw pixel IoU compares position as well as shape, and the two layout engines
    place glyphs a few pixels apart. That made a visually IDENTICAL rendering score
    zero - the metric could not tell "same words, different kerning" from "different
    words". Crop each to its ink bounding box and normalise before comparing, so this
    measures the letterforms and not the layout offset.
    """
    def norm(im):
        arr = (np.asarray(im) < 128)
        if not arr.any():
            return np.zeros((64, 256), dtype=bool)
        ys, xs = np.where(arr)
        crop = Image.fromarray((~arr[ys.min():ys.max() + 1, xs.min():xs.max() + 1]).astype(np.uint8) * 255)
        return np.asarray(crop.resize((256, 64), Image.LANCZOS)) < 128
    x, y = norm(a), norm(b)
    u = (x | y).sum()
    return float((x & y).sum() / u) if u else 1.0


def missing_glyphs(text: str, font_path: str) -> list[str]:
    """Characters the font has no glyph for. These render as .notdef boxes and are
    invisible to anyone skim-reading the language they DO know."""
    try:
        from fontTools.ttLib import TTFont, TTCollection
        f = (TTCollection(font_path).fonts[0] if font_path.endswith(".ttc")
             else TTFont(font_path, fontNumber=0))
        cmap = set()
        for t in f["cmap"].tables:
            cmap |= set(t.cmap.keys())
        return [c for c in dict.fromkeys(text) if c.strip() and ord(c) not in cmap]
    except Exception:
        return []


RAQM = ImageFont.Layout.RAQM
BASIC = ImageFont.Layout.BASIC

PATHS = {
    "raqm_plain":       (RAQM,  False),   # modern stack, text passed through as-is
    "raqm_reshaped":    (RAQM,  True),    # modern stack + the legacy recipe
    "basic_plain":      (BASIC, False),   # no complex-text layout, no recipe
    "basic_reshaped":   (BASIC, True),    # no complex-text layout + the recipe
}

if __name__ == "__main__":
    rows = []
    for fname, fpath in FONTS.items():
        if not Path(fpath).exists():
            print(f"  (skipping {fname}: not installed)"); continue
        for cid, text in CASES:
            # Ground truth: raqm_plain, verified BY EYE in the first run. Everything
            # is measured against it, and the contact sheet lets a human re-check.
            ref = draw(text, fpath, RAQM, False)
            miss = missing_glyphs(text, fpath)
            for pname, (engine, pre) in PATHS.items():
                im = draw(text, fpath, engine, pre)
                im.save(OUT / f"{fname}__{cid}__{pname}.png")
                iou = ink_iou(im, ref)
                rows.append({"font": fname, "case": cid, "text": text, "path": pname,
                             "iou_vs_reference": round(iou, 3),
                             # Three bands, not a pass/fail. Antialiasing across two
                             # layout engines means even a visually identical render
                             # will not reach 0.97, and a single threshold hid the
                             # most interesting result: the legacy recipe RECOVERS
                             # plain Arabic but still fails on digits, Latin runs and
                             # diacritics, because those need real shaping regardless.
                             "verdict": ("identical" if iou > 0.95 else
                                         "recognisable" if iou > 0.60 else "broken"),
                             "missing_glyphs": miss})
    (HERE / "results.jsonl").write_text(
        "\n".join(json.dumps(r, ensure_ascii=False) for r in rows) + "\n")

    print(f"\n{'path':17}{'identical':>11}{'recognisable':>14}{'broken':>9}   per-case IoU")
    for pname in PATHS:
        sub = [r for r in rows if r["path"] == pname]
        c = {v: sum(1 for r in sub if r["verdict"] == v)
             for v in ("identical", "recognisable", "broken")}
        ious = [f"{r['iou_vs_reference']:.2f}" for r in sub if r["font"] == "IBMPlexSansArabic"]
        print(f"{pname:17}{c['identical']:>11}{c['recognisable']:>14}{c['broken']:>9}   {' '.join(ious)}")
    print("\n  (per-case order: greeting · sentence · with_digits · mixed_latin · diacritics)")

    print("\nfont coverage traps:")
    seen = set()
    for r in rows:
        if r["missing_glyphs"] and (r["font"], r["case"]) not in seen:
            seen.add((r["font"], r["case"]))
            print(f"  {r['font']:20}{r['case']:13} cannot render: {' '.join(r['missing_glyphs'])}")
    if not seen:
        print("  none")