Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cd.py 12KB

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