cd.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. from __future__ import annotations
  2. import importlib
  3. from codecs import IncrementalDecoder
  4. from functools import lru_cache
  5. from .constant import (
  6. FREQUENCIES,
  7. KO_NAMES,
  8. LANGUAGE_SUPPORTED_COUNT,
  9. TOO_SMALL_SEQUENCE,
  10. ZH_NAMES,
  11. _FREQUENCIES_SET,
  12. _FREQUENCIES_RANK,
  13. )
  14. from .md import _ASCII_CHAR_INFO, _char_info, is_suspiciously_successive_range
  15. from .models import CoherenceMatches
  16. from .utils import (
  17. is_multi_byte_encoding,
  18. is_unicode_range_secondary,
  19. )
  20. def encoding_unicode_range(iana_name: str) -> list[str]:
  21. """
  22. Return associated unicode ranges in a single byte code page.
  23. """
  24. if is_multi_byte_encoding(iana_name):
  25. raise OSError( # Defensive:
  26. "Function not supported on multi-byte code page"
  27. )
  28. decoder = importlib.import_module(f"encodings.{iana_name}").IncrementalDecoder
  29. p: IncrementalDecoder = decoder(errors="ignore")
  30. seen_ranges: dict[str, int] = {}
  31. character_count: int = 0
  32. for i in range(0x40, 0xFF):
  33. chunk: str = p.decode(bytes([i]))
  34. if chunk:
  35. chunk_codepoint = ord(chunk)
  36. character_range: str | None = (
  37. _ASCII_CHAR_INFO[chunk_codepoint].range
  38. if chunk_codepoint < 128
  39. else _char_info(chunk).range
  40. )
  41. if character_range is None:
  42. continue
  43. if not is_unicode_range_secondary(character_range):
  44. if character_range not in seen_ranges:
  45. seen_ranges[character_range] = 0
  46. seen_ranges[character_range] += 1
  47. character_count += 1
  48. return sorted(
  49. [
  50. character_range
  51. for character_range in seen_ranges
  52. if seen_ranges[character_range] / character_count >= 0.15
  53. ]
  54. )
  55. def unicode_range_languages(primary_range: str) -> list[str]:
  56. """
  57. Return inferred languages used with a unicode range.
  58. """
  59. languages: list[str] = []
  60. for language, characters in FREQUENCIES.items():
  61. for character in characters:
  62. codepoint = ord(character)
  63. info = (
  64. _ASCII_CHAR_INFO[codepoint]
  65. if codepoint < 128
  66. else _char_info(character)
  67. )
  68. if info.range == primary_range:
  69. languages.append(language)
  70. break
  71. return languages
  72. @lru_cache()
  73. def encoding_languages(iana_name: str) -> list[str]:
  74. """
  75. Single-byte encoding language association. Some code page are heavily linked to particular language(s).
  76. This function does the correspondence.
  77. """
  78. try:
  79. unicode_ranges: list[str] = encoding_unicode_range(iana_name)
  80. except ImportError: # Defensive: encoding unavailable on this build.
  81. return []
  82. primary_range: str | None = None
  83. for specified_range in unicode_ranges:
  84. if "Latin" not in specified_range:
  85. primary_range = specified_range
  86. break
  87. if primary_range is None:
  88. return ["Latin Based"]
  89. return unicode_range_languages(primary_range)
  90. @lru_cache()
  91. def mb_encoding_languages(iana_name: str) -> list[str]:
  92. """
  93. Multi-byte encoding language association. Some code page are heavily linked to particular language(s).
  94. This function does the correspondence.
  95. """
  96. if (
  97. iana_name.startswith("shift_")
  98. or iana_name.startswith("iso2022_jp")
  99. or iana_name.startswith("euc_j")
  100. or iana_name == "cp932"
  101. ):
  102. return ["Japanese"]
  103. if iana_name.startswith("gb") or iana_name in ZH_NAMES:
  104. return ["Chinese"]
  105. if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES:
  106. return ["Korean"]
  107. return []
  108. @lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT)
  109. def get_target_features(language: str) -> tuple[bool, bool]:
  110. """
  111. Determine main aspects from a supported language if it contains accents and if is pure Latin.
  112. """
  113. target_have_accents: bool = False
  114. target_pure_latin: bool = True
  115. for character in FREQUENCIES[language]:
  116. codepoint = ord(character)
  117. info = _ASCII_CHAR_INFO[codepoint] if codepoint < 128 else _char_info(character)
  118. if not target_have_accents and info.accentuated:
  119. target_have_accents = True
  120. if target_pure_latin and not info.latin:
  121. target_pure_latin = False
  122. return target_have_accents, target_pure_latin
  123. def alphabet_languages(
  124. characters: list[str], ignore_non_latin: bool = False
  125. ) -> list[str]:
  126. """
  127. Return associated languages associated to given characters.
  128. """
  129. languages: list[tuple[str, float]] = []
  130. characters_set: frozenset[str] = frozenset(characters)
  131. source_have_accents = False
  132. for character in characters:
  133. codepoint = ord(character)
  134. info = _ASCII_CHAR_INFO[codepoint] if codepoint < 128 else _char_info(character)
  135. if info.accentuated:
  136. source_have_accents = True
  137. break
  138. for language, language_characters in FREQUENCIES.items():
  139. target_have_accents, target_pure_latin = get_target_features(language)
  140. if ignore_non_latin and not target_pure_latin:
  141. continue
  142. if not target_have_accents and source_have_accents:
  143. continue
  144. character_count: int = len(language_characters)
  145. character_match_count: int = len(_FREQUENCIES_SET[language] & characters_set)
  146. ratio: float = character_match_count / character_count
  147. if ratio >= 0.2:
  148. languages.append((language, ratio))
  149. languages = sorted(languages, key=lambda x: x[1], reverse=True)
  150. return [compatible_language[0] for compatible_language in languages]
  151. def characters_popularity_compare(
  152. language: str, ordered_characters: list[str]
  153. ) -> float:
  154. """
  155. Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language.
  156. The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit).
  157. Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.)
  158. """
  159. if language not in FREQUENCIES:
  160. raise ValueError(f"{language} not available") # Defensive:
  161. character_approved_count: int = 0
  162. lang_rank: dict[str, int] = _FREQUENCIES_RANK[language]
  163. ordered_characters_count: int = len(ordered_characters)
  164. target_language_characters_count: int = len(FREQUENCIES[language])
  165. large_alphabet: bool = target_language_characters_count > 26
  166. large_alphabet_threshold: float = target_language_characters_count / 3
  167. expected_projection_ratio: float = (
  168. target_language_characters_count / ordered_characters_count
  169. )
  170. # Single pass: characters present in the language vocabulary, as
  171. # (language rank, popularity rank) pairs. The scoring below only ever
  172. # needs ranks, never the characters themselves.
  173. common_lr: list[int] = []
  174. common_orr: list[int] = []
  175. for popularity_rank, character in enumerate(ordered_characters):
  176. language_rank = lang_rank.get(character)
  177. if language_rank is not None:
  178. common_lr.append(language_rank)
  179. common_orr.append(popularity_rank)
  180. for character_rank_in_language, character_rank in zip(common_lr, common_orr):
  181. character_rank_projection: int = int(character_rank * expected_projection_ratio)
  182. if (
  183. not large_alphabet
  184. and abs(character_rank_projection - character_rank_in_language) > 4
  185. ):
  186. continue
  187. if (
  188. large_alphabet
  189. and abs(character_rank_projection - character_rank_in_language)
  190. < large_alphabet_threshold
  191. ):
  192. character_approved_count += 1
  193. continue
  194. if character_rank_in_language == 0:
  195. # before_match_count is structurally 0 here (no pair can have a
  196. # smaller language rank): the historic "before <= 4" acceptance
  197. # always holds. (The symmetric "after_len == 0" case is
  198. # impossible: language ranks are strictly below the language
  199. # character count, hence after_len >= 1.)
  200. character_approved_count += 1
  201. continue
  202. after_len: int = target_language_characters_count - character_rank_in_language
  203. # Count how many characters appear "before" in both orderings, and
  204. # how many appear "at or after" in both orderings. Both counts grow
  205. # monotonically and the approval thresholds
  206. # (before / rank >= 0.4 or after / after_len >= 0.4) are known
  207. # upfront, expressed below as exact integer comparisons: exit as
  208. # soon as one is crossed.
  209. before_match_count: int = 0
  210. after_match_count: int = 0
  211. for lr_i, orr_i in zip(common_lr, common_orr):
  212. if lr_i < character_rank_in_language:
  213. if orr_i < character_rank:
  214. before_match_count += 1
  215. if 5 * before_match_count >= 2 * character_rank_in_language:
  216. character_approved_count += 1
  217. break
  218. else:
  219. if orr_i >= character_rank:
  220. after_match_count += 1
  221. if 5 * after_match_count >= 2 * after_len:
  222. character_approved_count += 1
  223. break
  224. return character_approved_count / len(ordered_characters)
  225. def alpha_unicode_split(decoded_sequence: str) -> list[str]:
  226. """
  227. Given a decoded text sequence, return a list of str. Unicode range / alphabet separation.
  228. Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list;
  229. One containing the latin letters and the other hebrew.
  230. """
  231. layers: dict[str, list[str]] = {}
  232. # Fast path: track single-layer key to skip dict iteration for single-script text.
  233. single_layer_key: str | None = None
  234. multi_layer: bool = False
  235. # Cache the last character_range and its resolved layer to avoid repeated
  236. # is_suspiciously_successive_range calls for consecutive same-range chars.
  237. prev_character_range: str | None = None
  238. prev_layer_target: str | None = None
  239. for character in decoded_sequence:
  240. # Reuse the per-codepoint CharInfo cache: info.alpha and info.range
  241. # are computed with the very same str.isalpha() / unicode_range()
  242. # calls this loop historically made per character occurrence.
  243. codepoint: int = ord(character)
  244. if codepoint < 128:
  245. info = _ASCII_CHAR_INFO[codepoint]
  246. else:
  247. info = _char_info(character)
  248. if not info.alpha:
  249. continue
  250. character_range: str | None = info.range
  251. if character_range is None:
  252. continue
  253. # Fast path: same range as previous character → reuse cached layer target.
  254. if character_range == prev_character_range:
  255. if prev_layer_target is not None:
  256. layers[prev_layer_target].append(character)
  257. continue
  258. layer_target_range: str | None = None
  259. if multi_layer:
  260. for discovered_range in layers:
  261. if not is_suspiciously_successive_range(
  262. discovered_range, character_range
  263. ):
  264. layer_target_range = discovered_range
  265. break
  266. elif single_layer_key is not None:
  267. if not is_suspiciously_successive_range(single_layer_key, character_range):
  268. layer_target_range = single_layer_key
  269. if layer_target_range is None:
  270. layer_target_range = character_range
  271. if layer_target_range not in layers:
  272. layers[layer_target_range] = []
  273. if single_layer_key is None:
  274. single_layer_key = layer_target_range
  275. else:
  276. multi_layer = True
  277. layers[layer_target_range].append(character)
  278. # Cache for next iteration
  279. prev_character_range = character_range
  280. prev_layer_target = layer_target_range
  281. return ["".join(chars).lower() for chars in layers.values()]
  282. def merge_coherence_ratios(results: list[CoherenceMatches]) -> CoherenceMatches:
  283. """
  284. This function merge results previously given by the function coherence_ratio.
  285. The return type is the same as coherence_ratio.
  286. """
  287. per_language_ratios: dict[str, list[float]] = {}
  288. for result in results:
  289. for sub_result in result:
  290. language, ratio = sub_result
  291. if language not in per_language_ratios:
  292. per_language_ratios[language] = [ratio]
  293. continue
  294. per_language_ratios[language].append(ratio)
  295. merge = [
  296. (
  297. language,
  298. round(
  299. sum(per_language_ratios[language]) / len(per_language_ratios[language]),
  300. 4,
  301. ),
  302. )
  303. for language in per_language_ratios
  304. ]
  305. return sorted(merge, key=lambda x: x[1], reverse=True)
  306. def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches:
  307. """
  308. We shall NOT return "English—" in CoherenceMatches because it is an alternative
  309. of "English". This function only keeps the best match and remove the em-dash in it.
  310. """
  311. index_results: dict[str, list[float]] = dict()
  312. for result in results:
  313. language, ratio = result
  314. no_em_name: str = language.replace("—", "")
  315. if no_em_name not in index_results:
  316. index_results[no_em_name] = []
  317. index_results[no_em_name].append(ratio)
  318. if any(len(index_results[e]) > 1 for e in index_results):
  319. filtered_results: CoherenceMatches = []
  320. for language in index_results:
  321. filtered_results.append((language, max(index_results[language])))
  322. return filtered_results
  323. return results
  324. def coherence_ratio(
  325. decoded_sequence: str, threshold: float = 0.1, lg_inclusion: str | None = None
  326. ) -> CoherenceMatches:
  327. """
  328. Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers.
  329. A layer = Character extraction by alphabets/ranges.
  330. """
  331. results: list[tuple[str, float]] = []
  332. ignore_non_latin: bool = False
  333. sufficient_match_count: int = 0
  334. lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else []
  335. if "Latin Based" in lg_inclusion_list:
  336. ignore_non_latin = True
  337. lg_inclusion_list.remove("Latin Based")
  338. for layer in alpha_unicode_split(decoded_sequence):
  339. # Native counting + stable sort reproduce Counter.most_common()
  340. # ordering exactly (ties keep first-appearance order) without the
  341. # interpreted Counter machinery in the compiled hot path.
  342. char_counts: dict[str, int] = {}
  343. for layer_character in layer:
  344. char_counts[layer_character] = char_counts.get(layer_character, 0) + 1
  345. character_count: int = len(layer)
  346. if character_count <= TOO_SMALL_SEQUENCE:
  347. continue
  348. popular_character_ordered: list[str] = [
  349. item[0]
  350. for item in sorted(
  351. char_counts.items(), key=lambda item: item[1], reverse=True
  352. )
  353. ]
  354. for language in lg_inclusion_list or alphabet_languages(
  355. popular_character_ordered, ignore_non_latin
  356. ):
  357. ratio: float = characters_popularity_compare(
  358. language, popular_character_ordered
  359. )
  360. if ratio < threshold:
  361. continue
  362. elif ratio >= 0.8:
  363. sufficient_match_count += 1
  364. results.append((language, round(ratio, 4)))
  365. if sufficient_match_count >= 3:
  366. break
  367. return sorted(
  368. filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True
  369. )