m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

399 lines
13 KiB

6 months ago
  1. from . import idnadata
  2. import bisect
  3. import unicodedata
  4. import re
  5. from typing import Union, Optional
  6. from .intranges import intranges_contain
  7. _virama_combining_class = 9
  8. _alabel_prefix = b'xn--'
  9. _unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
  10. class IDNAError(UnicodeError):
  11. """ Base exception for all IDNA-encoding related problems """
  12. pass
  13. class IDNABidiError(IDNAError):
  14. """ Exception when bidirectional requirements are not satisfied """
  15. pass
  16. class InvalidCodepoint(IDNAError):
  17. """ Exception when a disallowed or unallocated codepoint is used """
  18. pass
  19. class InvalidCodepointContext(IDNAError):
  20. """ Exception when the codepoint is not valid in the context it is used """
  21. pass
  22. def _combining_class(cp: int) -> int:
  23. v = unicodedata.combining(chr(cp))
  24. if v == 0:
  25. if not unicodedata.name(chr(cp)):
  26. raise ValueError('Unknown character in unicodedata')
  27. return v
  28. def _is_script(cp: str, script: str) -> bool:
  29. return intranges_contain(ord(cp), idnadata.scripts[script])
  30. def _punycode(s: str) -> bytes:
  31. return s.encode('punycode')
  32. def _unot(s: int) -> str:
  33. return 'U+{:04X}'.format(s)
  34. def valid_label_length(label: Union[bytes, str]) -> bool:
  35. if len(label) > 63:
  36. return False
  37. return True
  38. def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool:
  39. if len(label) > (254 if trailing_dot else 253):
  40. return False
  41. return True
  42. def check_bidi(label: str, check_ltr: bool = False) -> bool:
  43. # Bidi rules should only be applied if string contains RTL characters
  44. bidi_label = False
  45. for (idx, cp) in enumerate(label, 1):
  46. direction = unicodedata.bidirectional(cp)
  47. if direction == '':
  48. # String likely comes from a newer version of Unicode
  49. raise IDNABidiError('Unknown directionality in label {} at position {}'.format(repr(label), idx))
  50. if direction in ['R', 'AL', 'AN']:
  51. bidi_label = True
  52. if not bidi_label and not check_ltr:
  53. return True
  54. # Bidi rule 1
  55. direction = unicodedata.bidirectional(label[0])
  56. if direction in ['R', 'AL']:
  57. rtl = True
  58. elif direction == 'L':
  59. rtl = False
  60. else:
  61. raise IDNABidiError('First codepoint in label {} must be directionality L, R or AL'.format(repr(label)))
  62. valid_ending = False
  63. number_type = None # type: Optional[str]
  64. for (idx, cp) in enumerate(label, 1):
  65. direction = unicodedata.bidirectional(cp)
  66. if rtl:
  67. # Bidi rule 2
  68. if not direction in ['R', 'AL', 'AN', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']:
  69. raise IDNABidiError('Invalid direction for codepoint at position {} in a right-to-left label'.format(idx))
  70. # Bidi rule 3
  71. if direction in ['R', 'AL', 'EN', 'AN']:
  72. valid_ending = True
  73. elif direction != 'NSM':
  74. valid_ending = False
  75. # Bidi rule 4
  76. if direction in ['AN', 'EN']:
  77. if not number_type:
  78. number_type = direction
  79. else:
  80. if number_type != direction:
  81. raise IDNABidiError('Can not mix numeral types in a right-to-left label')
  82. else:
  83. # Bidi rule 5
  84. if not direction in ['L', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']:
  85. raise IDNABidiError('Invalid direction for codepoint at position {} in a left-to-right label'.format(idx))
  86. # Bidi rule 6
  87. if direction in ['L', 'EN']:
  88. valid_ending = True
  89. elif direction != 'NSM':
  90. valid_ending = False
  91. if not valid_ending:
  92. raise IDNABidiError('Label ends with illegal codepoint directionality')
  93. return True
  94. def check_initial_combiner(label: str) -> bool:
  95. if unicodedata.category(label[0])[0] == 'M':
  96. raise IDNAError('Label begins with an illegal combining character')
  97. return True
  98. def check_hyphen_ok(label: str) -> bool:
  99. if label[2:4] == '--':
  100. raise IDNAError('Label has disallowed hyphens in 3rd and 4th position')
  101. if label[0] == '-' or label[-1] == '-':
  102. raise IDNAError('Label must not start or end with a hyphen')
  103. return True
  104. def check_nfc(label: str) -> None:
  105. if unicodedata.normalize('NFC', label) != label:
  106. raise IDNAError('Label must be in Normalization Form C')
  107. def valid_contextj(label: str, pos: int) -> bool:
  108. cp_value = ord(label[pos])
  109. if cp_value == 0x200c:
  110. if pos > 0:
  111. if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
  112. return True
  113. ok = False
  114. for i in range(pos-1, -1, -1):
  115. joining_type = idnadata.joining_types.get(ord(label[i]))
  116. if joining_type == ord('T'):
  117. continue
  118. elif joining_type in [ord('L'), ord('D')]:
  119. ok = True
  120. break
  121. else:
  122. break
  123. if not ok:
  124. return False
  125. ok = False
  126. for i in range(pos+1, len(label)):
  127. joining_type = idnadata.joining_types.get(ord(label[i]))
  128. if joining_type == ord('T'):
  129. continue
  130. elif joining_type in [ord('R'), ord('D')]:
  131. ok = True
  132. break
  133. else:
  134. break
  135. return ok
  136. if cp_value == 0x200d:
  137. if pos > 0:
  138. if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
  139. return True
  140. return False
  141. else:
  142. return False
  143. def valid_contexto(label: str, pos: int, exception: bool = False) -> bool:
  144. cp_value = ord(label[pos])
  145. if cp_value == 0x00b7:
  146. if 0 < pos < len(label)-1:
  147. if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c:
  148. return True
  149. return False
  150. elif cp_value == 0x0375:
  151. if pos < len(label)-1 and len(label) > 1:
  152. return _is_script(label[pos + 1], 'Greek')
  153. return False
  154. elif cp_value == 0x05f3 or cp_value == 0x05f4:
  155. if pos > 0:
  156. return _is_script(label[pos - 1], 'Hebrew')
  157. return False
  158. elif cp_value == 0x30fb:
  159. for cp in label:
  160. if cp == '\u30fb':
  161. continue
  162. if _is_script(cp, 'Hiragana') or _is_script(cp, 'Katakana') or _is_script(cp, 'Han'):
  163. return True
  164. return False
  165. elif 0x660 <= cp_value <= 0x669:
  166. for cp in label:
  167. if 0x6f0 <= ord(cp) <= 0x06f9:
  168. return False
  169. return True
  170. elif 0x6f0 <= cp_value <= 0x6f9:
  171. for cp in label:
  172. if 0x660 <= ord(cp) <= 0x0669:
  173. return False
  174. return True
  175. return False
  176. def check_label(label: Union[str, bytes, bytearray]) -> None:
  177. if isinstance(label, (bytes, bytearray)):
  178. label = label.decode('utf-8')
  179. if len(label) == 0:
  180. raise IDNAError('Empty Label')
  181. check_nfc(label)
  182. check_hyphen_ok(label)
  183. check_initial_combiner(label)
  184. for (pos, cp) in enumerate(label):
  185. cp_value = ord(cp)
  186. if intranges_contain(cp_value, idnadata.codepoint_classes['PVALID']):
  187. continue
  188. elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTJ']):
  189. try:
  190. if not valid_contextj(label, pos):
  191. raise InvalidCodepointContext('Joiner {} not allowed at position {} in {}'.format(
  192. _unot(cp_value), pos+1, repr(label)))
  193. except ValueError:
  194. raise IDNAError('Unknown codepoint adjacent to joiner {} at position {} in {}'.format(
  195. _unot(cp_value), pos+1, repr(label)))
  196. elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTO']):
  197. if not valid_contexto(label, pos):
  198. raise InvalidCodepointContext('Codepoint {} not allowed at position {} in {}'.format(_unot(cp_value), pos+1, repr(label)))
  199. else:
  200. raise InvalidCodepoint('Codepoint {} at position {} of {} not allowed'.format(_unot(cp_value), pos+1, repr(label)))
  201. check_bidi(label)
  202. def alabel(label: str) -> bytes:
  203. try:
  204. label_bytes = label.encode('ascii')
  205. ulabel(label_bytes)
  206. if not valid_label_length(label_bytes):
  207. raise IDNAError('Label too long')
  208. return label_bytes
  209. except UnicodeEncodeError:
  210. pass
  211. check_label(label)
  212. label_bytes = _alabel_prefix + _punycode(label)
  213. if not valid_label_length(label_bytes):
  214. raise IDNAError('Label too long')
  215. return label_bytes
  216. def ulabel(label: Union[str, bytes, bytearray]) -> str:
  217. if not isinstance(label, (bytes, bytearray)):
  218. try:
  219. label_bytes = label.encode('ascii')
  220. except UnicodeEncodeError:
  221. check_label(label)
  222. return label
  223. else:
  224. label_bytes = label
  225. label_bytes = label_bytes.lower()
  226. if label_bytes.startswith(_alabel_prefix):
  227. label_bytes = label_bytes[len(_alabel_prefix):]
  228. if not label_bytes:
  229. raise IDNAError('Malformed A-label, no Punycode eligible content found')
  230. if label_bytes.decode('ascii')[-1] == '-':
  231. raise IDNAError('A-label must not end with a hyphen')
  232. else:
  233. check_label(label_bytes)
  234. return label_bytes.decode('ascii')
  235. try:
  236. label = label_bytes.decode('punycode')
  237. except UnicodeError:
  238. raise IDNAError('Invalid A-label')
  239. check_label(label)
  240. return label
  241. def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:
  242. """Re-map the characters in the string according to UTS46 processing."""
  243. from .uts46data import uts46data
  244. output = ''
  245. for pos, char in enumerate(domain):
  246. code_point = ord(char)
  247. try:
  248. uts46row = uts46data[code_point if code_point < 256 else
  249. bisect.bisect_left(uts46data, (code_point, 'Z')) - 1]
  250. status = uts46row[1]
  251. replacement = None # type: Optional[str]
  252. if len(uts46row) == 3:
  253. replacement = uts46row[2]
  254. if (status == 'V' or
  255. (status == 'D' and not transitional) or
  256. (status == '3' and not std3_rules and replacement is None)):
  257. output += char
  258. elif replacement is not None and (status == 'M' or
  259. (status == '3' and not std3_rules) or
  260. (status == 'D' and transitional)):
  261. output += replacement
  262. elif status != 'I':
  263. raise IndexError()
  264. except IndexError:
  265. raise InvalidCodepoint(
  266. 'Codepoint {} not allowed at position {} in {}'.format(
  267. _unot(code_point), pos + 1, repr(domain)))
  268. return unicodedata.normalize('NFC', output)
  269. def encode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False, transitional: bool = False) -> bytes:
  270. if not isinstance(s, str):
  271. try:
  272. s = str(s, 'ascii')
  273. except UnicodeDecodeError:
  274. raise IDNAError('should pass a unicode string to the function rather than a byte string.')
  275. if uts46:
  276. s = uts46_remap(s, std3_rules, transitional)
  277. trailing_dot = False
  278. result = []
  279. if strict:
  280. labels = s.split('.')
  281. else:
  282. labels = _unicode_dots_re.split(s)
  283. if not labels or labels == ['']:
  284. raise IDNAError('Empty domain')
  285. if labels[-1] == '':
  286. del labels[-1]
  287. trailing_dot = True
  288. for label in labels:
  289. s = alabel(label)
  290. if s:
  291. result.append(s)
  292. else:
  293. raise IDNAError('Empty label')
  294. if trailing_dot:
  295. result.append(b'')
  296. s = b'.'.join(result)
  297. if not valid_string_length(s, trailing_dot):
  298. raise IDNAError('Domain too long')
  299. return s
  300. def decode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False) -> str:
  301. try:
  302. if not isinstance(s, str):
  303. s = str(s, 'ascii')
  304. except UnicodeDecodeError:
  305. raise IDNAError('Invalid ASCII in A-label')
  306. if uts46:
  307. s = uts46_remap(s, std3_rules, False)
  308. trailing_dot = False
  309. result = []
  310. if not strict:
  311. labels = _unicode_dots_re.split(s)
  312. else:
  313. labels = s.split('.')
  314. if not labels or labels == ['']:
  315. raise IDNAError('Empty domain')
  316. if not labels[-1]:
  317. del labels[-1]
  318. trailing_dot = True
  319. for label in labels:
  320. s = ulabel(label)
  321. if s:
  322. result.append(s)
  323. else:
  324. raise IDNAError('Empty label')
  325. if trailing_dot:
  326. result.append('')
  327. return '.'.join(result)