File size: 4,661 Bytes
24e04bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Correct Devanagari text rendering: HarfBuzz shaping + FreeType rasterization.

Pillow's bundled build has no Raqm, so ImageDraw.text() renders Devanagari
unshaped -- conjuncts break apart and pre-base matras (ि) land on the wrong
side. Everything here goes through HarfBuzz so the glyph stream is what a
real text engine would produce.
"""
from __future__ import annotations

import functools
from dataclasses import dataclass

import freetype
import numpy as np
import uharfbuzz as hb
from PIL import Image

# FreeType 26.6 fixed point -> pixels
F26_6 = 64.0


@dataclass
class ShapedGlyph:
    gid: int
    x_off: float
    y_off: float
    x_adv: float
    cluster: int


class Face:
    """A font face wired up for both HarfBuzz (shaping) and FreeType (raster)."""

    def __init__(self, path: str, px: int, face_index: int = 0):
        self.path = path
        self.px = px
        with open(path, "rb") as fh:
            data = fh.read()
        self.hb_face = hb.Face(data, face_index)
        self.hb_font = hb.Font(self.hb_face)
        # HarfBuzz works in font units scaled to px; match FreeType's 26.6 grid.
        self.hb_font.scale = (px * 64, px * 64)
        hb.ot_font_set_funcs(self.hb_font)

        self.ft = freetype.Face(path, index=face_index)
        self.ft.set_pixel_sizes(0, px)

    def shape(self, text: str, script: str = "Deva", language: str = "hi",
              features: dict | None = None) -> list[ShapedGlyph]:
        buf = hb.Buffer()
        buf.add_str(text)
        buf.direction = "ltr"
        buf.script = script
        buf.language = language
        # guess_segment_properties would also work, but being explicit means a
        # missing script tag can't silently disable Devanagari shaping rules.
        hb.shape(self.hb_font, buf, features)
        return [
            ShapedGlyph(i.codepoint, p.x_offset / F26_6, p.y_offset / F26_6,
                        p.x_advance / F26_6, i.cluster)
            for i, p in zip(buf.glyph_infos, buf.glyph_positions)
        ]

    def covers(self, text: str) -> bool:
        """True if every non-space codepoint has a real glyph in this face."""
        for ch in text:
            if ch.isspace():
                continue
            if self.ft.get_char_index(ch) == 0:
                return False
        return True


def render_line(face: Face, text: str, pad: int = 8) -> tuple[Image.Image, dict]:
    """Render one line to a tight grayscale coverage mask (255 = ink).

    Returns the mask plus metrics describing where the baseline ended up, so
    callers can compose without re-deriving it.
    """
    glyphs = face.shape(text)
    if not glyphs:
        return Image.new("L", (1, 1), 0), {"baseline": 0, "width": 0}

    # Pass 1: measure the real ink box. Devanagari routinely overshoots the
    # nominal ascender (ै, ॉ) and descender (ु, ृ), so trusting font metrics
    # alone clips diacritics -- which is precisely what we cannot afford.
    pen_x = 0.0
    x0 = y0 = 1e9
    x1 = y1 = -1e9
    placed = []
    for g in glyphs:
        face.ft.load_glyph(g.gid, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_NORMAL)
        bmp = face.ft.glyph.bitmap
        left = face.ft.glyph.bitmap_left
        top = face.ft.glyph.bitmap_top
        gx = pen_x + g.x_off + left
        gy = -(g.y_off) - top  # y grows downward in image space
        if bmp.width and bmp.rows:
            buf = np.array(bmp.buffer, dtype=np.uint8)
            # FreeType rows are padded to `pitch`; slice the real width back out.
            arr = buf.reshape(bmp.rows, bmp.pitch)[:, : bmp.width].copy()
            placed.append((arr, gx, gy))
            x0 = min(x0, gx); y0 = min(y0, gy)
            x1 = max(x1, gx + bmp.width); y1 = max(y1, gy + bmp.rows)
        pen_x += g.x_adv

    if not placed:
        return Image.new("L", (1, 1), 0), {"baseline": 0, "width": 0}

    w = int(np.ceil(x1 - x0)) + 2 * pad
    h = int(np.ceil(y1 - y0)) + 2 * pad
    canvas = np.zeros((h, w), dtype=np.uint16)

    for arr, gx, gy in placed:
        px = int(round(gx - x0)) + pad
        py = int(round(gy - y0)) + pad
        sub = canvas[py : py + arr.shape[0], px : px + arr.shape[1]]
        if sub.shape != arr.shape:  # defensive: rounding at the edge
            continue
        np.maximum(sub, arr, out=sub)

    mask = Image.fromarray(np.clip(canvas, 0, 255).astype(np.uint8), "L")
    return mask, {"baseline": int(round(-y0)) + pad, "width": w, "height": h,
                  "advance": pen_x, "n_glyphs": len(glyphs)}


@functools.lru_cache(maxsize=64)
def load_face(path: str, px: int, index: int = 0) -> Face:
    return Face(path, px, index)