__init__.py 7.0 KB

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