cd.py 9.0 KB

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