__init__.py 7.1 KB

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