__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. from gflanguages import languages_public_pb2
  25. from google.protobuf import text_format
  26. from pkg_resources import resource_filename
  27. try:
  28. from ._version import version as __version__ # type: ignore
  29. except ImportError:
  30. __version__ = "0.0.0+unknown"
  31. DATA_DIR = resource_filename("gflanguages", "data")
  32. def LoadLanguages(base_dir=DATA_DIR):
  33. if base_dir is None:
  34. base_dir = DATA_DIR
  35. languages_dir = os.path.join(base_dir, "languages")
  36. langs = {}
  37. for textproto_file in glob.iglob(os.path.join(languages_dir, "*.textproto")):
  38. with open(textproto_file, "r", encoding="utf-8") as f:
  39. language = text_format.Parse(f.read(), languages_public_pb2.LanguageProto())
  40. langs[language.id] = language
  41. return langs
  42. def LoadScripts(base_dir=DATA_DIR):
  43. if base_dir is None:
  44. base_dir = DATA_DIR
  45. scripts_dir = os.path.join(base_dir, "scripts")
  46. scripts = {}
  47. for textproto_file in glob.iglob(os.path.join(scripts_dir, "*.textproto")):
  48. with open(textproto_file, "r", encoding="utf-8") as f:
  49. script = text_format.Parse(f.read(), languages_public_pb2.ScriptProto())
  50. scripts[script.id] = script
  51. return scripts
  52. def LoadRegions(base_dir=DATA_DIR):
  53. if base_dir is None:
  54. base_dir = DATA_DIR
  55. regions_dir = os.path.join(base_dir, "regions")
  56. regions = {}
  57. for textproto_file in glob.iglob(os.path.join(regions_dir, "*.textproto")):
  58. with open(textproto_file, "r", encoding="utf-8") as f:
  59. region = text_format.Parse(f.read(), languages_public_pb2.RegionProto())
  60. regions[region.id] = region
  61. return regions