view make_preview.py @ 0:b5a96b547b01

initial public version
author ark
date 2026-11-03 01:29 +0100
parents
children
line wrap: on
line source

#!/usr/bin/env python3
"""Render a preview PNG of a text in every installed font.

Each PNG is named after the font's PostScript name, so the file can be
passed to make_glyphs.py as it is. The text is drawn from the same outlines
the printed model uses. Optionally the glyphs get an outline band like the
decal of the two-colour print, with its width given in mm at the font's
maximum print size.
"""

import argparse
import logging
import os
import re
import sys
from concurrent.futures import ProcessPoolExecutor

import numpy as np
from PIL import Image, ImageDraw, ImageFont

import fontlib as fl

SUPERSAMPLE = 3


def parse_args():
    """Parse the command line."""
    p = argparse.ArgumentParser(description=__doc__,
                                formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--text", default="24", help="text to render (default: %(default)s)")
    p.add_argument("--out", default="preview", help="output directory (default: %(default)s)")
    p.add_argument("--list", action="store_true",
                   help="only list the fonts that pass the filters")
    f = p.add_argument_group("filters")
    f.add_argument("--family", help="regular expression on the family name, case-insensitive")
    f.add_argument("--name", help="regular expression on the PostScript name, case-insensitive")
    f.add_argument("--weight-min", type=int, help="lowest weight, 100 to 900")
    f.add_argument("--weight-max", type=int, help="highest weight, 100 to 900")
    f.add_argument("--italic", action=argparse.BooleanOptionalAction,
                   help="only italic (--italic) or only upright (--no-italic) faces")
    f.add_argument("--mono", action=argparse.BooleanOptionalAction,
                   help="only monospaced (--mono) or only proportional (--no-mono) faces")
    f.add_argument("--class", dest="cls", choices=["serif", "sans"],
                   help="only fonts classified as serif or sans-serif")
    r = p.add_argument_group("rendering")
    r.add_argument("--fill", default="#202020", help="glyph colour (default: %(default)s)")
    r.add_argument("--outline", default="#c03030", help="outline colour (default: %(default)s)")
    r.add_argument("--background", default="#f4f4f0",
                   help="background colour (default: %(default)s)")
    r.add_argument("--band", type=float, default=0,
                   help="outline band width in mm at maximum print size, 0 for none "
                        "(default: %(default)s)")
    r.add_argument("--layout", choices=["text", "glyph"], default="glyph",
                   help="layout whose maximum size scales the band (default: %(default)s)")
    r.add_argument("--px", type=int, default=2000,
                   help="image size along the longer side (default: %(default)s)")
    r.add_argument("--jobs", type=int, default=os.cpu_count(),
                   help="parallel processes (default: %(default)s)")
    b = p.add_argument_group("printer")
    b.add_argument("--bed", type=float, default=300, help="bed size in mm (default: %(default)s)")
    b.add_argument("--margin", type=float, default=10,
                   help="bed margin in mm (default: %(default)s)")
    b.add_argument("--line-width", type=float, default=.4,
                   help="line width in mm (default: %(default)s)")
    return p.parse_args()


def select(args):
    """Faces that pass the filters given on the command line.

    Filters that need the font file (weight, class, missing characters) are
    applied while rendering, see render().
    """
    fam = re.compile(args.family, re.I) if args.family else None
    name = re.compile(args.name, re.I) if args.name else None
    out = []
    for face in fl.list_faces():
        if fam and not fam.search(face.family):
            continue
        if name and not name.search(face.file_name):
            continue
        if args.italic is not None and face.italic != args.italic:
            continue
        out.append(face)
    return out


def check_face(face, args):
    """Apply the filters that need the opened font.

    Returns:
        None if the face passes, else the reason it does not.
    """
    if not face.has_chars(args.text):
        return "missing characters"
    if args.weight_min is not None and face.weight < args.weight_min:
        return "weight"
    if args.weight_max is not None and face.weight > args.weight_max:
        return "weight"
    if args.mono is not None and face.mono != args.mono:
        return "spacing"
    if args.cls and face.classification != args.cls:
        return "class"
    return None


def render(face_info, args):
    """Render the preview PNG of one face.

    Returns:
        (PostScript name, None) on success, or (PostScript name, reason)
        when the face is skipped.
    """
    logging.disable(logging.WARNING)
    try:
        face = fl.Face(face_info)
        reason = check_face(face, args)
        if reason:
            return face_info.psname, reason
        placed = face.layout(args.text)
    except Exception as e:  # damaged or unusual fonts are skipped, not fatal
        return face_info.psname, f"error: {e}"
    inked = [(x, g) for x, g in placed if not g.empty]
    if not inked:
        return face_info.psname, "no outline"
    sizes = fl.max_sizes(placed, fl.usable_area(args.bed, args.margin, args.line_width))
    bboxes = [g.bbox() for _, g in inked]
    xmin = min(x + b[0] for (x, _), b in zip(inked, bboxes))
    xmax = max(x + b[2] for (x, _), b in zip(inked, bboxes))
    ymin = min(b[1] for b in bboxes)
    ymax = max(b[3] for b in bboxes)
    height = max(b[3] - b[1] for b in bboxes)

    # image geometry, in supersampled pixels
    pad = args.px // 20
    caption_h = args.px // 14
    k = (args.px - 2 * pad) / max(xmax - xmin, ymax - ymin)
    w = int(round((xmax - xmin) * k)) + 2 * pad
    h = int(round((ymax - ymin) * k)) + 2 * pad
    ss = SUPERSAMPLE

    def to_px(pts, dx):
        return [((x + dx - xmin) * k * ss + pad * ss, (ymax - y) * k * ss + pad * ss)
                for x, y in pts]

    fill = Image.new("L", (w * ss, h * ss), 0)
    band = Image.new("L", (w * ss, h * ss), 0)
    for dx, g in inked:
        for group in g.groups:
            layer = Image.new("L", fill.size, 0)
            d = ImageDraw.Draw(layer)
            d.polygon(to_px(group[0], dx), fill=255)
            for hole in group[1:]:
                d.polygon(to_px(hole, dx), fill=0)
            fill.paste(255, mask=layer)
        if args.band > 0:
            mm_px = height * k * ss / sizes[args.layout]["size0"]
            width = max(1, int(round(2 * args.band * mm_px)))
            d = ImageDraw.Draw(band)
            r = width / 2
            for line in fl.visible_runs(g.groups, face.upm / 200):
                pts = to_px(line, dx)
                # single segments with a disc at every point: polyline joints
                # leave hairline gaps between nearly collinear segments
                for p, q in zip(pts, pts[1:]):
                    d.line([p, q], fill=255, width=width)
                for x, y in pts:
                    d.ellipse((x - r, y - r, x + r, y + r), fill=255)
    if args.band > 0:
        band = Image.fromarray(np.minimum(np.asarray(band), np.asarray(fill)))

    img = Image.new("RGB", fill.size, args.background)
    img.paste(Image.new("RGB", fill.size, args.fill), mask=fill)
    if args.band > 0:
        img.paste(Image.new("RGB", fill.size, args.outline), mask=band)
    img = img.resize((w, h), Image.LANCZOS)

    # caption below the text; narrow images are widened to fit it
    font = ImageFont.load_default(size=caption_h // 3)
    flags = [f"weight {face.weight}", face.classification or "unclassified"]
    if face_info.italic:
        flags.append("italic")
    if face.mono:
        flags.append("mono")
    fill_error = max(g.fill_error for _, g in inked)
    if fill_error > 0.001:
        flags.append(f"OUTLINE DIFFERS FROM FONT ON {100 * fill_error:.1f}%")
    lines = [f"{face_info.family} {face_info.style}  ({face_info.psname})",
             f"{', '.join(flags)}   max size: text {sizes['text']['size0']:.0f} mm, "
             f"glyph {sizes['glyph']['size0']:.0f} mm"]
    text_w = max(font.getbbox(line)[2] for line in lines)
    out_w = max(w, int(text_w) + 2 * pad)
    out = Image.new("RGB", (out_w, h + caption_h), args.background)
    out.paste(img, ((out_w - w) // 2, 0))
    d = ImageDraw.Draw(out)
    for i, line in enumerate(lines):
        d.text((pad, h + i * caption_h * 0.42), line, fill=args.fill, font=font)
    out.save(os.path.join(args.out, face_info.file_name + ".png"), optimize=True)
    return face_info.psname, None


def main():
    """Select the faces and render them in parallel."""
    args = parse_args()
    faces = select(args)
    if args.list:
        logging.disable(logging.WARNING)
        for info in faces:
            try:
                face = fl.Face(info)
                if check_face(face, args):
                    continue
            except Exception:
                continue
            print(f"{info.file_name}\t{info.family}\t{info.style}\t"
                  f"weight {face.weight}\t{face.classification or '-'}")
        return
    os.makedirs(args.out, exist_ok=True)
    done = skipped = 0
    with ProcessPoolExecutor(max_workers=args.jobs) as pool:
        for name, reason in pool.map(render, faces, [args] * len(faces), chunksize=4):
            if reason is None:
                done += 1
            else:
                skipped += 1
                if reason.startswith("error"):
                    print(f"{name}: {reason}", file=sys.stderr)
    print(f"{done} previews written to {args.out}, {skipped} faces skipped")


if __name__ == "__main__":
    main()