Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

4.5 KB
Raw Blame
"""Builds Kinetic Motion's self-hosted type faces.

Each face in scripts/kinetic/fonts.json is cut from its SIL OFL source font: variable axes pinned or narrowed to the
instance the type pairings use (so canvas text gets the right optical size, width and softness), then subset to the
Latin range in "subset" and saved as WOFF2 in public/fonts/kinetic/, with each family's licence next to it.
The script also writes src/lib/motion/type/faces.generated.ts (the faces, their files and versions).

    python scripts/kinetic/build-fonts.py <folder with the Google Fonts "ofl/<family>/" sources>

Needs fontTools and brotli (pip install fonttools brotli).
"""

import hashlib
import io
import json
import shutil
import sys
from pathlib import Path

from fontTools import subset
from fontTools.ttLib import TTFont
from fontTools.varLib import instancer

ROOT = Path(__file__).resolve().parents[2]
MANIFEST = ROOT / "scripts" / "kinetic" / "fonts.json"
OUT = ROOT / "public" / "fonts" / "kinetic"
GENERATED = ROOT / "src" / "lib" / "motion" / "type" / "faces.generated.ts"


def unicodes(spec: str) -> list[int]:
    out: list[int] = []
    for part in spec.split(","):
        part = part.strip().upper().removeprefix("U+")
        if "-" in part:
            a, b = part.split("-")
            out.extend(range(int(a, 16), int(b, 16) + 1))
        else:
            out.append(int(part, 16))
    return out


def build(src_root: Path) -> None:
    manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
    codepoints = unicodes(manifest["subset"])
    OUT.mkdir(parents=True, exist_ok=True)
    (OUT / "licences").mkdir(exist_ok=True)
    rows = []
    for face in manifest["faces"]:
        src = src_root / face["src"]
        font = TTFont(src, lazy=False)
        axes = face.get("axes")
        if axes and "fvar" in font:
            limits = {tag: (tuple(v) if isinstance(v, list) else v) for tag, v in axes.items()}
            font = instancer.instantiateVariableFont(font, limits, updateFontNames=False)
            # Round-trip so every table is plain again before subsetting.
            buf = io.BytesIO()
            font.save(buf)
            buf.seek(0)
            font = TTFont(buf, lazy=False)
        options = subset.Options()
        options.flavor = "woff2"
        options.layout_features = ["*"]
        options.name_IDs = ["*"]
        options.name_legacy = True
        options.name_languages = ["*"]
        options.notdef_outline = True
        options.glyph_names = False
        options.hinting = False
        options.desubroutinize = True
        sub = subset.Subsetter(options)
        sub.populate(unicodes=codepoints)
        sub.subset(font)
        target = OUT / f"{face['id']}.woff2"
        font.flavor = "woff2"
        font.save(target)
        data = target.read_bytes()
        licence_dir = face["src"].split("/")[0]
        shutil.copyfile(src_root / licence_dir / "OFL.txt", OUT / "licences" / f"{licence_dir}-OFL.txt")
        rows.append(
            {
                "id": face["id"],
                "family": face["family"],
                "style": face["style"],
                "weight": face["weight"],
                "file": f"/fonts/kinetic/{face['id']}.woff2",
                "v": hashlib.sha256(data).hexdigest()[:8],
                "bytes": len(data),
                "licence": f"/fonts/kinetic/licences/{licence_dir}-OFL.txt",
            }
        )
        print(f"{face['id']:28} {len(data) / 1024:7.1f} KB")
    lines = [
        "// Generated by scripts/kinetic/build-fonts.py from scripts/kinetic/fonts.json. Do not edit by hand.",
        "",
        'import type { KineticFace } from "./faces";',
        "",
        f"export const KINETIC_UNICODE_RANGE = {json.dumps(manifest['subset'])};",
        "",
        "export const KINETIC_FACES: readonly KineticFace[] = [",
    ]
    for r in rows:
        lines.append(
            "  { "
            + f'id: {json.dumps(r["id"])}, family: {json.dumps(r["family"])}, style: {json.dumps(r["style"])}, '
            + f'weight: [{r["weight"][0]}, {r["weight"][1]}], file: {json.dumps(r["file"])}, v: {json.dumps(r["v"])}, '
            + f'bytes: {r["bytes"]}, licence: {json.dumps(r["licence"])}'
            + " },"
        )
    lines += ["];", ""]
    GENERATED.parent.mkdir(parents=True, exist_ok=True)
    GENERATED.write_text("\n".join(lines), encoding="utf-8", newline="\n")
    total = sum(r["bytes"] for r in rows)
    print(f"{len(rows)} faces, {total / 1024:.0f} KB in all")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit(__doc__)
    build(Path(sys.argv[1]))