Debian Codegraph @

Lib/gflanguages/__init__.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 Helper API for interaction with languages/regions/scripts
20 data on the Google Fonts collection.
21 """
22 import glob
23 import os
24 import unicodedata
25 import sys
26
27 from gflanguages import languages_public_pb2
28 from google.protobuf import text_format
29
30 if sys.version_info < (3, 10):
31 from importlib_resources import files
32 else:
33 from importlib.resources import files
34
35 try:
36 from ._version import version as __version__ # type: ignore
37 except ImportError:
38 __version__ = "0.0.0+unknown"
39
40
41 def _load_thing(thing_type, proto_class, base_dir=None):
42 things = {}
43
44 def read_a_thing(contents):
45 proto = proto_class()
46 thing = text_format.Parse(contents, proto)
47 assert thing.id not in things, f"Duplicate {thing_type} id: {thing.id}"
48 things[thing.id] = thing
49
50 if base_dir is not None:
51 thing_dir = os.path.join(base_dir, thing_type)
52 for textproto_file in glob.iglob(os.path.join(thing_dir, "*.textproto")):
53 with open(textproto_file, "r", encoding="utf-8") as f:
54 read_a_thing(f.read())
55 else:
56 for textproto_file in files("gflanguages.data").joinpath(thing_type).iterdir():
57 if not textproto_file.name.endswith(".textproto"):
58 continue
59 read_a_thing(textproto_file.read_text(encoding="utf-8"))
60 return things
61
62
63 def LoadLanguages(base_dir=None):
64 return _load_thing("languages", languages_public_pb2.LanguageProto, base_dir)
65
66
67 def LoadScripts(base_dir=None):
68 return _load_thing("scripts", languages_public_pb2.ScriptProto, base_dir)
69
70
71 def LoadRegions(base_dir=None):
72 return _load_thing("regions", languages_public_pb2.RegionProto, base_dir)
73
74
75 def parse(exemplars: str):
76 """Parses a list of exemplar characters into a set of codepoints."""
77 codepoints = set()
78 for chars in exemplars.split():
79 if len(chars) > 1:
80 chars = chars.lstrip("{").rstrip("}")
81 normalized_chars = unicodedata.normalize("NFC", chars)
82 if normalized_chars != chars:
83 for char in normalized_chars:
84 codepoints.add(char)
85 for char in chars:
86 codepoints.add(char)
87 return codepoints