trans.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import logging
  2. import re
  3. from scriptshifter.exceptions import BREAK, CONT
  4. from scriptshifter.tables import WORD_BOUNDARY, load_table
  5. # Match multiple spaces.
  6. MULTI_WS_RE = re.compile(r"\s{2,}")
  7. # Cursor bitwise flags.
  8. CUR_BOW = 1 << 0
  9. CUR_EOW = 1 << 1
  10. logger = logging.getLogger(__name__)
  11. class Context:
  12. """
  13. Context used within the transliteration and passed to hook functions.
  14. """
  15. @property
  16. def src(self):
  17. return self._src
  18. @src.setter
  19. def src(self):
  20. raise NotImplementedError("Atribute is read-only.")
  21. @src.deleter
  22. def src(self):
  23. raise NotImplementedError("Atribute is read-only.")
  24. def __init__(self, src, general, langsec, options={}):
  25. """
  26. Initialize a context.
  27. Args:
  28. src (str): The original text. Read-only.
  29. general (dict): general section of the current config.
  30. langsec (dict): Language configuration section being used.
  31. options (dict): extra options as a dict.
  32. """
  33. self._src = src
  34. self.general = general
  35. self.options = options
  36. self.langsec = langsec
  37. self.dest_ls = []
  38. def transliterate(src, lang, t_dir="s2r", capitalize=False, options={}):
  39. """
  40. Transliterate a single string.
  41. Args:
  42. src (str): Source string.
  43. lang (str): Language name.
  44. t_dir (str): Transliteration direction. Either `s2r` for
  45. script-to-Roman (default) or `r2s` for Roman-to-script.
  46. capitalize: capitalize words: one of `False` (no change - default),
  47. `"first"` (only first letter), or `"all"` (first letter of each
  48. word).
  49. options: extra script-dependent options. Defaults to the empty map.
  50. Keyword args:
  51. r2s (bool): If False (the default), the source is considered to be a
  52. non-latin script in the language and script specified, and the output
  53. the Romanization thereof; if True, the source is considered to be
  54. romanized text to be transliterated into the specified script/language.
  55. Return:
  56. str: The transliterated string.
  57. """
  58. source_str = "Latin" if t_dir == "r2s" else lang
  59. target_str = lang if t_dir == "r2s" else "Latin"
  60. logger.info(f"Transliteration is from {source_str} to {target_str}.")
  61. cfg = load_table(lang)
  62. logger.info(f"Loaded table for {lang}.")
  63. # General directives.
  64. general = cfg.get("general", {})
  65. if t_dir == "s2r" and "script_to_roman" not in cfg:
  66. raise NotImplementedError(
  67. f"Script-to-Roman transliteration not yet supported for {lang}."
  68. )
  69. elif t_dir == "r2s" and "roman_to_script" not in cfg:
  70. raise NotImplementedError(
  71. f"Roman-to-script transliteration not yet supported for {lang}."
  72. )
  73. langsec = (
  74. cfg["script_to_roman"] if t_dir == "s2r"
  75. else cfg["roman_to_script"])
  76. # langsec_dir = langsec.get("directives", {})
  77. langsec_hooks = langsec.get("hooks", {})
  78. src = src.strip()
  79. options["capitalize"] = capitalize
  80. ctx = Context(src, general, langsec, options)
  81. # This hook may take over the whole transliteration process or delegate it
  82. # to some external process, and return the output string directly.
  83. if _run_hook("post_config", ctx, langsec_hooks) == BREAK:
  84. return getattr(ctx, "dest", ""), getattr(ctx, "warnings", [])
  85. # Loop through source characters. The increment of each loop depends on
  86. # the length of the token that eventually matches.
  87. ignore_list = langsec.get("ignore", []) # Only present in R2S
  88. ctx.cur = 0
  89. word_boundary = langsec.get("word_boundary", WORD_BOUNDARY)
  90. while ctx.cur < len(src):
  91. # Reset cursor position flags.
  92. # Carry over extended "beginning of word" flag.
  93. ctx.cur_flags = 0
  94. cur_char = src[ctx.cur]
  95. # Look for a word boundary and flag word beginning/end it if found.
  96. if (ctx.cur == 0 or src[ctx.cur - 1] in word_boundary) and (
  97. cur_char not in word_boundary):
  98. # Beginning of word.
  99. logger.debug(f"Beginning of word at position {ctx.cur}.")
  100. ctx.cur_flags |= CUR_BOW
  101. if (
  102. ctx.cur == len(src) - 1
  103. or src[ctx.cur + 1] in word_boundary
  104. ) and (cur_char not in word_boundary):
  105. # Beginning of word.
  106. # End of word.
  107. logger.debug(f"End of word at position {ctx.cur}.")
  108. ctx.cur_flags |= CUR_EOW
  109. # This hook may skip the parsing of the current
  110. # token or exit the scanning loop altogether.
  111. hret = _run_hook("begin_input_token", ctx, langsec_hooks)
  112. if hret == BREAK:
  113. logger.debug("Breaking text scanning from hook signal.")
  114. break
  115. if hret == CONT:
  116. logger.debug("Skipping scanning iteration from hook signal.")
  117. continue
  118. # Check ignore list. Find as many subsequent ignore tokens
  119. # as possible before moving on to looking for match tokens.
  120. ctx.tk = None
  121. while True:
  122. ctx.ignoring = False
  123. for ctx.tk in ignore_list:
  124. hret = _run_hook("pre_ignore_token", ctx, langsec_hooks)
  125. if hret == BREAK:
  126. break
  127. if hret == CONT:
  128. continue
  129. step = len(ctx.tk)
  130. if ctx.tk == src[ctx.cur:ctx.cur + step]:
  131. # The position matches an ignore token.
  132. hret = _run_hook("on_ignore_match", ctx, langsec_hooks)
  133. if hret == BREAK:
  134. break
  135. if hret == CONT:
  136. continue
  137. logger.info(f"Ignored token: {ctx.tk}")
  138. ctx.dest_ls.append(ctx.tk)
  139. ctx.cur += step
  140. ctx.ignoring = True
  141. break
  142. # We looked through all ignore tokens, not found any. Move on.
  143. if not ctx.ignoring:
  144. break
  145. # Otherwise, if we found a match, check if the next position may be
  146. # ignored as well.
  147. delattr(ctx, "tk")
  148. delattr(ctx, "ignoring")
  149. # Begin transliteration token lookup.
  150. ctx.match = False
  151. for ctx.src_tk, ctx.dest_tk in langsec["map"]:
  152. hret = _run_hook("pre_tx_token", ctx, langsec_hooks)
  153. if hret == BREAK:
  154. break
  155. if hret == CONT:
  156. continue
  157. step = len(ctx.src_tk)
  158. # If the first character of the token is greater (= higher code
  159. # point value) than the current character, then break the loop
  160. # without a match, because we know there won't be any more match
  161. # due to the alphabetical ordering.
  162. if ctx.src_tk[0] > cur_char:
  163. logger.debug(
  164. f"{ctx.src_tk} is after {src[ctx.cur:ctx.cur + step]}."
  165. " Breaking loop.")
  166. break
  167. # Longer tokens should be guaranteed to be scanned before their
  168. # substrings at this point.
  169. if ctx.src_tk == src[ctx.cur:ctx.cur + step]:
  170. ctx.match = True
  171. # This hook may skip this token or break out of the token
  172. # lookup for the current position.
  173. hret = _run_hook("on_tx_token_match", ctx, langsec_hooks)
  174. if hret == BREAK:
  175. break
  176. if hret == CONT:
  177. continue
  178. # A match is found. Stop scanning tokens, append result, and
  179. # proceed scanning the source.
  180. # Capitalization.
  181. if (
  182. (ctx.options["capitalize"] == "first" and ctx.cur == 0)
  183. or
  184. (
  185. ctx.options["capitalize"] == "all"
  186. and ctx.cur_flags & CUR_BOW
  187. )
  188. ):
  189. logger.info("Capitalizing token.")
  190. double_cap = False
  191. for dcap_rule in ctx.langsec.get("double_cap", []):
  192. if ctx.dest_tk == dcap_rule:
  193. ctx.dest_tk = ctx.dest_tk.upper()
  194. double_cap = True
  195. break
  196. if not double_cap:
  197. ctx.dest_tk = ctx.dest_tk[0].upper() + ctx.dest_tk[1:]
  198. ctx.dest_ls.append(ctx.dest_tk)
  199. ctx.cur += step
  200. break
  201. if ctx.match is False:
  202. delattr(ctx, "match")
  203. hret = _run_hook("on_no_tx_token_match", ctx, langsec_hooks)
  204. if hret == BREAK:
  205. break
  206. if hret == CONT:
  207. continue
  208. # No match found. Copy non-mapped character (one at a time).
  209. logger.info(
  210. f"Token {cur_char} (\\u{hex(ord(cur_char))[2:]}) "
  211. f"at position {ctx.cur} is not mapped.")
  212. ctx.dest_ls.append(cur_char)
  213. ctx.cur += 1
  214. else:
  215. delattr(ctx, "match")
  216. delattr(ctx, "cur_flags")
  217. delattr(ctx, "cur")
  218. # This hook may take care of the assembly and cause the function to return
  219. # its own return value.
  220. hret = _run_hook("pre_assembly", ctx, langsec_hooks)
  221. if hret is not None:
  222. return hret, getattr(ctx, "warnings", [])
  223. logger.debug(f"Output list: {ctx.dest_ls}")
  224. ctx.dest = "".join(ctx.dest_ls)
  225. # This hook may reassign the output string and/or cause the function to
  226. # return it immediately.
  227. hret = _run_hook("post_assembly", ctx, langsec_hooks)
  228. if hret == "ret":
  229. return ctx.dest, getattr(ctx, "warnings", [])
  230. # Strip multiple spaces and leading/trailing whitespace.
  231. ctx.dest = re.sub(MULTI_WS_RE, ' ', ctx.dest.strip())
  232. return ctx.dest, getattr(ctx, "warnings", [])
  233. def _run_hook(hname, ctx, hooks):
  234. ret = None
  235. for hook_def in hooks.get(hname, []):
  236. kwargs = hook_def[1] if len(hook_def) > 1 else {}
  237. ret = hook_def[0](ctx, **kwargs)
  238. if ret in (BREAK, CONT):
  239. # This will stop parsing hooks functions and tell the caller to
  240. # break out of the outer loop or skip iteration.
  241. return ret
  242. return ret