cd.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import importlib
  2. from codecs import IncrementalDecoder
  3. from collections import Counter, OrderedDict
  4. from functools import lru_cache
  5. from typing import Dict, List, Optional, Tuple
  6. from .assets import FREQUENCIES
  7. from .constant import KO_NAMES, LANGUAGE_SUPPORTED_COUNT, TOO_SMALL_SEQUENCE, ZH_NAMES
  8. from .md import is_suspiciously_successive_range
  9. from .models import CoherenceMatches
  10. from .utils import (
  11. is_accentuated,
  12. is_latin,
  13. is_multi_byte_encoding,
  14. is_unicode_range_secondary,
  15. unicode_range,
  16. )
  17. def encoding_unicode_range(iana_name: str) -> List[str]:
  18. """
  19. Return associated unicode ranges in a single byte code page.
  20. """
  21. if is_multi_byte_encoding(iana_name):
  22. raise IOError("Function not supported on multi-byte code page")
  23. decoder = importlib.import_module("encodings.{}".format(iana_name)).IncrementalDecoder # type: ignore
  24. p = decoder(errors="ignore") # type: IncrementalDecoder
  25. seen_ranges = {} # type: Dict[str, int]
  26. character_count = 0 # type: int
  27. for i in range(0x40, 0xFF):
  28. chunk = p.decode(bytes([i])) # type: str
  29. if chunk:
  30. character_range = unicode_range(chunk) # type: Optional[str]
  31. if character_range is None:
  32. continue
  33. if is_unicode_range_secondary(character_range) is False:
  34. if character_range not in seen_ranges:
  35. seen_ranges[character_range] = 0
  36. seen_ranges[character_range] += 1
  37. character_count += 1
  38. return sorted(
  39. [
  40. character_range
  41. for character_range in seen_ranges
  42. if seen_ranges[character_range] / character_count >= 0.15
  43. ]
  44. )
  45. def unicode_range_languages(primary_range: str) -> List[str]:
  46. """
  47. Return inferred languages used with a unicode range.
  48. """
  49. languages = [] # type: List[str]
  50. for language, characters in FREQUENCIES.items():
  51. for character in characters:
  52. if unicode_range(character) == primary_range:
  53. languages.append(language)
  54. break
  55. return languages
  56. @lru_cache()
  57. def encoding_languages(iana_name: str) -> List[str]:
  58. """
  59. Single-byte encoding language association. Some code page are heavily linked to particular language(s).
  60. This function does the correspondence.
  61. """
  62. unicode_ranges = encoding_unicode_range(iana_name) # type: List[str]
  63. primary_range = None # type: Optional[str]
  64. for specified_range in unicode_ranges:
  65. if "Latin" not in specified_range:
  66. primary_range = specified_range
  67. break
  68. if primary_range is None:
  69. return ["Latin Based"]
  70. return unicode_range_languages(primary_range)
  71. @lru_cache()
  72. def mb_encoding_languages(iana_name: str) -> List[str]:
  73. """
  74. Multi-byte encoding language association. Some code page are heavily linked to particular language(s).
  75. This function does the correspondence.
  76. """
  77. if (
  78. iana_name.startswith("shift_")
  79. or iana_name.startswith("iso2022_jp")
  80. or iana_name.startswith("euc_j")
  81. or iana_name == "cp932"
  82. ):
  83. return ["Japanese"]
  84. if iana_name.startswith("gb") or iana_name in ZH_NAMES:
  85. return ["Chinese", "Classical Chinese"]
  86. if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES:
  87. return ["Korean"]
  88. return []
  89. @lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT)
  90. def get_target_features(language: str) -> Tuple[bool, bool]:
  91. """
  92. Determine main aspects from a supported language if it contains accents and if is pure Latin.
  93. """
  94. target_have_accents = False # type: bool
  95. target_pure_latin = True # type: bool
  96. for character in FREQUENCIES[language]:
  97. if not target_have_accents and is_accentuated(character):
  98. target_have_accents = True
  99. if target_pure_latin and is_latin(character) is False:
  100. target_pure_latin = False
  101. return target_have_accents, target_pure_latin
  102. def alphabet_languages(
  103. characters: List[str], ignore_non_latin: bool = False
  104. ) -> List[str]:
  105. """
  106. Return associated languages associated to given characters.
  107. """
  108. languages = [] # type: List[Tuple[str, float]]
  109. source_have_accents = any(is_accentuated(character) for character in characters)
  110. for language, language_characters in FREQUENCIES.items():
  111. target_have_accents, target_pure_latin = get_target_features(language)
  112. if ignore_non_latin and target_pure_latin is False:
  113. continue
  114. if target_have_accents is False and source_have_accents:
  115. continue
  116. character_count = len(language_characters) # type: int
  117. character_match_count = len(
  118. [c for c in language_characters if c in characters]
  119. ) # type: int
  120. ratio = character_match_count / character_count # type: float
  121. if ratio >= 0.2:
  122. languages.append((language, ratio))
  123. languages = sorted(languages, key=lambda x: x[1], reverse=True)
  124. return [compatible_language[0] for compatible_language in languages]
  125. def characters_popularity_compare(
  126. language: str, ordered_characters: List[str]
  127. ) -> float:
  128. """
  129. Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language.
  130. The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit).
  131. Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.)
  132. """
  133. if language not in FREQUENCIES:
  134. raise ValueError("{} not available".format(language))
  135. character_approved_count = 0 # type: int
  136. for character in ordered_characters:
  137. if character not in FREQUENCIES[language]:
  138. continue
  139. characters_before_source = FREQUENCIES[language][
  140. 0 : FREQUENCIES[language].index(character)
  141. ] # type: List[str]
  142. characters_after_source = FREQUENCIES[language][
  143. FREQUENCIES[language].index(character) :
  144. ] # type: List[str]
  145. characters_before = ordered_characters[
  146. 0 : ordered_characters.index(character)
  147. ] # type: List[str]
  148. characters_after = ordered_characters[
  149. ordered_characters.index(character) :
  150. ] # type: List[str]
  151. before_match_count = [
  152. e in characters_before for e in characters_before_source
  153. ].count(
  154. True
  155. ) # type: int
  156. after_match_count = [
  157. e in characters_after for e in characters_after_source
  158. ].count(
  159. True
  160. ) # type: int
  161. if len(characters_before_source) == 0 and before_match_count <= 4:
  162. character_approved_count += 1
  163. continue
  164. if len(characters_after_source) == 0 and after_match_count <= 4:
  165. character_approved_count += 1
  166. continue
  167. if (
  168. before_match_count / len(characters_before_source) >= 0.4
  169. or after_match_count / len(characters_after_source) >= 0.4
  170. ):
  171. character_approved_count += 1
  172. continue
  173. return character_approved_count / len(ordered_characters)
  174. def alpha_unicode_split(decoded_sequence: str) -> List[str]:
  175. """
  176. Given a decoded text sequence, return a list of str. Unicode range / alphabet separation.
  177. Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list;
  178. One containing the latin letters and the other hebrew.
  179. """
  180. layers = OrderedDict() # type: Dict[str, str]
  181. for character in decoded_sequence:
  182. if character.isalpha() is False:
  183. continue
  184. character_range = unicode_range(character) # type: Optional[str]
  185. if character_range is None:
  186. continue
  187. layer_target_range = None # type: Optional[str]
  188. for discovered_range in layers:
  189. if (
  190. is_suspiciously_successive_range(discovered_range, character_range)
  191. is False
  192. ):
  193. layer_target_range = discovered_range
  194. break
  195. if layer_target_range is None:
  196. layer_target_range = character_range
  197. if layer_target_range not in layers:
  198. layers[layer_target_range] = character.lower()
  199. continue
  200. layers[layer_target_range] += character.lower()
  201. return list(layers.values())
  202. def merge_coherence_ratios(results: List[CoherenceMatches]) -> CoherenceMatches:
  203. """
  204. This function merge results previously given by the function coherence_ratio.
  205. The return type is the same as coherence_ratio.
  206. """
  207. per_language_ratios = OrderedDict() # type: Dict[str, List[float]]
  208. for result in results:
  209. for sub_result in result:
  210. language, ratio = sub_result
  211. if language not in per_language_ratios:
  212. per_language_ratios[language] = [ratio]
  213. continue
  214. per_language_ratios[language].append(ratio)
  215. merge = [
  216. (
  217. language,
  218. round(
  219. sum(per_language_ratios[language]) / len(per_language_ratios[language]),
  220. 4,
  221. ),
  222. )
  223. for language in per_language_ratios
  224. ]
  225. return sorted(merge, key=lambda x: x[1], reverse=True)
  226. @lru_cache(maxsize=2048)
  227. def coherence_ratio(
  228. decoded_sequence: str, threshold: float = 0.1, lg_inclusion: Optional[str] = None
  229. ) -> CoherenceMatches:
  230. """
  231. Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers.
  232. A layer = Character extraction by alphabets/ranges.
  233. """
  234. results = [] # type: List[Tuple[str, float]]
  235. ignore_non_latin = False # type: bool
  236. sufficient_match_count = 0 # type: int
  237. lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else []
  238. if "Latin Based" in lg_inclusion_list:
  239. ignore_non_latin = True
  240. lg_inclusion_list.remove("Latin Based")
  241. for layer in alpha_unicode_split(decoded_sequence):
  242. sequence_frequencies = Counter(layer) # type: Counter
  243. most_common = sequence_frequencies.most_common()
  244. character_count = sum(o for c, o in most_common) # type: int
  245. if character_count <= TOO_SMALL_SEQUENCE:
  246. continue
  247. popular_character_ordered = [c for c, o in most_common] # type: List[str]
  248. for language in lg_inclusion_list or alphabet_languages(
  249. popular_character_ordered, ignore_non_latin
  250. ):
  251. ratio = characters_popularity_compare(
  252. language, popular_character_ordered
  253. ) # type: float
  254. if ratio < threshold:
  255. continue
  256. elif ratio >= 0.8:
  257. sufficient_match_count += 1
  258. results.append((language, round(ratio, 4)))
  259. if sufficient_match_count >= 3:
  260. break
  261. return sorted(results, key=lambda x: x[1], reverse=True)