HindiText-Pilot / src /diag /verify_shaping.py
sinhal's picture
Add pilot dataset: 4,000 shaped Devanagari samples + masks, fonts, generator (part 14)
24e04bb verified
Raw History Blame Contribute Delete
3.01 kB
"""Prove HarfBuzz shaping is active. Without it a dataset looks fine at a
glance but teaches the model wrong letterforms, so this gate runs first."""
import sys, pathlib
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from render.shaper import load_face
def pick_font() -> str:
"""Prefer a project font so this runs anywhere; fall back to a system one."""
for cand in ("fonts/NotoSansDevanagari-Variable.ttf",
"fonts/Mukta-Regular.ttf"):
if pathlib.Path(cand).exists():
return cand
ok = pathlib.Path("configs/fonts_ok.txt")
if ok.exists():
for line in ok.read_text(encoding="utf-8").split():
p = pathlib.Path("fonts") / line
if p.exists():
return str(p)
for cand in (r"C:\Windows\Fonts\Nirmala.ttc",
"/usr/share/fonts/truetype/lohit-devanagari/Lohit-Devanagari.ttf"):
if pathlib.Path(cand).exists():
return cand
raise SystemExit("no Devanagari font found -- run src/diag/get_fonts.py first")
FONT = pick_font()
print(f"font: {FONT}\n")
face = load_face(FONT, 64)
CASES = [
# (text, description, expectation)
("कि", "pre-base matra (i)", "ि must render LEFT of क"),
("क्ष", "conjunct ksha", "3 codepoints -> fewer glyphs (ligature)"),
("त्र", "conjunct tra", "3 codepoints -> fewer glyphs"),
("ज्ञ", "conjunct gya", "3 codepoints -> fewer glyphs"),
("हिन्दी", "word: Hindi", "reorder + conjunct + matras"),
("स्त्री", "3-consonant cluster", "stri"),
]
print(f"{'text':<8} {'cps':>4} {'glyphs':>7} {'x-offsets':<28} note")
print("-" * 88)
ok = True
for text, desc, exp in CASES:
g = face.shape(text)
xs, pen = [], 0.0
for gl in g:
xs.append(round(pen + gl.x_off, 1)); pen += gl.x_adv
clusters = [gl.cluster for gl in g]
print(f"{text:<8} {len(text):>4} {len(g):>7} {str(xs):<28} {desc}")
if text == "कि":
gid_ka = face.ft.get_char_index("क")
# Logical order is क then ि; shaped output must put the matra glyph
# first. The base consonant landing SECOND is the reordering signal.
# Do NOT compare the matra glyph to its cmap value: fonts substitute
# contextual variants of ि (hook length matched to the following
# consonant), so Noto returns gid 545 where cmap says 32 while
# shaping perfectly correctly.
if not (len(g) == 2 and g[1].gid == gid_ka and g[0].gid != gid_ka):
print(f" FAIL: no reorder -- base क (gid {gid_ka}) should be 2nd, "
f"got {[x.gid for x in g]}"); ok = False
if text in ("क्ष", "त्र", "ज्ञ") and len(g) >= len(text):
print(f" WARN: no ligature formed ({len(g)} glyphs for {len(text)} cps)")
print("-" * 88)
print("SHAPING ACTIVE" if ok else "SHAPING BROKEN")