| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 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__ |
| 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 |