cd.py 12 KB

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