trans.py 9.1 KB

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