trans.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import logging
  2. from importlib import import_module
  3. from re import Pattern, compile
  4. from unicodedata import normalize as precomp_normalize
  5. from scriptshifter.exceptions import BREAK, CONT
  6. from scriptshifter.tables import (
  7. BOW, EOW, WORD_BOUNDARY, FEAT_R2S, FEAT_S2R, HOOK_PKG_PATH,
  8. get_connection, get_lang_dcap, get_lang_general, get_lang_hooks,
  9. get_lang_ignore, get_lang_map, get_lang_normalize)
  10. # Match multiple spaces.
  11. MULTI_WS_RE = compile(r"(\s){2,}")
  12. logger = logging.getLogger(__name__)
  13. class Context:
  14. """
  15. Context used within the transliteration and passed to hook functions.
  16. Use within a `with` block for proper cleanup.
  17. """
  18. @property
  19. def src(self):
  20. return self._src
  21. @src.setter
  22. def src(self):
  23. raise NotImplementedError("Attribute is read-only.")
  24. @src.deleter
  25. def src(self):
  26. raise NotImplementedError("Attribute is read-only.")
  27. def __init__(self, lang, src, t_dir, options={}):
  28. """
  29. Initialize a context.
  30. Args:
  31. src (str): The original text. Read-only.
  32. t_dir (int): the direction of transliteration.
  33. Either FEAT_R2S or FEAT_S2R.
  34. options (dict): extra options as a dict.
  35. """
  36. self.lang = lang
  37. self._src = src
  38. self.t_dir = t_dir
  39. self.conn = get_connection()
  40. with self.conn as conn:
  41. general = get_lang_general(conn, self.lang)
  42. self.general = general["data"]
  43. self.lang_id = general["id"]
  44. self.options = options
  45. self.hooks = get_lang_hooks(self.conn, self.lang_id, self.t_dir)
  46. self.dest_ls = []
  47. self.warnings = []
  48. def __enter__(self):
  49. return self
  50. def __exit__(self, exc_type, exc_value, traceback):
  51. self.conn.close()
  52. def transliterate(src, lang, t_dir="s2r", capitalize=False, options={}):
  53. """
  54. Transliterate a single string.
  55. Args:
  56. src (str): Source string.
  57. lang (str): Language name.
  58. t_dir (str): Transliteration direction. Either `s2r` for
  59. script-to-Roman (default) or `r2s` for Roman-to-script.
  60. capitalize: capitalize words: one of `False` (no change - default),
  61. `"first"` (only first letter), or `"all"` (first letter of each
  62. word).
  63. options: extra script-dependent options. Defaults to the empty map.
  64. Keyword args:
  65. r2s (bool): If False (the default), the source is considered to be a
  66. non-latin script in the language and script specified, and the output
  67. the Romanization thereof; if True, the source is considered to be
  68. romanized text to be transliterated into the specified script/language.
  69. Return:
  70. str: The transliterated string.
  71. """
  72. # Map t_dir to constant.
  73. t_dir = FEAT_S2R if t_dir == "s2r" else FEAT_R2S
  74. source_str = "Roman" if t_dir == FEAT_R2S else lang
  75. target_str = lang if t_dir == FEAT_R2S else "Roman"
  76. logger.info(f"Transliteration is from {source_str} to {target_str}.")
  77. src = src.strip()
  78. options["capitalize"] = capitalize
  79. with Context(lang, src, t_dir, options) as ctx:
  80. if t_dir == FEAT_S2R and not ctx.general["has_s2r"]:
  81. raise NotImplementedError(
  82. f"Script-to-Roman not yet supported for {lang}."
  83. )
  84. if t_dir == FEAT_R2S and not ctx.general["has_r2s"]:
  85. raise NotImplementedError(
  86. f"Roman-to-script not yet supported for {lang}."
  87. )
  88. # Normalize case before post_config and rule-based normalization.
  89. if t_dir == FEAT_R2S and not ctx.general["case_sensitive"]:
  90. ctx._src = ctx.src.lower()
  91. # This hook may take over the whole transliteration process or delegate
  92. # it to some external process, and return the output string directly.
  93. if _run_hook("post_config", ctx) == BREAK:
  94. return getattr(ctx, "dest", ""), ctx.warnings
  95. # _normalize_src returns the results of the post_normalize hook.
  96. if _normalize_src(
  97. ctx, get_lang_normalize(ctx.conn, ctx.lang_id)) == BREAK:
  98. return getattr(ctx, "dest", ""), ctx.warnings
  99. logger.debug(f"Normalized source: {ctx.src}")
  100. lang_map = list(get_lang_map(ctx.conn, ctx.lang_id, ctx.t_dir))
  101. # Loop through source characters. The increment of each loop depends on
  102. # the length of the token that eventually matches.
  103. ctx.cur = 0
  104. while ctx.cur < len(ctx.src):
  105. # Reset cursor position flags.
  106. # Carry over extended "beginning of word" flag.
  107. ctx.cur_flags = 0
  108. cur_char = ctx.src[ctx.cur]
  109. # Look for a word boundary and flag word beginning/end it if found.
  110. if _is_bow(ctx.cur, ctx, WORD_BOUNDARY):
  111. # Beginning of word.
  112. logger.debug(f"Beginning of word at position {ctx.cur}.")
  113. ctx.cur_flags |= BOW
  114. if _is_eow(ctx.cur, ctx, WORD_BOUNDARY):
  115. # End of word.
  116. logger.debug(f"End of word at position {ctx.cur}.")
  117. ctx.cur_flags |= EOW
  118. # This hook may skip the parsing of the current
  119. # token or exit the scanning loop altogether.
  120. hret = _run_hook("begin_input_token", ctx)
  121. if hret == BREAK:
  122. logger.debug("Breaking text scanning from hook signal.")
  123. break
  124. if hret == CONT:
  125. logger.debug("Skipping scanning iteration from hook signal.")
  126. continue
  127. # Check ignore list. Find as many subsequent ignore tokens
  128. # as possible before moving on to looking for match tokens.
  129. ctx.tk = None
  130. while True:
  131. ctx.ignoring = False
  132. for ctx.tk in get_lang_ignore(ctx.conn, ctx.lang_id):
  133. hret = _run_hook("pre_ignore_token", ctx)
  134. if hret == BREAK:
  135. break
  136. if hret == CONT:
  137. continue
  138. _matching = False
  139. if type(ctx.tk) is Pattern:
  140. # Seach RE pattern beginning at cursor.
  141. if _ptn_match := ctx.tk.match(ctx.src[ctx.cur:]):
  142. ctx.tk = _ptn_match[0]
  143. logger.debug(f"Matched regex: {ctx.tk}")
  144. step = len(ctx.tk)
  145. _matching = True
  146. else:
  147. # Search exact match.
  148. step = len(ctx.tk)
  149. if ctx.tk == ctx.src[ctx.cur:ctx.cur + step]:
  150. _matching = True
  151. if _matching:
  152. # The position matches an ignore token.
  153. hret = _run_hook("on_ignore_match", ctx)
  154. if hret == BREAK:
  155. break
  156. if hret == CONT:
  157. continue
  158. logger.info(f"Ignored token: {ctx.tk}")
  159. ctx.dest_ls.append(ctx.tk)
  160. ctx.cur += step
  161. if ctx.cur >= len(ctx.src):
  162. # reached end of string. Stop ignoring.
  163. # The outer loop will exit imediately after.
  164. ctx.ignoring = False
  165. break
  166. cur_char = ctx.src[ctx.cur]
  167. ctx.ignoring = True
  168. break
  169. # We looked through all ignore tokens, not found any. Move on.
  170. if not ctx.ignoring:
  171. break
  172. # Otherwise, if we found a match, check if the next position
  173. # may be ignored as well.
  174. delattr(ctx, "tk")
  175. delattr(ctx, "ignoring")
  176. if ctx.cur >= len(ctx.src):
  177. break
  178. # Begin transliteration token lookup.
  179. ctx.match = False
  180. for ctx.src_tk, ctx.dest_str in lang_map:
  181. hret = _run_hook("pre_tx_token", ctx)
  182. if hret == BREAK:
  183. break
  184. if hret == CONT:
  185. continue
  186. step = len(ctx.src_tk.content)
  187. # If the token is longer than the remaining of the string,
  188. # it surely won't match.
  189. if ctx.cur + step > len(ctx.src):
  190. continue
  191. # If the first character of the token is greater (= higher code
  192. # point value) than the current character, then break the loop
  193. # without a match, because we know there won't be any more
  194. # match due to the alphabetical ordering.
  195. if ctx.src_tk.content[0] > cur_char:
  196. logger.debug(
  197. f"{ctx.src_tk.content} is after "
  198. f"{ctx.src[ctx.cur:ctx.cur + step]}. "
  199. "Breaking loop.")
  200. break
  201. # If src_tk has a WB flag but the token is not at WB, skip.
  202. if (
  203. (ctx.src_tk.flags & BOW and not ctx.cur_flags & BOW)
  204. or
  205. # Can't rely on EOW flag, we must check on the last
  206. # character of the potential match.
  207. (ctx.src_tk.flags & EOW and not _is_eow(
  208. ctx.cur + step - 1, ctx, WORD_BOUNDARY))
  209. ):
  210. continue
  211. # Longer tokens should be guaranteed to be scanned before their
  212. # substrings at this point.
  213. # Similarly, flagged tokens are evaluated first.
  214. if ctx.src_tk.content == ctx.src[ctx.cur:ctx.cur + step]:
  215. ctx.match = True
  216. # This hook may skip this token or break out of the token
  217. # lookup for the current position.
  218. hret = _run_hook("on_tx_token_match", ctx)
  219. if hret == BREAK:
  220. break
  221. if hret == CONT:
  222. continue
  223. # A match is found. Stop scanning tokens, append result,
  224. # and proceed scanning the source.
  225. # Capitalization. This applies double capitalization
  226. # rules. The external function in
  227. # scriptshifter.tools.capitalize used for non-table
  228. # languages does not.
  229. if (
  230. (ctx.options["capitalize"] == "first" and ctx.cur == 0)
  231. or
  232. (
  233. ctx.options["capitalize"] == "all"
  234. and ctx.cur_flags & BOW
  235. )
  236. ):
  237. logger.info("Capitalizing token.")
  238. double_cap = False
  239. for dcap_rule in get_lang_dcap(ctx.conn, ctx.lang_id):
  240. if ctx.dest_str == dcap_rule:
  241. ctx.dest_str = ctx.dest_str.upper()
  242. double_cap = True
  243. break
  244. if not double_cap:
  245. ctx.dest_str = (
  246. ctx.dest_str[0].upper() + ctx.dest_str[1:])
  247. ctx.dest_ls.append(ctx.dest_str)
  248. ctx.cur += step
  249. break
  250. if ctx.match is False:
  251. delattr(ctx, "match")
  252. hret = _run_hook("on_no_tx_token_match", ctx)
  253. if hret == BREAK:
  254. break
  255. if hret == CONT:
  256. continue
  257. # No match found. Copy non-mapped character (one at a time).
  258. logger.info(
  259. f"Token {cur_char} (\\u{hex(ord(cur_char))[2:]}) "
  260. f"at position {ctx.cur} is not mapped.")
  261. ctx.dest_ls.append(cur_char)
  262. ctx.cur += 1
  263. else:
  264. delattr(ctx, "match")
  265. delattr(ctx, "cur_flags")
  266. delattr(ctx, "cur")
  267. # This hook may take care of the assembly and cause the function to
  268. # return its own return value.
  269. hret = _run_hook("pre_assembly", ctx)
  270. if hret is not None:
  271. return hret, ctx.warnings
  272. logger.debug(f"Output list: {ctx.dest_ls}")
  273. ctx.dest = "".join(ctx.dest_ls)
  274. # This hook may reassign the output string and/or cause the function to
  275. # return it immediately.
  276. hret = _run_hook("post_assembly", ctx)
  277. if hret is not None:
  278. return hret, ctx.warnings
  279. # Strip multiple spaces and leading/trailing whitespace.
  280. ctx.dest = MULTI_WS_RE.sub(r"\1", ctx.dest.strip())
  281. return ctx.dest, ctx.warnings
  282. def _normalize_src(ctx, norm_rules):
  283. """
  284. Normalize source text according to rules.
  285. NOTE: this manipluates the protected source attribute so it may not
  286. correspond to the originally provided source.
  287. """
  288. # Normalize precomposed Unicode characters.
  289. #
  290. # In using diacritics, LC standards prefer the decomposed form (combining
  291. # diacritic + base character) to the pre-composed form (single Unicode
  292. # symbol for the letter with diacritic).
  293. #
  294. # Note: only safe for R2S.
  295. if ctx.t_dir == FEAT_R2S:
  296. logger.debug("Normalizing pre-composed symbols.")
  297. ctx._src = precomp_normalize("NFD", ctx.src)
  298. for nk, nv in norm_rules.items():
  299. ctx._src = ctx.src.replace(nk, nv)
  300. return _run_hook("post_normalize", ctx)
  301. def _is_bow(cur, ctx, word_boundary):
  302. return (cur == 0 or ctx.src[cur - 1] in word_boundary) and (
  303. ctx.src[cur] not in word_boundary)
  304. def _is_eow(cur, ctx, word_boundary):
  305. return (
  306. cur == len(ctx.src) - 1
  307. or ctx.src[cur + 1] in word_boundary
  308. ) and (ctx.src[cur] not in word_boundary)
  309. def _run_hook(hname, ctx):
  310. ret = None
  311. for hook_def in ctx.hooks.get(hname, []):
  312. fn = getattr(
  313. import_module("." + hook_def["module_name"], HOOK_PKG_PATH),
  314. hook_def["fn_name"])
  315. ret = fn(ctx, **hook_def["kwargs"])
  316. if ret in (BREAK, CONT):
  317. # This will stop parsing hooks functions and tell the caller to
  318. # break out of the outer loop or skip iteration.
  319. return ret
  320. return ret