Debian Codegraph @

Lib/notobuilder/documentation.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 import argparse
5 import logging
6 from collections import OrderedDict
7 from pathlib import Path
8
9 import fontTools.ttLib
10 import youseedee
11 import markdown
12 from gftools.utils import primary_script
13 from gflanguages import LoadScripts
14 import yaml
15 from jinja2 import Environment, PackageLoader, select_autoescape
16 from tidylib import tidy_document
17
18
19 jinja = Environment(
20 loader=PackageLoader(__package__, "templates"), autoescape=select_autoescape()
21 )
22 jinja.trim_blocks = True
23 jinja.lstrip_blocks = True
24
25 script_aliases = {}
26 with open(Path(youseedee.ucd_dir()) / "PropertyValueAliases.txt", "r") as f:
27 for line in f:
28 if line.startswith("#"):
29 continue
30 line = line.strip()
31 if not line:
32 continue
33 parts = line.split(";")
34 if parts[0].strip() == "sc":
35 script_aliases[parts[2].strip()] = parts[1].strip()
36
37 logging.basicConfig(level=logging.WARN)
38
39 base_folder = Path(Path(__file__).parent)
40
41 update_odd_scripts = {
42 "Aran": "Arab",
43 "Jpan": "Hani",
44 "Kore": "Hani",
45 "Hans": "Hani",
46 "Hant": "Hani",
47 "Zsym": "Zyyy",
48 }
49
50 scripts_info = LoadScripts()
51
52
53 class FontDescription(object):
54
55 def __init__(self, path, config, noto=True):
56 self.path = path
57 article = config.get("article", {})
58 self.stub = article.get("stub")
59 self.variant = article.get("variant")
60 self.style = article.get("style")
61 if not self.style:
62 if "SERIF" in config.get("category", ["SANS"]):
63 self.style = "Serif"
64 else:
65 self.style = "Sans"
66
67 self.is_UI = "UI" in path.name
68 self.is_mono = "Mono" in path.name
69 self.has_italic = False
70 self.font = fontTools.ttLib.TTFont(path)
71 self.noto_script = article.get(
72 "script", primary_script(self.font, ignore_latin=True)
73 )
74 if "STAT" in self.font:
75 stat_tags = [
76 axis.AxisTag for axis in self.font["STAT"].table.DesignAxisRecord.Axis
77 ]
78 if "ital" in stat_tags:
79 self.has_italic = True
80
81 self.unicodes = list(self.font.getBestCmap().keys())
82 self.scripts = OrderedDict()
83 self.blocks = OrderedDict()
84 self.family_name = self.font["name"].getDebugName(16) or self.font[
85 "name"
86 ].getDebugName(1)
87 self.glyphs_count = len(self.font.getGlyphOrder())
88 self.features_count = 0
89 self.art = ""
90 self.desc = ""
91 self.build_features_count()
92 self.build_axes()
93 self.build_scripts()
94 self.build_blocks()
95 self.build_desc()
96
97 def build_scripts(self):
98 for u in self.unicodes:
99 data = youseedee.ucd_data(u)
100 if data["General_Category"][0] not in ("N", "C"):
101 script = script_aliases[data["Script"]]
102 self.scripts[script] = self.scripts.get(script, 0) + 1
103 self.scripts = OrderedDict(
104 sorted(self.scripts.items(), key=lambda t: t[1], reverse=True)
105 )
106 if self.noto_script in update_odd_scripts.keys():
107 self.scripts[self.noto_script] = self.scripts.pop(
108 update_odd_scripts[self.noto_script]
109 )
110 if self.noto_script == "SYM2":
111 self.scripts["Zyyy"] = self.scripts.pop("Zsym")
112 if self.family_name == "Noto Music":
113 self.scripts["Grek"] = self.scripts.pop("Zyyy")
114 if self.family_name == "Noto Sans Mono":
115 self.scripts["Grek"] = self.scripts["Cyrl"]
116 for k in ("Zyyy", "Zinh", "Zzzz"):
117 if k in self.scripts.keys():
118 del self.scripts[k]
119 if "Zmth" in list(self.scripts.keys())[1:]:
120 del self.scripts["Zmth"]
121 if len(self.unicodes) < 10000:
122 for k in list(self.scripts.keys()):
123 if self.scripts[k] / len(self.unicodes) < 0.11:
124 del self.scripts[k]
125
126 def build_blocks(self):
127 for u in self.unicodes:
128 data = youseedee.ucd_data(u)
129 if data["General_Category"][0] not in ("N", "C"):
130 block = data["Block"]
131 self.blocks[block] = self.blocks.get(block, 0) + 1
132 self.blocks = OrderedDict(
133 sorted(self.blocks.items(), key=lambda t: t[1], reverse=True)
134 )
135 for k in list(self.blocks.keys()):
136 if self.blocks[k] < 4:
137 del self.blocks[k]
138
139 def build_axes(self):
140 self.axes = ""
141 axes_text = ""
142 italic_text = ""
143 if self.has_italic:
144 italic_text = "italic styles, "
145 axes_simple = []
146 axes_custom = []
147 fvar = self.font.get("fvar", None)
148 name = self.font["name"]
149 comma = ""
150 if fvar:
151 for axis in fvar.axes:
152 if axis.maxValue > axis.minValue:
153 axisname = name.getName(axis.axisNameID, 3, 1).toUnicode().lower()
154 if axisname in ("weight", "width"):
155 axes_simple.append(axisname + "s")
156 else:
157 axes_custom.append(axisname)
158 if len(axes_simple):
159 axes_simple_text = " and ".join(axes_simple)
160 if len(axes_custom):
161 axes_custom_text = "variations in" + ", ".join(axes_custom)
162 if len(axes_simple):
163 axes_text += axes_simple_text
164 if len(axes_custom):
165 axes_text += ", and "
166 if len(axes_custom):
167 axes_text += axes_custom_text
168 if len(axes_simple) + len(axes_custom) > 1:
169 comma = ","
170 if len(axes_simple) or len(axes_custom):
171 self.axes = f"{italic_text}multiple {axes_text}{comma}"
172
173 def build_features_count(self):
174 features = set()
175 for table in [self.font.get("GSUB"), self.font.get("GPOS")]:
176 if not table:
177 continue
178 features.update(
179 set(
180 [
181 FeatureRecord.FeatureTag
182 for FeatureRecord in table.table.FeatureList.FeatureRecord
183 ]
184 )
185 )
186 self.features_count = len(sorted(list(features)))
187
188 def build_desc(self):
189 variables = dict(
190 family_name=self.family_name,
191 stub=self.stub,
192 glyphs_count=self.glyphs_count,
193 features_count=self.features_count,
194 unicodes_count=len(self.unicodes),
195 style=self.style,
196 variant=self.variant,
197 is_mono=self.is_mono,
198 is_UI=self.is_UI,
199 axes=self.axes,
200 scripts=list(self.scripts.keys()),
201 scripts_info=scripts_info,
202 blocks=list(self.blocks.keys()),
203 )
204
205 self.art = jinja.get_template("font_article.md").render(**variables)
206 self.desc = jinja.get_template("font_desc.md").render(**variables)
207
208 def save(self, path, md):
209 logging.info(f"Saving {path}")
210 with open(path, "w", encoding="utf-8") as f:
211 document, errors = tidy_document(
212 markdown.markdown(md), {"show-body-only": "y"}
213 )
214 f.write(document)
215
216
217 def main():
218 parser = argparse.ArgumentParser()
219 parser.add_argument("-c", "--config", help="YAML configuration file", required=True)
220 parser.add_argument(
221 "-f", "--font", help="Path to best font file", required=True, type=Path
222 )
223 args = parser.parse_args()
224 config = yaml.safe_load(open(args.config, "r"))
225 art_desc = FontDescription(args.font, config, noto=True)
226
227 if args.font.parts[0] != "fonts":
228 print("Expected a path of the form fonts/NotoSansWhatever/...")
229 family_path = args.font.parts[1]
230
231 art_path = Path("documentation") / (family_path + ".article.html")
232 desc_path = Path("documentation") / (family_path + ".html")
233 art_desc.save(art_path, art_desc.art)
234 art_desc.save(desc_path, art_desc.desc)
235
236
237 if __name__ == "__main__":
238 main()