comparison make_preview.py @ 0:b5a96b547b01

initial public version
author ark
date 2026-11-03 01:29 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:b5a96b547b01
1 #!/usr/bin/env python3
2 """Render a preview PNG of a text in every installed font.
3
4 Each PNG is named after the font's PostScript name, so the file can be
5 passed to make_glyphs.py as it is. The text is drawn from the same outlines
6 the printed model uses. Optionally the glyphs get an outline band like the
7 decal of the two-colour print, with its width given in mm at the font's
8 maximum print size.
9 """
10
11 import argparse
12 import logging
13 import os
14 import re
15 import sys
16 from concurrent.futures import ProcessPoolExecutor
17
18 import numpy as np
19 from PIL import Image, ImageDraw, ImageFont
20
21 import fontlib as fl
22
23 SUPERSAMPLE = 3
24
25
26 def parse_args():
27 """Parse the command line."""
28 p = argparse.ArgumentParser(description=__doc__,
29 formatter_class=argparse.RawDescriptionHelpFormatter)
30 p.add_argument("--text", default="24", help="text to render (default: %(default)s)")
31 p.add_argument("--out", default="preview", help="output directory (default: %(default)s)")
32 p.add_argument("--list", action="store_true",
33 help="only list the fonts that pass the filters")
34 f = p.add_argument_group("filters")
35 f.add_argument("--family", help="regular expression on the family name, case-insensitive")
36 f.add_argument("--name", help="regular expression on the PostScript name, case-insensitive")
37 f.add_argument("--weight-min", type=int, help="lowest weight, 100 to 900")
38 f.add_argument("--weight-max", type=int, help="highest weight, 100 to 900")
39 f.add_argument("--italic", action=argparse.BooleanOptionalAction,
40 help="only italic (--italic) or only upright (--no-italic) faces")
41 f.add_argument("--mono", action=argparse.BooleanOptionalAction,
42 help="only monospaced (--mono) or only proportional (--no-mono) faces")
43 f.add_argument("--class", dest="cls", choices=["serif", "sans"],
44 help="only fonts classified as serif or sans-serif")
45 r = p.add_argument_group("rendering")
46 r.add_argument("--fill", default="#202020", help="glyph colour (default: %(default)s)")
47 r.add_argument("--outline", default="#c03030", help="outline colour (default: %(default)s)")
48 r.add_argument("--background", default="#f4f4f0",
49 help="background colour (default: %(default)s)")
50 r.add_argument("--band", type=float, default=0,
51 help="outline band width in mm at maximum print size, 0 for none "
52 "(default: %(default)s)")
53 r.add_argument("--layout", choices=["text", "glyph"], default="glyph",
54 help="layout whose maximum size scales the band (default: %(default)s)")
55 r.add_argument("--px", type=int, default=2000,
56 help="image size along the longer side (default: %(default)s)")
57 r.add_argument("--jobs", type=int, default=os.cpu_count(),
58 help="parallel processes (default: %(default)s)")
59 b = p.add_argument_group("printer")
60 b.add_argument("--bed", type=float, default=300, help="bed size in mm (default: %(default)s)")
61 b.add_argument("--margin", type=float, default=10,
62 help="bed margin in mm (default: %(default)s)")
63 b.add_argument("--line-width", type=float, default=.4,
64 help="line width in mm (default: %(default)s)")
65 return p.parse_args()
66
67
68 def select(args):
69 """Faces that pass the filters given on the command line.
70
71 Filters that need the font file (weight, class, missing characters) are
72 applied while rendering, see render().
73 """
74 fam = re.compile(args.family, re.I) if args.family else None
75 name = re.compile(args.name, re.I) if args.name else None
76 out = []
77 for face in fl.list_faces():
78 if fam and not fam.search(face.family):
79 continue
80 if name and not name.search(face.file_name):
81 continue
82 if args.italic is not None and face.italic != args.italic:
83 continue
84 out.append(face)
85 return out
86
87
88 def check_face(face, args):
89 """Apply the filters that need the opened font.
90
91 Returns:
92 None if the face passes, else the reason it does not.
93 """
94 if not face.has_chars(args.text):
95 return "missing characters"
96 if args.weight_min is not None and face.weight < args.weight_min:
97 return "weight"
98 if args.weight_max is not None and face.weight > args.weight_max:
99 return "weight"
100 if args.mono is not None and face.mono != args.mono:
101 return "spacing"
102 if args.cls and face.classification != args.cls:
103 return "class"
104 return None
105
106
107 def render(face_info, args):
108 """Render the preview PNG of one face.
109
110 Returns:
111 (PostScript name, None) on success, or (PostScript name, reason)
112 when the face is skipped.
113 """
114 logging.disable(logging.WARNING)
115 try:
116 face = fl.Face(face_info)
117 reason = check_face(face, args)
118 if reason:
119 return face_info.psname, reason
120 placed = face.layout(args.text)
121 except Exception as e: # damaged or unusual fonts are skipped, not fatal
122 return face_info.psname, f"error: {e}"
123 inked = [(x, g) for x, g in placed if not g.empty]
124 if not inked:
125 return face_info.psname, "no outline"
126 sizes = fl.max_sizes(placed, fl.usable_area(args.bed, args.margin, args.line_width))
127 bboxes = [g.bbox() for _, g in inked]
128 xmin = min(x + b[0] for (x, _), b in zip(inked, bboxes))
129 xmax = max(x + b[2] for (x, _), b in zip(inked, bboxes))
130 ymin = min(b[1] for b in bboxes)
131 ymax = max(b[3] for b in bboxes)
132 height = max(b[3] - b[1] for b in bboxes)
133
134 # image geometry, in supersampled pixels
135 pad = args.px // 20
136 caption_h = args.px // 14
137 k = (args.px - 2 * pad) / max(xmax - xmin, ymax - ymin)
138 w = int(round((xmax - xmin) * k)) + 2 * pad
139 h = int(round((ymax - ymin) * k)) + 2 * pad
140 ss = SUPERSAMPLE
141
142 def to_px(pts, dx):
143 return [((x + dx - xmin) * k * ss + pad * ss, (ymax - y) * k * ss + pad * ss)
144 for x, y in pts]
145
146 fill = Image.new("L", (w * ss, h * ss), 0)
147 band = Image.new("L", (w * ss, h * ss), 0)
148 for dx, g in inked:
149 for group in g.groups:
150 layer = Image.new("L", fill.size, 0)
151 d = ImageDraw.Draw(layer)
152 d.polygon(to_px(group[0], dx), fill=255)
153 for hole in group[1:]:
154 d.polygon(to_px(hole, dx), fill=0)
155 fill.paste(255, mask=layer)
156 if args.band > 0:
157 mm_px = height * k * ss / sizes[args.layout]["size0"]
158 width = max(1, int(round(2 * args.band * mm_px)))
159 d = ImageDraw.Draw(band)
160 r = width / 2
161 for line in fl.visible_runs(g.groups, face.upm / 200):
162 pts = to_px(line, dx)
163 # single segments with a disc at every point: polyline joints
164 # leave hairline gaps between nearly collinear segments
165 for p, q in zip(pts, pts[1:]):
166 d.line([p, q], fill=255, width=width)
167 for x, y in pts:
168 d.ellipse((x - r, y - r, x + r, y + r), fill=255)
169 if args.band > 0:
170 band = Image.fromarray(np.minimum(np.asarray(band), np.asarray(fill)))
171
172 img = Image.new("RGB", fill.size, args.background)
173 img.paste(Image.new("RGB", fill.size, args.fill), mask=fill)
174 if args.band > 0:
175 img.paste(Image.new("RGB", fill.size, args.outline), mask=band)
176 img = img.resize((w, h), Image.LANCZOS)
177
178 # caption below the text; narrow images are widened to fit it
179 font = ImageFont.load_default(size=caption_h // 3)
180 flags = [f"weight {face.weight}", face.classification or "unclassified"]
181 if face_info.italic:
182 flags.append("italic")
183 if face.mono:
184 flags.append("mono")
185 fill_error = max(g.fill_error for _, g in inked)
186 if fill_error > 0.001:
187 flags.append(f"OUTLINE DIFFERS FROM FONT ON {100 * fill_error:.1f}%")
188 lines = [f"{face_info.family} {face_info.style} ({face_info.psname})",
189 f"{', '.join(flags)} max size: text {sizes['text']['size0']:.0f} mm, "
190 f"glyph {sizes['glyph']['size0']:.0f} mm"]
191 text_w = max(font.getbbox(line)[2] for line in lines)
192 out_w = max(w, int(text_w) + 2 * pad)
193 out = Image.new("RGB", (out_w, h + caption_h), args.background)
194 out.paste(img, ((out_w - w) // 2, 0))
195 d = ImageDraw.Draw(out)
196 for i, line in enumerate(lines):
197 d.text((pad, h + i * caption_h * 0.42), line, fill=args.fill, font=font)
198 out.save(os.path.join(args.out, face_info.file_name + ".png"), optimize=True)
199 return face_info.psname, None
200
201
202 def main():
203 """Select the faces and render them in parallel."""
204 args = parse_args()
205 faces = select(args)
206 if args.list:
207 logging.disable(logging.WARNING)
208 for info in faces:
209 try:
210 face = fl.Face(info)
211 if check_face(face, args):
212 continue
213 except Exception:
214 continue
215 print(f"{info.file_name}\t{info.family}\t{info.style}\t"
216 f"weight {face.weight}\t{face.classification or '-'}")
217 return
218 os.makedirs(args.out, exist_ok=True)
219 done = skipped = 0
220 with ProcessPoolExecutor(max_workers=args.jobs) as pool:
221 for name, reason in pool.map(render, faces, [args] * len(faces), chunksize=4):
222 if reason is None:
223 done += 1
224 else:
225 skipped += 1
226 if reason.startswith("error"):
227 print(f"{name}: {reason}", file=sys.stderr)
228 print(f"{done} previews written to {args.out}, {skipped} faces skipped")
229
230
231 if __name__ == "__main__":
232 main()