__init__.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. from __future__ import annotations
  2. from fontTools.misc.textTools import byteord, tostr
  3. import re
  4. from bisect import bisect_right
  5. from typing import Literal, TypeVar, overload
  6. try:
  7. # use unicodedata backport compatible with python2:
  8. # https://github.com/fonttools/unicodedata2
  9. from unicodedata2 import *
  10. except ImportError: # pragma: no cover
  11. # fall back to built-in unicodedata (possibly outdated)
  12. from unicodedata import *
  13. from . import Blocks, Mirrored, Scripts, ScriptExtensions, OTTags
  14. __all__ = [
  15. # names from built-in unicodedata module
  16. "lookup",
  17. "name",
  18. "decimal",
  19. "digit",
  20. "numeric",
  21. "category",
  22. "bidirectional",
  23. "combining",
  24. "east_asian_width",
  25. "mirrored",
  26. "decomposition",
  27. "normalize",
  28. "unidata_version",
  29. "ucd_3_2_0",
  30. # additonal functions
  31. "block",
  32. "script",
  33. "script_extension",
  34. "script_name",
  35. "script_code",
  36. "script_horizontal_direction",
  37. "ot_tags_from_script",
  38. "ot_tag_to_script",
  39. ]
  40. def mirrored(code):
  41. """If code (unicode codepoint) has a mirrored version returns it, otherwise None."""
  42. return Mirrored.MIRRORED.get(code)
  43. def script(char):
  44. """Return the four-letter script code assigned to the Unicode character
  45. 'char' as string.
  46. >>> script("a")
  47. 'Latn'
  48. >>> script(",")
  49. 'Zyyy'
  50. >>> script(chr(0x10FFFF))
  51. 'Zzzz'
  52. """
  53. code = byteord(char)
  54. # 'bisect_right(a, x, lo=0, hi=len(a))' returns an insertion point which
  55. # comes after (to the right of) any existing entries of x in a, and it
  56. # partitions array a into two halves so that, for the left side
  57. # all(val <= x for val in a[lo:i]), and for the right side
  58. # all(val > x for val in a[i:hi]).
  59. # Our 'SCRIPT_RANGES' is a sorted list of ranges (only their starting
  60. # breakpoints); we want to use `bisect_right` to look up the range that
  61. # contains the given codepoint: i.e. whose start is less than or equal
  62. # to the codepoint. Thus, we subtract -1 from the index returned.
  63. i = bisect_right(Scripts.RANGES, code)
  64. return Scripts.VALUES[i - 1]
  65. def script_extension(char):
  66. """Return the script extension property assigned to the Unicode character
  67. 'char' as a set of string.
  68. >>> script_extension("a") == {'Latn'}
  69. True
  70. >>> script_extension(chr(0x060C)) == {'Nkoo', 'Arab', 'Rohg', 'Thaa', 'Syrc', 'Gara', 'Yezi'}
  71. True
  72. >>> script_extension(chr(0x10FFFF)) == {'Zzzz'}
  73. True
  74. """
  75. code = byteord(char)
  76. i = bisect_right(ScriptExtensions.RANGES, code)
  77. value = ScriptExtensions.VALUES[i - 1]
  78. if value is None:
  79. # code points not explicitly listed for Script Extensions
  80. # have as their value the corresponding Script property value
  81. return {script(char)}
  82. return value
  83. def script_name(code, default=KeyError):
  84. """Return the long, human-readable script name given a four-letter
  85. Unicode script code.
  86. If no matching name is found, a KeyError is raised by default.
  87. You can use the 'default' argument to return a fallback value (e.g.
  88. 'Unknown' or None) instead of throwing an error.
  89. """
  90. try:
  91. return str(Scripts.NAMES[code].replace("_", " "))
  92. except KeyError:
  93. if isinstance(default, type) and issubclass(default, KeyError):
  94. raise
  95. return default
  96. _normalize_re = re.compile(r"[-_ ]+")
  97. def _normalize_property_name(string):
  98. """Remove case, strip space, '-' and '_' for loose matching."""
  99. return _normalize_re.sub("", string).lower()
  100. _SCRIPT_CODES = {_normalize_property_name(v): k for k, v in Scripts.NAMES.items()}
  101. def script_code(script_name, default=KeyError):
  102. """Returns the four-letter Unicode script code from its long name
  103. If no matching script code is found, a KeyError is raised by default.
  104. You can use the 'default' argument to return a fallback string (e.g.
  105. 'Zzzz' or None) instead of throwing an error.
  106. """
  107. normalized_name = _normalize_property_name(script_name)
  108. try:
  109. return _SCRIPT_CODES[normalized_name]
  110. except KeyError:
  111. if isinstance(default, type) and issubclass(default, KeyError):
  112. raise
  113. return default
  114. # The data on script direction is taken from Harfbuzz source code:
  115. # https://github.com/harfbuzz/harfbuzz/blob/3.2.0/src/hb-common.cc#L514-L613
  116. # This in turn references the following "Script_Metadata" document:
  117. # https://docs.google.com/spreadsheets/d/1Y90M0Ie3MUJ6UVCRDOypOtijlMDLNNyyLk36T6iMu0o
  118. RTL_SCRIPTS = {
  119. # Unicode-1.1 additions
  120. "Arab", # Arabic
  121. "Hebr", # Hebrew
  122. # Unicode-3.0 additions
  123. "Syrc", # Syriac
  124. "Thaa", # Thaana
  125. # Unicode-4.0 additions
  126. "Cprt", # Cypriot
  127. # Unicode-4.1 additions
  128. "Khar", # Kharoshthi
  129. # Unicode-5.0 additions
  130. "Phnx", # Phoenician
  131. "Nkoo", # Nko
  132. # Unicode-5.1 additions
  133. "Lydi", # Lydian
  134. # Unicode-5.2 additions
  135. "Avst", # Avestan
  136. "Armi", # Imperial Aramaic
  137. "Phli", # Inscriptional Pahlavi
  138. "Prti", # Inscriptional Parthian
  139. "Sarb", # Old South Arabian
  140. "Orkh", # Old Turkic
  141. "Samr", # Samaritan
  142. # Unicode-6.0 additions
  143. "Mand", # Mandaic
  144. # Unicode-6.1 additions
  145. "Merc", # Meroitic Cursive
  146. "Mero", # Meroitic Hieroglyphs
  147. # Unicode-7.0 additions
  148. "Mani", # Manichaean
  149. "Mend", # Mende Kikakui
  150. "Nbat", # Nabataean
  151. "Narb", # Old North Arabian
  152. "Palm", # Palmyrene
  153. "Phlp", # Psalter Pahlavi
  154. # Unicode-8.0 additions
  155. "Hatr", # Hatran
  156. "Hung", # Old Hungarian
  157. # Unicode-9.0 additions
  158. "Adlm", # Adlam
  159. # Unicode-11.0 additions
  160. "Rohg", # Hanifi Rohingya
  161. "Sogo", # Old Sogdian
  162. "Sogd", # Sogdian
  163. # Unicode-12.0 additions
  164. "Elym", # Elymaic
  165. # Unicode-13.0 additions
  166. "Chrs", # Chorasmian
  167. "Yezi", # Yezidi
  168. # Unicode-14.0 additions
  169. "Ougr", # Old Uyghur
  170. # Unicode-16.0 additions
  171. "Gara", # Garay
  172. # Unicode-17.0 additions
  173. "Sidt", # Sidetic
  174. }
  175. HorizDirection = Literal["RTL", "LTR"]
  176. T = TypeVar("T")
  177. @overload
  178. def script_horizontal_direction(script_code: str, default: T) -> HorizDirection | T: ...
  179. @overload
  180. def script_horizontal_direction(
  181. script_code: str, default: type[KeyError] = KeyError
  182. ) -> HorizDirection: ...
  183. def script_horizontal_direction(
  184. script_code: str, default: T | type[KeyError] = KeyError
  185. ) -> HorizDirection | T:
  186. """Return "RTL" for scripts that contain right-to-left characters
  187. according to the Bidi_Class property. Otherwise return "LTR".
  188. """
  189. if script_code not in Scripts.NAMES:
  190. if isinstance(default, type) and issubclass(default, KeyError):
  191. raise default(script_code)
  192. return default
  193. return "RTL" if script_code in RTL_SCRIPTS else "LTR"
  194. def block(char):
  195. """Return the block property assigned to the Unicode character 'char'
  196. as a string.
  197. >>> block("a")
  198. 'Basic Latin'
  199. >>> block(chr(0x060C))
  200. 'Arabic'
  201. >>> block(chr(0xEFFFF))
  202. 'No_Block'
  203. """
  204. code = byteord(char)
  205. i = bisect_right(Blocks.RANGES, code)
  206. return Blocks.VALUES[i - 1]
  207. def ot_tags_from_script(script_code):
  208. """Return a list of OpenType script tags associated with a given
  209. Unicode script code.
  210. Return ['DFLT'] script tag for invalid/unknown script codes.
  211. """
  212. if script_code in OTTags.SCRIPT_EXCEPTIONS:
  213. return [OTTags.SCRIPT_EXCEPTIONS[script_code]]
  214. if script_code not in Scripts.NAMES:
  215. return [OTTags.DEFAULT_SCRIPT]
  216. script_tags = [script_code[0].lower() + script_code[1:]]
  217. if script_code in OTTags.NEW_SCRIPT_TAGS:
  218. script_tags.extend(OTTags.NEW_SCRIPT_TAGS[script_code])
  219. script_tags.reverse() # last in, first out
  220. return script_tags
  221. def ot_tag_to_script(tag):
  222. """Return the Unicode script code for the given OpenType script tag, or
  223. None for "DFLT" tag or if there is no Unicode script associated with it.
  224. Raises ValueError if the tag is invalid.
  225. """
  226. tag = tostr(tag).strip()
  227. if not tag or " " in tag or len(tag) > 4:
  228. raise ValueError("invalid OpenType tag: %r" % tag)
  229. if tag in OTTags.SCRIPT_ALIASES:
  230. tag = OTTags.SCRIPT_ALIASES[tag]
  231. while len(tag) != 4:
  232. tag += str(" ") # pad with spaces
  233. if tag == OTTags.DEFAULT_SCRIPT:
  234. # it's unclear which Unicode script the "DFLT" OpenType tag maps to,
  235. # so here we return None
  236. return None
  237. if tag in OTTags.NEW_SCRIPT_TAGS_REVERSED:
  238. return OTTags.NEW_SCRIPT_TAGS_REVERSED[tag]
  239. if tag in OTTags.SCRIPT_EXCEPTIONS_REVERSED:
  240. return OTTags.SCRIPT_EXCEPTIONS_REVERSED[tag]
  241. # This side of the conversion is fully algorithmic
  242. # Any spaces at the end of the tag are replaced by repeating the last
  243. # letter. Eg 'nko ' -> 'Nkoo'.
  244. # Change first char to uppercase
  245. script_code = tag[0].upper() + tag[1]
  246. for i in range(2, 4):
  247. script_code += script_code[i - 1] if tag[i] == " " else tag[i]
  248. if script_code not in Scripts.NAMES:
  249. return None
  250. return script_code