blys 0.1.0__tar.gz

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.
Files changed (37) hide show
  1. blys-0.1.0/.github/workflows/publish-release.yml +82 -0
  2. blys-0.1.0/.github/workflows/test.yml +45 -0
  3. blys-0.1.0/LICENSE +201 -0
  4. blys-0.1.0/Lib/blys/__init__.py +10 -0
  5. blys-0.1.0/Lib/blys/dataset.py +318 -0
  6. blys-0.1.0/Lib/blys/font.py +110 -0
  7. blys-0.1.0/Lib/blys/googlefonts.py +346 -0
  8. blys-0.1.0/Lib/blys/pkbar.py +270 -0
  9. blys-0.1.0/Lib/blys/render.py +306 -0
  10. blys-0.1.0/Lib/blys/utils.py +238 -0
  11. blys-0.1.0/Lib/blys.egg-info/PKG-INFO +223 -0
  12. blys-0.1.0/Lib/blys.egg-info/SOURCES.txt +35 -0
  13. blys-0.1.0/Lib/blys.egg-info/dependency_links.txt +1 -0
  14. blys-0.1.0/Lib/blys.egg-info/requires.txt +14 -0
  15. blys-0.1.0/Lib/blys.egg-info/top_level.txt +1 -0
  16. blys-0.1.0/PKG-INFO +223 -0
  17. blys-0.1.0/README.md +200 -0
  18. blys-0.1.0/pyproject.toml +33 -0
  19. blys-0.1.0/setup.cfg +4 -0
  20. blys-0.1.0/tests/dummy_repo/ofl/abeezee/ABeeZee-Italic.ttf +0 -0
  21. blys-0.1.0/tests/dummy_repo/ofl/abeezee/ABeeZee-Regular.ttf +0 -0
  22. blys-0.1.0/tests/dummy_repo/ofl/abeezee/DESCRIPTION.en_us.html +6 -0
  23. blys-0.1.0/tests/dummy_repo/ofl/abeezee/FONTLOG.txt +56 -0
  24. blys-0.1.0/tests/dummy_repo/ofl/abeezee/METADATA.pb +44 -0
  25. blys-0.1.0/tests/dummy_repo/ofl/abeezee/OFL.txt +93 -0
  26. blys-0.1.0/tests/dummy_repo/ofl/abeezee/upstream_info.md +48 -0
  27. blys-0.1.0/tests/dummy_repo/ofl/roboto/DESCRIPTION.en_us.html +16 -0
  28. blys-0.1.0/tests/dummy_repo/ofl/roboto/METADATA.pb +57 -0
  29. blys-0.1.0/tests/dummy_repo/ofl/roboto/OFL.txt +93 -0
  30. blys-0.1.0/tests/dummy_repo/ofl/roboto/Roboto-Italic[wdth,wght].ttf +0 -0
  31. blys-0.1.0/tests/dummy_repo/ofl/roboto/Roboto[wdth,wght].ttf +0 -0
  32. blys-0.1.0/tests/dummy_repo/ofl/roboto/config.yaml +5 -0
  33. blys-0.1.0/tests/dummy_repo/ofl/roboto/upstream_info.md +15 -0
  34. blys-0.1.0/tests/dummy_repo/tags/all/families.csv +25066 -0
  35. blys-0.1.0/tests/test_googlefonts.py +30 -0
  36. blys-0.1.0/tests/test_googlefonts_dummy_repo.py +30 -0
  37. blys-0.1.0/tests/test_render.py +103 -0
@@ -0,0 +1,82 @@
1
+ on:
2
+ push:
3
+ tags:
4
+ - "v*" # Push events to matching `v*` version srings. e.g. v1.0, v20.15.10
5
+
6
+ name: Create and Publish Release
7
+
8
+ jobs:
9
+ build:
10
+ name: Build distribution
11
+ runs-on: ubuntu-latest
12
+ permissions:
13
+ contents: write
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ with:
17
+ submodules: recursive
18
+ fetch-depth: 0
19
+ - name: Set up Python
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: '3.x'
23
+
24
+ - name: Install release dependencies
25
+ run: |
26
+ python -m pip install --upgrade pip
27
+ pip install --upgrade setuptools wheel build
28
+
29
+ - name: Get release notes
30
+ id: release_notes
31
+ run: |
32
+ # By default, GH Actions checkout will only fetch a single commit.
33
+ # For us to extract the release notes, we need to fetch the tags
34
+ # and tag annotations as well.
35
+ # https://github.com/actions/checkout/issues/290
36
+ git fetch --tags --force
37
+ TAG_NAME=${GITHUB_REF/refs\/tags\//}
38
+ echo "$(git tag -l --format='%(contents)' $TAG_NAME)" > "${{ runner.temp }}/CHANGELOG.md"
39
+
40
+ - name: Create GitHub release
41
+ id: create_release
42
+ uses: actions/create-release@v1
43
+ env:
44
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
45
+ with:
46
+ tag_name: ${{ github.ref }}
47
+ release_name: ${{ github.ref }}
48
+ body_path: "${{ runner.temp }}/CHANGELOG.md"
49
+ draft: false
50
+ prerelease: false
51
+
52
+ - name: Build a binary wheel and a source tarball
53
+ run: python3 -m build
54
+ - name: Store the distribution packages
55
+ uses: actions/upload-artifact@v4
56
+ with:
57
+ name: python-package-distributions
58
+ path: dist/
59
+
60
+ publish-to-pypi:
61
+ name: >-
62
+ Publish Python 🐍 distribution 📦 to PyPI
63
+ if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes
64
+ needs:
65
+ - build
66
+ runs-on: ubuntu-latest
67
+ environment:
68
+ name: pypi
69
+ url: https://pypi.org/p/torchfont
70
+ permissions:
71
+ id-token: write # IMPORTANT: mandatory for trusted publishing
72
+ steps:
73
+ - name: Download all the dists
74
+ uses: actions/download-artifact@v4
75
+ with:
76
+ name: python-package-distributions
77
+ path: dist/
78
+ - name: Publish distribution 📦 to PyPI
79
+ uses: pypa/gh-action-pypi-publish@release/v1
80
+ with:
81
+ # repository-url: https://test.pypi.org/legacy/ # for testing purposes
82
+ verify-metadata: false # twine previously didn't verify metadata when uploading
@@ -0,0 +1,45 @@
1
+ name: Test
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ${{ matrix.platform }}
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ python-version: ["3.11", "3.12", "3.13"]
16
+ platform: [ubuntu-latest, windows-latest]
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ with:
20
+ submodules: recursive
21
+ fetch-depth: 0
22
+ - name: Set up Python ${{ matrix.python-version }}
23
+ uses: actions/setup-python@v5
24
+ with:
25
+ python-version: ${{ matrix.python-version }}
26
+ - name: Install packages
27
+ run: |
28
+ pip install '.[test]'
29
+ pip install black
30
+ - name: lint
31
+ run: |
32
+ black . --check --diff --color
33
+ - name: Check out Google Fonts
34
+ uses: actions/checkout@v6
35
+ with:
36
+ repository: google/fonts
37
+ submodules: recursive
38
+ fetch-depth: 0
39
+ path: google-fonts
40
+ - name: Run Tests
41
+ run: |
42
+ pytest tests/*.py
43
+ shell: bash
44
+ env:
45
+ GOOGLE_FONTS_DIR: ${{ github.workspace }}/google-fonts
blys-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -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"]
@@ -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