cd.py 12 KB

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