__init__.py 8.6 KB

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