Created
May 9, 2021 18:00
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
import glob | |
import subprocess | |
import argparse | |
class SubsetFont: | |
def __init__(self, args): | |
outdir = os.path.dirname(args.output) | |
os.makedirs(outdir, exist_ok=True) | |
self.__txt = outdir + "/all-characters.txt" | |
self.__args = args | |
self.__setTarget() | |
self.__setFile() | |
self.__genText() | |
self.__setCommandLine() | |
def __setTarget(self): | |
self.__target = self.__args.target | |
if self.__target[-1] != "/": | |
self.__target += "/" | |
self.__target += "**" | |
def __setFile(self): | |
exts = [e if e[0] == "." else "." + e for e in self.__args.exts] | |
files = glob.glob(self.__target, recursive=True) | |
tmp = [os.path.splitext(f) for f in files] | |
self.__files = [f[0] + f[1] for f in tmp if f[1] in exts] | |
def __genText(self): | |
txt = [] | |
for file in self.__files: | |
with open(file, mode="r", encoding="utf-8") as f: | |
txt.append(f.read()) | |
dedup = "".join(set("".join(txt))) | |
dedup = "".join(dedup.split()) | |
dedup = "".join(sorted(dedup)) | |
with open(self.__txt, mode="w", encoding="utf-8") as f: | |
print(dedup, file=f) | |
def __setCommandLine(self): | |
self.__cmd = " ".join([ | |
self.__args.pyftsubset, | |
self.__args.font, | |
f"--text-file={self.__txt}", | |
"--layout-features='*'", | |
]) | |
def generate(self, flavor): | |
output = f"{self.__args.output}.{flavor}" | |
cmd = f"{self.__cmd} --flavor={flavor} --output-file={output}" | |
subprocess.run(cmd) | |
def clean(self): | |
os.remove(self.__txt) | |
if __name__ == "__main__": | |
ap = argparse.ArgumentParser() | |
ap.add_argument("font", help="The input font file.") | |
ap.add_argument("-t", "--target", default=".", | |
help="Specify the target directory.") | |
ap.add_argument("-e", "--exts", type=lambda x: x.split(","), | |
default=["html","css","js","json","php"], | |
help="Specify extensions of text files") | |
ap.add_argument("-p", "--pyftsubset", type=str, default="pyftsubset", | |
help="Specify the path of pyftsubset.") | |
ap.add_argument("-o", "--output", default="subset", | |
help="Specify output file.") | |
sf = SubsetFont(ap.parse_args()) | |
sf.generate("woff") | |
sf.generate("woff2") | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment