__init__.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import logging
  2. from functools import cache
  3. from importlib import import_module
  4. from os import path, access, R_OK
  5. from yaml import load
  6. try:
  7. from yaml import CLoader as Loader
  8. except ImportError:
  9. from yaml import Loader
  10. from transliterator.exceptions import ConfigError
  11. __doc__ = """
  12. Transliteration tables.
  13. These tables contain all transliteration information, grouped by script and
  14. language (or language and script? TBD)
  15. """
  16. TABLE_DIR = path.join(path.dirname(path.realpath(__file__)), "data")
  17. # Available hook names.
  18. HOOKS = (
  19. "post_config",
  20. "begin_input_token",
  21. "pre_ignore_token",
  22. "on_ignore_match",
  23. "pre_tx_token",
  24. "on_tx_token_match",
  25. "on_no_tx_token_match",
  26. "pre_assembly",
  27. "post_assembly",
  28. )
  29. # Package path where hook functions are kept.
  30. HOOK_PKG_PATH = "transliterator.hooks"
  31. logger = logging.getLogger(__name__)
  32. class Token(str):
  33. """
  34. Token class: minimal unit of text parsing.
  35. This class overrides the `<` operator for strings, so that sorting is done
  36. in a way that prioritizes a longer string over a shorter one with identical
  37. root.
  38. """
  39. def __init__(self, content):
  40. self.content = content
  41. def __lt__(self, other):
  42. """
  43. Operator to sort tokens.
  44. E.g:
  45. - ABCD
  46. - AB
  47. - A
  48. - BCDE
  49. - BCD
  50. - BEFGH
  51. - B
  52. """
  53. logger.debug(f"a: {self.content}, b: {other.content}")
  54. self_len = len(self.content)
  55. other_len = len(other.content)
  56. min_len = min(self_len, other_len)
  57. # If one of the strings is entirely contained in the other string...
  58. if self.content[:min_len] == other.content[:min_len]:
  59. logger.debug("Roots match.")
  60. # ...then the longer one takes precedence (is "less")
  61. return self_len > other_len
  62. # If the root strings are different, perform a normal comparison.
  63. return self.content < other.content
  64. def __hash__(self):
  65. return hash(self.content)
  66. @cache
  67. def list_tables():
  68. """
  69. List all the available tables.
  70. """
  71. with open(path.join(TABLE_DIR, "index.yml")) as fh:
  72. tdata = load(fh, Loader=Loader)
  73. return tdata
  74. @cache
  75. def load_table(tname):
  76. """
  77. Load one transliteration table and possible parent.
  78. The table file is parsed into an in-memory configuration that contains
  79. the language & script metadata and parsing rules.
  80. """
  81. fname = path.join(TABLE_DIR, tname + ".yml")
  82. if not access(fname, R_OK):
  83. raise ValueError(f"No transliteration table for {tname}!")
  84. with open(fname) as fh:
  85. tdata = load(fh, Loader=Loader)
  86. # NOTE Only one level of inheritance. No need for recursion for now.
  87. parent = tdata.get("general", {}).get("inherits", None)
  88. if parent:
  89. parent_tdata = load_table(parent)
  90. if "script_to_roman" in tdata:
  91. tokens = {
  92. Token(k): v
  93. for k, v in tdata["script_to_roman"].get("map", {}).items()}
  94. if parent:
  95. # Merge (and override) parent values.
  96. tokens = {
  97. Token(k): v for k, v in parent_tdata.get(
  98. "script_to_roman", {}).get("map", {})
  99. } | tokens
  100. tdata["script_to_roman"]["map"] = tuple(
  101. (k.content, tokens[k]) for k in sorted(tokens))
  102. if "hooks" in tdata["script_to_roman"]:
  103. tdata["script_to_roman"]["hooks"] = load_hook_fn(
  104. tname, tdata["script_to_roman"])
  105. if "roman_to_script" in tdata:
  106. tokens = {
  107. Token(k): v
  108. for k, v in tdata["roman_to_script"].get("map", {}).items()}
  109. if parent:
  110. # Merge (and override) parent values.
  111. tokens = {
  112. Token(k): v for k, v in parent_tdata.get(
  113. "roman_to_script", {}).get("map", {})
  114. } | tokens
  115. tdata["roman_to_script"]["map"] = tuple(
  116. (k.content, tokens[k]) for k in sorted(tokens))
  117. if parent:
  118. p_ignore = {
  119. Token(t) for t in parent_tdata.get(
  120. "roman_to_script", {}).get("ignore", [])}
  121. else:
  122. p_ignore = set()
  123. ignore = {
  124. Token(t)
  125. for t in tdata["roman_to_script"].get("ignore", [])
  126. } | p_ignore
  127. tdata["roman_to_script"]["ignore"] = [
  128. t.content for t in sorted(ignore)]
  129. if "hooks" in tdata["roman_to_script"]:
  130. tdata["roman_to_script"]["hooks"] = load_hook_fn(
  131. tname, tdata["script_to_roman"])
  132. return tdata
  133. def load_hook_fn(cname, sec):
  134. """
  135. Load hook functions from configuration file.
  136. Args:
  137. lang (str): The language key for the configuration.
  138. sec (dict): The `script_to_roman` or `roman_to_script` section
  139. that may contain the `hooks` key to be parsed.
  140. Return:
  141. dict: Dictionary of hook name and list of hook functions pairs.
  142. """
  143. hook_fn = {}
  144. for cfg_hook, cfg_hook_fns in sec.get("hooks", {}).items():
  145. if cfg_hook not in HOOKS:
  146. raise ConfigError(f"{cfg_hook} is not a valid hook name!")
  147. hook_fn[cfg_hook] = []
  148. # There may be more than one function in each hook. They are
  149. # executed in the order they are found.
  150. for cfg_hook_fn in cfg_hook_fns:
  151. modname, fnname = path.splitext(cfg_hook_fn[0])
  152. fnname = fnname.lstrip(".")
  153. fn_kwargs = cfg_hook_fn[1]
  154. try:
  155. fn = getattr(import_module(
  156. "." + modname, HOOK_PKG_PATH), fnname)
  157. except NameError:
  158. raise ConfigError(
  159. f"Hook function {fnname} defined in {cname} configuration "
  160. f"not found in module {HOOK_PKG_PATH}.{modname}!"
  161. )
  162. hook_fn[cfg_hook].append((fn, fn_kwargs))
  163. return hook_fn