Debian Codegraph @

snippets/supported_languages.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #
3 # Copyright 2022 The Google Fonts Tools Authors.
4 # Copyright 2017,2022 Google LLC All Rights Reserved.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS-IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # =======================================================================
19 # ======= This code-snippet uses hyperglot, which is licensed =======
20 # ======= under the GNU GPLv3. So, the resulting license for =======
21 # ======= any program using this snippet will also have to be =======
22 # ======= the GNU GPLv3. =======
23 # =======================================================================
24
25 from gflanguages import LoadLanguages
26 from hyperglot import parse as hyperglot_parse
27
28
29 def _ParseFontChars(path):
30 """
31 Open the provided font path and extract the codepoints encoded in the font
32 @return list of characters
33 """
34 from fontTools.ttLib import TTFont
35 font = TTFont(path, lazy=True)
36 cmap = font["cmap"].getBestCmap()
37 font.close()
38
39 # The cmap keys are int codepoints
40 return [chr(c) for c in cmap.keys()]
41
42
43 def SupportedLanguages(font_path, languages=None):
44 """
45 Get languages supported by given font file.
46
47 Languages are pulled from the given set. Based on whether exemplar character
48 sets are present in the given font.
49
50 Logic based on Hyperglot:
51 https://github.com/rosettatype/hyperglot/blob/3172061ca05a62c0ff330eb802a17d4fad8b1a4d/lib/hyperglot/language.py#L273-L301
52 """
53 if languages is None:
54 languages = LoadLanguages()
55
56 chars = _ParseFontChars(font_path)
57
58 supported = []
59 for lang in languages.values():
60 if not lang.HasField('exemplar_chars') or \
61 not lang.exemplar_chars.HasField('base'):
62 continue
63
64 base = hyperglot_parse.parse_chars(lang.exemplar_chars.base,
65 decompose=False,
66 retainDecomposed=False)
67 if set(base).issubset(chars):
68 supported.append(lang)
69
70 return supported
71
72
73 def portable_path(p):
74 import os
75 return os.path.join(*p.split('/'))
76
77
78 def TEST_FILE(f):
79 return portable_path("data/test/" + f)
80
81
82 def test_SupportedLanguages():
83 font = TEST_FILE('nunito/Nunito-Regular.ttf')
84 supported = SupportedLanguages(font)
85 langs = [supported[i].name for i, _ in enumerate(supported)]
86 assert len(langs) == 225
87 assert 'Lithuanian' in langs