syamjithnk commited on
Commit
a81d94d
·
verified ·
1 Parent(s): 98e5285

Upload render_bench.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. render_bench.py +159 -0
render_bench.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ArShape — when does the standard Arabic rendering recipe break Arabic?
3
+
4
+ Author: Syamjith NK
5
+
6
+ REBUILT after the first version measured the wrong thing. Recording why, because the
7
+ mistake is the finding.
8
+
9
+ I assumed Arabic needs `arabic_reshaper` + `python-bidi` applied before drawing, and
10
+ that plain rendering would come out disconnected. That is the advice you find
11
+ everywhere. Rendering it proved the opposite: on a modern text stack, plain output was
12
+ correct (مرحبا بكم) and the reshaped output was mangled (مكب ابحرم).
13
+
14
+ The reason is that Pillow 12 links **Raqm/HarfBuzz**, which already performs shaping
15
+ and the bidi algorithm. Pre-reshaping hands it text that has been shaped once and
16
+ reordered once, and it does both again. Two rights make a wrong.
17
+
18
+ So the real question is not "does Arabic need reshaping" but:
19
+
20
+ Does this rendering path ALREADY do complex-text layout?
21
+ yes -> reshaping breaks it
22
+ no -> reshaping is required
23
+
24
+ This benchmark measures that 2x2 directly, plus the font-coverage trap that bit the
25
+ first run: SFArabic.ttf has no Latin digit glyphs, so "في عام 2026" renders the digits
26
+ as .notdef boxes while looking perfectly fine to anyone not reading the numbers.
27
+ """
28
+ import json
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+ from PIL import Image, ImageDraw, ImageFont
33
+
34
+ HERE = Path(__file__).parent
35
+ OUT = HERE / "out"; OUT.mkdir(parents=True, exist_ok=True)
36
+ SIZE = (900, 170)
37
+ PT = 60
38
+
39
+ FONTS = {
40
+ "SFArabic": "/System/Library/Fonts/SFArabic.ttf",
41
+ "GeezaPro": "/System/Library/Fonts/GeezaPro.ttc",
42
+ "IBMPlexSansArabic": str(Path.home() / "Library/Fonts/IBMPlexSansArabic-Regular.ttf"),
43
+ }
44
+
45
+ CASES = [
46
+ ("greeting", "مرحبا بكم"),
47
+ ("sentence", "التزامنا بالنزاهة"),
48
+ ("with_digits", "في عام 2026"),
49
+ ("mixed_latin", "شركة Pixelogik للإنتاج"),
50
+ ("diacritics", "مَرْحَبًا بِكُمْ"),
51
+ ]
52
+
53
+
54
+ def reshape(text: str) -> str:
55
+ import arabic_reshaper
56
+ from bidi.algorithm import get_display
57
+ return get_display(arabic_reshaper.reshape(text))
58
+
59
+
60
+ def draw(text: str, font_path: str, engine, pre_reshape: bool) -> Image.Image:
61
+ if pre_reshape:
62
+ text = reshape(text)
63
+ im = Image.new("L", SIZE, 255)
64
+ f = ImageFont.truetype(font_path, PT, layout_engine=engine)
65
+ ImageDraw.Draw(im).text((SIZE[0] - 30, 45), text, font=f, fill=0, anchor="ra")
66
+ return im
67
+
68
+
69
+ def ink_iou(a: Image.Image, b: Image.Image) -> float:
70
+ """Shape similarity, INVARIANT to where the text sits.
71
+
72
+ A raw pixel IoU compares position as well as shape, and the two layout engines
73
+ place glyphs a few pixels apart. That made a visually IDENTICAL rendering score
74
+ zero - the metric could not tell "same words, different kerning" from "different
75
+ words". Crop each to its ink bounding box and normalise before comparing, so this
76
+ measures the letterforms and not the layout offset.
77
+ """
78
+ def norm(im):
79
+ arr = (np.asarray(im) < 128)
80
+ if not arr.any():
81
+ return np.zeros((64, 256), dtype=bool)
82
+ ys, xs = np.where(arr)
83
+ crop = Image.fromarray((~arr[ys.min():ys.max() + 1, xs.min():xs.max() + 1]).astype(np.uint8) * 255)
84
+ return np.asarray(crop.resize((256, 64), Image.LANCZOS)) < 128
85
+ x, y = norm(a), norm(b)
86
+ u = (x | y).sum()
87
+ return float((x & y).sum() / u) if u else 1.0
88
+
89
+
90
+ def missing_glyphs(text: str, font_path: str) -> list[str]:
91
+ """Characters the font has no glyph for. These render as .notdef boxes and are
92
+ invisible to anyone skim-reading the language they DO know."""
93
+ try:
94
+ from fontTools.ttLib import TTFont, TTCollection
95
+ f = (TTCollection(font_path).fonts[0] if font_path.endswith(".ttc")
96
+ else TTFont(font_path, fontNumber=0))
97
+ cmap = set()
98
+ for t in f["cmap"].tables:
99
+ cmap |= set(t.cmap.keys())
100
+ return [c for c in dict.fromkeys(text) if c.strip() and ord(c) not in cmap]
101
+ except Exception:
102
+ return []
103
+
104
+
105
+ RAQM = ImageFont.Layout.RAQM
106
+ BASIC = ImageFont.Layout.BASIC
107
+
108
+ PATHS = {
109
+ "raqm_plain": (RAQM, False), # modern stack, text passed through as-is
110
+ "raqm_reshaped": (RAQM, True), # modern stack + the legacy recipe
111
+ "basic_plain": (BASIC, False), # no complex-text layout, no recipe
112
+ "basic_reshaped": (BASIC, True), # no complex-text layout + the recipe
113
+ }
114
+
115
+ if __name__ == "__main__":
116
+ rows = []
117
+ for fname, fpath in FONTS.items():
118
+ if not Path(fpath).exists():
119
+ print(f" (skipping {fname}: not installed)"); continue
120
+ for cid, text in CASES:
121
+ # Ground truth: raqm_plain, verified BY EYE in the first run. Everything
122
+ # is measured against it, and the contact sheet lets a human re-check.
123
+ ref = draw(text, fpath, RAQM, False)
124
+ miss = missing_glyphs(text, fpath)
125
+ for pname, (engine, pre) in PATHS.items():
126
+ im = draw(text, fpath, engine, pre)
127
+ im.save(OUT / f"{fname}__{cid}__{pname}.png")
128
+ iou = ink_iou(im, ref)
129
+ rows.append({"font": fname, "case": cid, "text": text, "path": pname,
130
+ "iou_vs_reference": round(iou, 3),
131
+ # Three bands, not a pass/fail. Antialiasing across two
132
+ # layout engines means even a visually identical render
133
+ # will not reach 0.97, and a single threshold hid the
134
+ # most interesting result: the legacy recipe RECOVERS
135
+ # plain Arabic but still fails on digits, Latin runs and
136
+ # diacritics, because those need real shaping regardless.
137
+ "verdict": ("identical" if iou > 0.95 else
138
+ "recognisable" if iou > 0.60 else "broken"),
139
+ "missing_glyphs": miss})
140
+ (HERE / "results.jsonl").write_text(
141
+ "\n".join(json.dumps(r, ensure_ascii=False) for r in rows) + "\n")
142
+
143
+ print(f"\n{'path':17}{'identical':>11}{'recognisable':>14}{'broken':>9} per-case IoU")
144
+ for pname in PATHS:
145
+ sub = [r for r in rows if r["path"] == pname]
146
+ c = {v: sum(1 for r in sub if r["verdict"] == v)
147
+ for v in ("identical", "recognisable", "broken")}
148
+ ious = [f"{r['iou_vs_reference']:.2f}" for r in sub if r["font"] == "IBMPlexSansArabic"]
149
+ print(f"{pname:17}{c['identical']:>11}{c['recognisable']:>14}{c['broken']:>9} {' '.join(ious)}")
150
+ print("\n (per-case order: greeting · sentence · with_digits · mixed_latin · diacritics)")
151
+
152
+ print("\nfont coverage traps:")
153
+ seen = set()
154
+ for r in rows:
155
+ if r["missing_glyphs"] and (r["font"], r["case"]) not in seen:
156
+ seen.add((r["font"], r["case"]))
157
+ print(f" {r['font']:20}{r['case']:13} cannot render: {' '.join(r['missing_glyphs'])}")
158
+ if not seen:
159
+ print(" none")