mx / dengtaishan-src /tools /subset_fonts.py
Ethscriptions's picture
登泰山记:旁白脚本、93 句旁白音频、字体子集
1b1f125 verified
Raw History Blame Contribute Delete
1.47 kB
# 字体子集化:扫描源码中出现的全部字符,生成 woff2 子集
import os, re, sys, subprocess
SRC = "/workspaces/frontend/src"; OUT = "/workspaces/frontend/public/fonts"; FD = "/tmp/fonts"
os.makedirs(OUT, exist_ok=True)
chars = set()
for root, _, files in os.walk(SRC):
for f in files:
if f.endswith((".ts", ".tsx", ".json", ".css")):
chars |= set(open(os.path.join(root, f), encoding="utf-8").read())
chars |= set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ·—…“”‘’《》〈〉「」『』,。、;:?!()·-:/%.+|#@&")
text = "".join(sorted(c for c in chars if ord(c) >= 32))
open("/tmp/fonts/chars.txt", "w", encoding="utf-8").write(text)
print("chars:", len(text))
def run(*a): subprocess.run(a, check=True)
if not os.path.exists(f"{FD}/serif500.ttf"):
run("fonttools", "varLib.instancer", f"{FD}/NotoSerifSC[wght].ttf", "wght=500", "-o", f"{FD}/serif500.ttf")
run("fonttools", "varLib.instancer", f"{FD}/NotoSerifSC[wght].ttf", "wght=900", "-o", f"{FD}/serif900.ttf")
for src, name in [("serif500.ttf", "serif-500"), ("serif900.ttf", "serif-900"), ("MaShanZheng-Regular.ttf", "kai"), ("ZhiMangXing-Regular.ttf", "xing"), ("LiuJianMaoCao-Regular.ttf", "cao")]:
run("pyftsubset", f"{FD}/{src}", "--text-file=/tmp/fonts/chars.txt", "--flavor=woff2", f"--output-file={OUT}/{name}.woff2", "--layout-features=*")
for f in sorted(os.listdir(OUT)): print(f, os.path.getsize(os.path.join(OUT, f)))