__init__.py 6.9 KB

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