-
Notifications
You must be signed in to change notification settings - Fork 0
/
fixfont.py
executable file
·77 lines (63 loc) · 2.39 KB
/
fixfont.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python3
import argparse
import sys
import os
from fontTools.ttx import makeOutputFileName
from fontTools.ttLib import TTFont
from unidecode import unidecode
# WOFF name table IDs
FAMILY = 1
SUBFAMILY = 2
FULL_NAME = 4
POSTSCRIPT_NAME = 6
PREFERRED_FAMILY = 16
PREFERRED_SUBFAMILY = 17
WWS_FAMILY = 21
WWS_SUBFAMILY = 22
def main(args=None):
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("-f", "--family-name")
parser.add_argument("-s", "--subfamily-name")
parser.add_argument("-o", "--output")
options = parser.parse_args()
font = TTFont(options.input)
if font.flavor not in ("woff2"):
print("Input file is not a WOFF2 font", file=sys.stderr)
return 1
family, subfamily = extract_names(options.input, options.family_name, options.subfamily_name)
full = "%s %s" % (family, subfamily)
postscript = "%s-%s" % (postscriptify(family), postscriptify(subfamily))[:63]
for rec in font["name"].names:
if rec.nameID in [FAMILY, PREFERRED_FAMILY, WWS_FAMILY]:
rec.string = family
elif rec.nameID in [SUBFAMILY, PREFERRED_SUBFAMILY, WWS_SUBFAMILY]:
rec.string = subfamily
elif rec.nameID == FULL_NAME:
rec.string = full
elif rec.nameID == POSTSCRIPT_NAME:
rec.string = postscript
# Remove extended metadata and private data
font.flavorData.metaData = None
font.flavorData.privData = None
if options.output:
font.save(options.output)
else:
filename, ext = os.path.splitext(options.input)
outfile = makeOutputFileName(filename, None, ext)
font.save(outfile)
print("Output saved in “%s”" % outfile)
def postscriptify(name):
return "".join(char for char in unidecode(name) if 33 <= ord(char) <= 126 and char not in " [](){}<>/%")
def extract_names(file, family_name=None, subfamily_name=None):
filename, _ = os.path.splitext(os.path.basename(file))
if filename.count("-") == 1:
family, subfamily = filename.split("-")
elif filename.count(" ") == 1:
family, subfamily = filename.split(" ")
elif not family_name or not subfamily_name:
print("Could not figure out names from “%s”" % filename, file=sys.stderr)
sys.exit(1)
return family_name or family, subfamily_name or subfamily
if __name__ == "__main__":
sys.exit(main())