blys 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
blys/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """blys package.
2
+
3
+ Utilities for loading fonts, building PyTorch datasets, rendering glyph rasters,
4
+ and running repeatable training loops for font-focused ML tasks.
5
+ """
6
+
7
+ from .utils import TrainingLoop
8
+ from .googlefonts import GoogleFonts
9
+
10
+ __all__ = ["TrainingLoop", "GoogleFonts"]
blys/dataset.py ADDED
@@ -0,0 +1,318 @@
1
+ """Dataset construction helpers for font ML tasks.
2
+
3
+ This module provides train/test splitting at the family level and dataset/sampler
4
+ utilities that emit either codepoint-level items or glyph-index-level items.
5
+ """
6
+
7
+ from collections import defaultdict
8
+ import math
9
+ import random
10
+ from typing import Callable, Optional, Sequence, Set
11
+
12
+ import torch
13
+ import uharfbuzz as hb
14
+ from glyphsets import GlyphSet, unicodes_per_glyphset
15
+ from sklearn.model_selection import train_test_split
16
+ from torch.utils.data import BatchSampler, DataLoader
17
+ from torch.utils.data import Dataset as TorchDataset
18
+
19
+ from blys.googlefonts import GoogleFonts
20
+
21
+ LATIN_CORE = [x for x in GlyphSet("GF_Latin_Core").get_characters() if x != 32]
22
+ # Skip combining characters
23
+ LATIN_CORE = [x for x in LATIN_CORE if not (0x0300 <= x <= 0x036F)]
24
+
25
+ kernel_glyphs = unicodes_per_glyphset("GF_Latin_Kernel")
26
+ assert kernel_glyphs is not None
27
+ LATIN_KERNEL = [x for x in kernel_glyphs if x != 32]
28
+ # Skip combining characters
29
+ LATIN_KERNEL = [x for x in LATIN_KERNEL if not (0x0300 <= x <= 0x036F)]
30
+
31
+
32
+ def _hb_font_for_face(face):
33
+ """Construct a HarfBuzz Font object for a face."""
34
+ return getattr(hb, "Font")(face)
35
+
36
+
37
+ class DatasetMaker:
38
+ """Create train/test splits and loaders over glyph rendering items."""
39
+
40
+ def __init__(
41
+ self,
42
+ repo_url: str,
43
+ batch_size: int,
44
+ having: Optional[Set[int]] = None,
45
+ target_codepoints: Optional[Set[int]] = None,
46
+ canary_size: Optional[int] = None,
47
+ image_size: int = 128,
48
+ split_seed: int = 1234,
49
+ ):
50
+ self.target_codepoints = set(target_codepoints) if target_codepoints else None
51
+ having_filter: Optional[Set[int]] = None
52
+ if having is not None:
53
+ having_filter = set(having)
54
+ if self.target_codepoints is not None:
55
+ having_filter = (
56
+ set(self.target_codepoints)
57
+ if having_filter is None
58
+ else having_filter | self.target_codepoints
59
+ )
60
+
61
+ self.googlefonts = GoogleFonts(repo_url, having=having_filter)
62
+ self.batch_size = batch_size
63
+ self.image_size = image_size
64
+ self.split_seed = split_seed
65
+ # Keep data-order randomization reproducible without forcing fixed batches.
66
+ self._train_loader_generator = torch.Generator()
67
+ self._train_loader_generator.manual_seed(self.split_seed + 1)
68
+ self._test_loader_generator = torch.Generator()
69
+ self._test_loader_generator.manual_seed(self.split_seed + 2)
70
+
71
+ # Test chars are a random split from GF Latin Core.
72
+ _, self.test_latincore_chars = train_test_split(
73
+ LATIN_CORE,
74
+ random_state=self.split_seed,
75
+ )
76
+
77
+ if canary_size is not None:
78
+ fonts = self.googlefonts.fonts[:canary_size]
79
+ else:
80
+ fonts = self.googlefonts.fonts
81
+
82
+ self.train_fonts, self.test_fonts = self._split_fonts_by_family(
83
+ fonts,
84
+ split_seed=self.split_seed,
85
+ )
86
+ print("Train fonts:", len(self.train_fonts))
87
+ print("Test fonts:", len(self.test_fonts))
88
+
89
+ @staticmethod
90
+ def _split_fonts_by_family(fonts, *, split_seed: int):
91
+ """Split fonts into train/test by family to avoid cross-style leakage."""
92
+ if len(fonts) < 2:
93
+ return list(fonts), []
94
+
95
+ family_to_fonts = defaultdict(list)
96
+ for font in fonts:
97
+ family_to_fonts[font.family].append(font)
98
+
99
+ families = sorted(family_to_fonts.keys())
100
+ if len(families) < 2:
101
+ # If only one family is available, keep current behaviour and avoid empty train.
102
+ return list(fonts), []
103
+
104
+ train_families, test_families = train_test_split(
105
+ families,
106
+ random_state=split_seed,
107
+ )
108
+
109
+ train_family_set = set(train_families)
110
+ test_family_set = set(test_families)
111
+
112
+ train_fonts = [
113
+ font for family in train_family_set for font in family_to_fonts[family]
114
+ ]
115
+ test_fonts = [
116
+ font for family in test_family_set for font in family_to_fonts[family]
117
+ ]
118
+ return train_fonts, test_fonts
119
+
120
+ def train_set(self):
121
+ """Return the training dataset for this maker.
122
+
123
+ Subclasses can override this to emit task-specific item structures.
124
+ """
125
+ return Dataset(
126
+ self.train_fonts, codepoint_filter_fn=self.train_codepoint_filter
127
+ )
128
+
129
+ def test_set(self):
130
+ """Return the test/validation dataset for this maker."""
131
+ return Dataset(self.test_fonts, codepoint_filter_fn=self.test_codepoint_filter)
132
+
133
+ def train_codepoint_filter(self, font_codepoints: Set[int]) -> Set[int]:
134
+ """Filter a font's codepoints for training.
135
+
136
+ By default this excludes the held-out Latin Core split, unless
137
+ ``target_codepoints`` was provided, in which case only those are kept.
138
+ """
139
+ if self.target_codepoints is not None:
140
+ return set(font_codepoints) & self.target_codepoints
141
+ return set(font_codepoints) - set(self.test_latincore_chars)
142
+
143
+ def test_codepoint_filter(self, font_codepoints: Set[int]) -> Set[int]:
144
+ """Filter a font's codepoints for testing.
145
+
146
+ By default this keeps only the held-out Latin Core split, unless
147
+ ``target_codepoints`` was provided, in which case only those are kept.
148
+ """
149
+ if self.target_codepoints is not None:
150
+ return set(font_codepoints) & self.target_codepoints
151
+ return set(font_codepoints) & set(self.test_latincore_chars)
152
+
153
+ def train_loader(self):
154
+ """Build the shuffled training ``DataLoader`` with deterministic RNG."""
155
+ return DataLoader(
156
+ self.train_set(),
157
+ batch_size=self.batch_size,
158
+ shuffle=True,
159
+ generator=self._train_loader_generator,
160
+ drop_last=True,
161
+ collate_fn=self.collate_fn,
162
+ )
163
+
164
+ def test_loader(self):
165
+ """Build the shuffled test ``DataLoader`` with deterministic RNG."""
166
+ return DataLoader(
167
+ self.test_set(),
168
+ batch_size=self.batch_size,
169
+ shuffle=True,
170
+ generator=self._test_loader_generator,
171
+ drop_last=True,
172
+ collate_fn=self.collate_fn,
173
+ )
174
+
175
+ def collate_fn(self, batch):
176
+ """Collate a batch into model inputs/targets.
177
+
178
+ Must be implemented by subclasses that know the task-specific tensor
179
+ layout and metadata packing.
180
+ """
181
+ raise NotImplementedError("Base DatasetMaker does not implement collate_fn")
182
+
183
+
184
+ class Dataset(TorchDataset):
185
+ """Dataset over (font, char) pairs for codepoint-level tasks.
186
+
187
+ Returns items of the form {"font": font, "char": char} where char is a Unicode
188
+ codepoint integer. The dataset is filtered by the provided codepoint_filter_fn,
189
+ which takes the set of codepoints available in a font and returns the subset to
190
+ include in the dataset.
191
+ """
192
+
193
+ def __init__(self, fonts, codepoint_filter_fn: Callable[[Set[int]], Set[int]]):
194
+ """Initialize a codepoint-level dataset over the provided fonts."""
195
+ self.fonts = fonts
196
+ self.codepoint_filter_fn = codepoint_filter_fn
197
+ self.order = []
198
+ for font in self.fonts:
199
+ chars = self.codepoint_filter_fn(set(font.codepoints))
200
+ for char in chars:
201
+ # Skip empty glyphs; they can destabilize training targets.
202
+ if font.has_non_empty_codepoint(char):
203
+ self.order.append((font, char))
204
+
205
+ def __len__(self):
206
+ """Return number of (font, codepoint) items."""
207
+ return len(self.order)
208
+
209
+ def __getitem__(self, idx):
210
+ """Return one sample dictionary containing ``char`` and ``font``."""
211
+ font, char = self.order[idx]
212
+ return {
213
+ "char": char,
214
+ "font": font,
215
+ }
216
+
217
+
218
+ class AllGidsDataset(TorchDataset):
219
+ """Dataset over all GIDs in the font, used for glyph-level tasks.
220
+
221
+ Returns items of the form {"font": font, "gid": gid} where gid is a glyph index. The
222
+ dataset includes all GIDs for which the font has a non-empty outline, regardless of
223
+ codepoint coverage.
224
+ """
225
+
226
+ def __init__(self, fonts):
227
+ """Initialize a glyph-index dataset over all non-empty outlines."""
228
+ self.fonts = fonts
229
+ self.order = []
230
+ for font in self.fonts:
231
+ for gid in range(1, font.hb_face.glyph_count):
232
+ # Skip empty glyphs; they can destabilize training targets.
233
+ if font.has_non_empty_gid(gid):
234
+ self.order.append((font, gid))
235
+
236
+ def __len__(self):
237
+ """Return number of (font, gid) items."""
238
+ return len(self.order)
239
+
240
+ def __getitem__(self, idx):
241
+ """Return one sample dictionary containing ``gid`` and ``font``."""
242
+ font, gid = self.order[idx]
243
+ return {
244
+ "gid": gid,
245
+ "font": font,
246
+ }
247
+
248
+
249
+ class ClassBalancedBatchSampler(BatchSampler):
250
+ """Batch sampler that balances font classes within each emitted batch."""
251
+
252
+ def __init__(
253
+ self,
254
+ order: Sequence[tuple],
255
+ *,
256
+ batch_size: int,
257
+ drop_last: bool,
258
+ ) -> None:
259
+ if batch_size <= 0:
260
+ raise ValueError(f"batch_size must be positive, got {batch_size}")
261
+ if len(order) == 0:
262
+ raise ValueError("Cannot build class-balanced sampler for empty dataset")
263
+
264
+ self.batch_size = batch_size
265
+ self.drop_last = drop_last
266
+ self.dataset_size = len(order)
267
+
268
+ class_to_indices: dict[str, list[int]] = {}
269
+ for idx, (font, _char) in enumerate(order):
270
+ cls = font.classification()
271
+ class_to_indices.setdefault(cls, []).append(idx)
272
+
273
+ if not class_to_indices:
274
+ raise ValueError("No classes found for class-balanced sampling")
275
+
276
+ self.class_to_indices = class_to_indices
277
+ self.classes = sorted(class_to_indices.keys())
278
+
279
+ def __len__(self) -> int:
280
+ """Return the number of batches emitted per epoch-like pass."""
281
+ if self.drop_last:
282
+ return self.dataset_size // self.batch_size
283
+ return math.ceil(self.dataset_size / self.batch_size)
284
+
285
+ def __iter__(self):
286
+ """Yield index batches with near-uniform class presence per batch."""
287
+ num_classes = len(self.classes)
288
+ num_batches = len(self)
289
+
290
+ class_cursor = random.randrange(num_classes)
291
+
292
+ for _ in range(num_batches):
293
+ batch_indices: list[int] = []
294
+
295
+ if num_classes <= self.batch_size:
296
+ base = self.batch_size // num_classes
297
+ remainder = self.batch_size % num_classes
298
+ class_order = self.classes[:]
299
+ random.shuffle(class_order)
300
+
301
+ for cls in class_order:
302
+ indices = self.class_to_indices[cls]
303
+ for _ in range(base):
304
+ batch_indices.append(random.choice(indices))
305
+
306
+ for cls in class_order[:remainder]:
307
+ batch_indices.append(random.choice(self.class_to_indices[cls]))
308
+ else:
309
+ selected_classes = [
310
+ self.classes[(class_cursor + i) % num_classes]
311
+ for i in range(self.batch_size)
312
+ ]
313
+ class_cursor = (class_cursor + self.batch_size) % num_classes
314
+ for cls in selected_classes:
315
+ batch_indices.append(random.choice(self.class_to_indices[cls]))
316
+
317
+ random.shuffle(batch_indices)
318
+ yield batch_indices
blys/font.py ADDED
@@ -0,0 +1,110 @@
1
+ """Font abstractions shared by Google Fonts-backed and standalone fonts."""
2
+
3
+ from functools import cached_property
4
+ import itertools
5
+ from pathlib import Path
6
+ from typing import Dict, List, Optional, Set
7
+ import uharfbuzz as hb
8
+
9
+ import numpy as np
10
+
11
+ from fontTools.ttLib import TTFont
12
+ from blys.render import render_gid
13
+
14
+
15
+ class Font:
16
+ """A font, whether standalone or from the Google Fonts repository. This is an abstract base class that defines the interface for fonts, and provides some common functionality. The concrete implementations are GoogleFont and StandaloneFont."""
17
+
18
+ hb_face: hb.Face
19
+ path: Path
20
+
21
+ def render_char(
22
+ self, char: int, size: int = 64, axis_position: Optional[List[float]] = None
23
+ ) -> np.ndarray:
24
+ """Render one Unicode codepoint as a CHW float image.
25
+
26
+ Returns an all-ones fallback image if shaping or rasterization fails.
27
+ """
28
+ try:
29
+ gid = hb.Font(self.hb_face).get_nominal_glyph(char)
30
+ return self.render_gid(gid, size, axis_position=axis_position)
31
+ except Exception:
32
+ return np.ones((3, size, size), dtype=np.float32)
33
+
34
+ def render_gid(
35
+ self, gid: int, size: int = 64, axis_position: Optional[List[float]] = None
36
+ ) -> np.ndarray:
37
+ """Render one glyph index (GID) as a CHW float image.
38
+
39
+ Returns an all-ones fallback image if rasterization fails.
40
+ """
41
+ try:
42
+ axis_tuple = tuple(axis_position) if axis_position is not None else None
43
+ return render_gid(self.path, gid, size, axis_position=axis_tuple)
44
+ except Exception:
45
+ return np.ones((3, size, size), dtype=np.float32)
46
+
47
+ @cached_property
48
+ def codepoints(self) -> Set[int]:
49
+ """Unicode codepoints present in this font."""
50
+ return set(self.hb_face.unicodes)
51
+
52
+ def has_codepoint(self, char: int) -> bool:
53
+ """Return whether this font contains a glyph for ``char``."""
54
+ return char in self.codepoints
55
+
56
+ def description(self) -> str:
57
+ """Empty description — no metadata available for standalone fonts."""
58
+ return ""
59
+
60
+ def tags(self) -> Dict[str, float]:
61
+ """Empty tags — no metadata available for standalone fonts."""
62
+ return {}
63
+
64
+ def classification(self) -> str:
65
+ """Coarse style classification used for bucketed training metrics."""
66
+ return "UNKNOWN"
67
+
68
+ def sample_axis_positions(self, splits: int = 5) -> List[List[float]]:
69
+ """Sample variable-axis user-space coordinates.
70
+
71
+ If the font is not variable, returns ``[[]]``. Otherwise this returns
72
+ a list containing the default ``[]`` plus a Cartesian-product grid of up
73
+ to the first five fvar axes, each split into ``splits`` values.
74
+ """
75
+ if "fvar" not in self.hb_face.table_tags:
76
+ return [[]]
77
+ # Slow path
78
+ ttfont = TTFont(self.path)
79
+ axes = {
80
+ ix: np.linspace(axis.minValue, axis.maxValue, splits).tolist()
81
+ for ix, axis in enumerate(ttfont["fvar"].axes[0:5])
82
+ # Use first five axes to stop things like Amstelvar dominating the dataset
83
+ }
84
+ # Take Cartesian product, convert each set of coordinates to list in order
85
+ tags = axes.keys()
86
+ instances = itertools.product(*axes.values())
87
+ instances = [[instance[ix] for ix in tags] for instance in instances]
88
+ return [[]] + instances
89
+
90
+ def has_non_empty_codepoint(self, codepoint: int) -> bool:
91
+ """Return True if the font has a non-empty outline for codepoint."""
92
+ if not self.has_codepoint(codepoint):
93
+ return False
94
+ if not hasattr(self, "hb_face"):
95
+ # Test doubles and lightweight mocks may not expose HarfBuzz handles.
96
+ return True
97
+ hb_font = hb.Font(self.hb_face) # type: ignore
98
+ gid = hb_font.get_nominal_glyph(codepoint)
99
+ return self.has_non_empty_gid(gid)
100
+
101
+ def has_non_empty_gid(self, gid: int) -> bool:
102
+ """Return True if the font has a non-empty outline for the given gid."""
103
+ if not hasattr(self, "hb_face"):
104
+ # Test doubles and lightweight mocks may not expose HarfBuzz handles.
105
+ return True
106
+ hb_font = hb.Font(self.hb_face) # type: ignore
107
+ extents = hb_font.get_glyph_extents(gid)
108
+ if extents is None:
109
+ return False
110
+ return not all(x == 0 for x in extents)