models.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. from __future__ import annotations
  2. from encodings.aliases import aliases
  3. from re import sub
  4. from typing import Any, Iterator, List, Tuple
  5. from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE
  6. from .utils import iana_name, is_multi_byte_encoding, unicode_range
  7. class CharsetMatch:
  8. def __init__(
  9. self,
  10. payload: bytes | bytearray,
  11. guessed_encoding: str,
  12. mean_mess_ratio: float,
  13. has_sig_or_bom: bool,
  14. languages: CoherenceMatches,
  15. decoded_payload: str | None = None,
  16. preemptive_declaration: str | None = None,
  17. ):
  18. self._payload: bytes | bytearray = payload
  19. self._encoding: str = guessed_encoding
  20. self._mean_mess_ratio: float = mean_mess_ratio
  21. self._languages: CoherenceMatches = languages
  22. self._has_sig_or_bom: bool = has_sig_or_bom
  23. self._unicode_ranges: list[str] | None = None
  24. self._leaves: list[CharsetMatch] = []
  25. self._mean_coherence_ratio: float = 0.0
  26. self._output_payload: bytes | None = None
  27. self._output_encoding: str | None = None
  28. self._string: str | None = decoded_payload
  29. self._preemptive_declaration: str | None = preemptive_declaration
  30. def __eq__(self, other: object) -> bool:
  31. if not isinstance(other, CharsetMatch):
  32. if isinstance(other, str):
  33. # Use non-strict iana_name so an operand that is not a known
  34. # encoding alias compares unequal instead of raising, keeping
  35. # __eq__ total as the data model requires (mirrors the lookup
  36. # in CharsetMatches.__getitem__).
  37. return iana_name(other, False) == self.encoding
  38. return False
  39. return self.encoding == other.encoding and self.fingerprint == other.fingerprint
  40. def __lt__(self, other: object) -> bool:
  41. """
  42. Implemented to make sorted available upon CharsetMatches items.
  43. """
  44. if not isinstance(other, CharsetMatch):
  45. raise ValueError
  46. chaos_difference: float = abs(self.chaos - other.chaos)
  47. coherence_difference: float = abs(self.coherence - other.coherence)
  48. # Below 0.5% difference --> Use Coherence
  49. if chaos_difference < 0.005 and coherence_difference > 0.02:
  50. return self.coherence > other.coherence
  51. elif chaos_difference < 0.005 and coherence_difference <= 0.02:
  52. # When having a difficult decision, use the result that decoded as many multi-byte as possible.
  53. # preserve RAM usage!
  54. if len(self._payload) >= TOO_BIG_SEQUENCE:
  55. return self.chaos < other.chaos
  56. return self.multi_byte_usage > other.multi_byte_usage
  57. return self.chaos < other.chaos
  58. @property
  59. def multi_byte_usage(self) -> float:
  60. # Empty payloads are valid (from_bytes(b"") returns a match); avoid /0.
  61. raw_len = len(self.raw)
  62. if raw_len == 0:
  63. return 0.0
  64. return 1.0 - (len(str(self)) / raw_len)
  65. def __str__(self) -> str:
  66. # Lazy Str Loading
  67. if self._string is None:
  68. self._string = str(self._payload, self._encoding, "strict")
  69. # UTF-7 BOM is encoded in modified Base64 whose byte boundary
  70. # can overlap with the next character, so raw-byte stripping
  71. # is unreliable. Strip the decoded BOM character instead.
  72. if (
  73. self._has_sig_or_bom
  74. and self._encoding == "utf_7"
  75. and self._string
  76. and self._string[0] == "\ufeff"
  77. ):
  78. self._string = self._string[1:]
  79. return self._string
  80. def __repr__(self) -> str:
  81. return f"<CharsetMatch '{self.encoding}' fp({self.fingerprint})>"
  82. def add_submatch(self, other: CharsetMatch) -> None:
  83. if not isinstance(other, CharsetMatch) or other == self:
  84. raise ValueError(
  85. "Unable to add instance <{}> as a submatch of a CharsetMatch".format(
  86. other.__class__
  87. )
  88. )
  89. other._string = None # Unload RAM usage; dirty trick.
  90. self._leaves.append(other)
  91. @property
  92. def encoding(self) -> str:
  93. return self._encoding
  94. @property
  95. def encoding_aliases(self) -> list[str]:
  96. """
  97. Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855.
  98. """
  99. also_known_as: list[str] = []
  100. for u, p in aliases.items():
  101. if self.encoding == u:
  102. also_known_as.append(p)
  103. elif self.encoding == p:
  104. also_known_as.append(u)
  105. return also_known_as
  106. @property
  107. def bom(self) -> bool:
  108. return self._has_sig_or_bom
  109. @property
  110. def byte_order_mark(self) -> bool:
  111. return self._has_sig_or_bom
  112. @property
  113. def languages(self) -> list[str]:
  114. """
  115. Return the complete list of possible languages found in decoded sequence.
  116. Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'.
  117. """
  118. return [e[0] for e in self._languages]
  119. @property
  120. def language(self) -> str:
  121. """
  122. Most probable language found in decoded sequence. If none were detected or inferred, the property will return
  123. "Unknown".
  124. """
  125. if not self._languages:
  126. # Trying to infer the language based on the given encoding
  127. # Its either English or we should not pronounce ourselves in certain cases.
  128. if "ascii" in self.could_be_from_charset:
  129. return "English"
  130. # doing it there to avoid circular import
  131. from charset_normalizer.cd import encoding_languages, mb_encoding_languages
  132. languages = (
  133. mb_encoding_languages(self.encoding)
  134. if is_multi_byte_encoding(self.encoding)
  135. else encoding_languages(self.encoding)
  136. )
  137. if len(languages) == 0 or "Latin Based" in languages:
  138. return "Unknown"
  139. return languages[0]
  140. return self._languages[0][0]
  141. @property
  142. def chaos(self) -> float:
  143. return self._mean_mess_ratio
  144. @property
  145. def coherence(self) -> float:
  146. if not self._languages:
  147. return 0.0
  148. return self._languages[0][1]
  149. @property
  150. def percent_chaos(self) -> float:
  151. return round(self.chaos * 100, ndigits=3)
  152. @property
  153. def percent_coherence(self) -> float:
  154. return round(self.coherence * 100, ndigits=3)
  155. @property
  156. def raw(self) -> bytes | bytearray:
  157. """
  158. Original untouched bytes.
  159. """
  160. return self._payload
  161. @property
  162. def submatch(self) -> list[CharsetMatch]:
  163. return self._leaves
  164. @property
  165. def has_submatch(self) -> bool:
  166. return len(self._leaves) > 0
  167. @property
  168. def alphabets(self) -> list[str]:
  169. if self._unicode_ranges is not None:
  170. return self._unicode_ranges
  171. # list detected ranges
  172. detected_ranges: list[str | None] = [unicode_range(char) for char in str(self)]
  173. # filter and sort
  174. self._unicode_ranges = sorted(list({r for r in detected_ranges if r}))
  175. return self._unicode_ranges
  176. @property
  177. def could_be_from_charset(self) -> list[str]:
  178. """
  179. The complete list of encoding that output the exact SAME str result and therefore could be the originating
  180. encoding.
  181. This list does include the encoding available in property 'encoding'.
  182. """
  183. return [self._encoding] + [m.encoding for m in self._leaves]
  184. def output(self, encoding: str = "utf_8") -> bytes:
  185. """
  186. Method to get re-encoded bytes payload using given target encoding. Default to UTF-8.
  187. Any errors will be simply ignored by the encoder NOT replaced.
  188. """
  189. if self._output_encoding is None or self._output_encoding != encoding:
  190. self._output_encoding = encoding
  191. decoded_string = str(self)
  192. if (
  193. self._preemptive_declaration is not None
  194. and self._preemptive_declaration.lower()
  195. not in ["utf-8", "utf8", "utf_8"]
  196. ):
  197. patched_header = sub(
  198. RE_POSSIBLE_ENCODING_INDICATION,
  199. lambda m: m.string[m.span()[0] : m.span()[1]].replace(
  200. m.groups()[0],
  201. iana_name(self._output_encoding).replace("_", "-"), # type: ignore[arg-type]
  202. ),
  203. decoded_string[:8192],
  204. count=1,
  205. )
  206. decoded_string = patched_header + decoded_string[8192:]
  207. self._output_payload = decoded_string.encode(encoding, "replace")
  208. return self._output_payload # type: ignore
  209. @property
  210. def fingerprint(self) -> int:
  211. """
  212. Retrieve a hash fingerprint of the decoded payload, used for deduplication.
  213. """
  214. return hash(str(self))
  215. class CharsetMatches:
  216. """
  217. Container with every CharsetMatch items ordered by default from most probable to the less one.
  218. Act like a list(iterable) but does not implements all related methods.
  219. """
  220. def __init__(self, results: list[CharsetMatch] | None = None):
  221. self._results: list[CharsetMatch] = sorted(results) if results else []
  222. self._is_sorted: bool = True
  223. def _ensure_sorted(self) -> None:
  224. if not self._is_sorted:
  225. self._results.sort()
  226. self._is_sorted = True
  227. def __iter__(self) -> Iterator[CharsetMatch]:
  228. self._ensure_sorted()
  229. yield from self._results
  230. def __getitem__(self, item: int | str) -> CharsetMatch:
  231. """
  232. Retrieve a single item either by its position or encoding name (alias may be used here).
  233. Raise KeyError upon invalid index or encoding not present in results.
  234. """
  235. if isinstance(item, int):
  236. self._ensure_sorted()
  237. return self._results[item]
  238. if isinstance(item, str):
  239. item = iana_name(item, False)
  240. for result in self._results:
  241. if item in result.could_be_from_charset:
  242. return result
  243. raise KeyError
  244. def __len__(self) -> int:
  245. return len(self._results)
  246. def __bool__(self) -> bool:
  247. return len(self._results) > 0
  248. def append(self, item: CharsetMatch) -> None:
  249. """
  250. Insert a single match. Will be inserted accordingly to preserve sort.
  251. Can be inserted as a submatch.
  252. """
  253. if not isinstance(item, CharsetMatch):
  254. raise ValueError(
  255. "Cannot append instance '{}' to CharsetMatches".format(
  256. str(item.__class__)
  257. )
  258. )
  259. # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage)
  260. if len(item.raw) < TOO_BIG_SEQUENCE:
  261. for match in self._results:
  262. if match.fingerprint == item.fingerprint and match.chaos == item.chaos:
  263. match.add_submatch(item)
  264. return
  265. self._results.append(item)
  266. self._is_sorted = False
  267. def best(self) -> CharsetMatch | None:
  268. """
  269. Simply return the first match. Strict equivalent to matches[0].
  270. """
  271. if not self._results:
  272. return None
  273. self._ensure_sorted()
  274. return self._results[0]
  275. def first(self) -> CharsetMatch | None:
  276. """
  277. Redundant method, call the method best(). Kept for BC reasons.
  278. """
  279. return self.best()
  280. CoherenceMatch = Tuple[str, float]
  281. CoherenceMatches = List[CoherenceMatch]
  282. class CliDetectionResult:
  283. def __init__(
  284. self,
  285. path: str,
  286. encoding: str | None,
  287. encoding_aliases: list[str],
  288. alternative_encodings: list[str],
  289. language: str,
  290. alphabets: list[str],
  291. has_sig_or_bom: bool,
  292. chaos: float,
  293. coherence: float,
  294. unicode_path: str | None,
  295. is_preferred: bool,
  296. ):
  297. self.path: str = path
  298. self.unicode_path: str | None = unicode_path
  299. self.encoding: str | None = encoding
  300. self.encoding_aliases: list[str] = encoding_aliases
  301. self.alternative_encodings: list[str] = alternative_encodings
  302. self.language: str = language
  303. self.alphabets: list[str] = alphabets
  304. self.has_sig_or_bom: bool = has_sig_or_bom
  305. self.chaos: float = chaos
  306. self.coherence: float = coherence
  307. self.is_preferred: bool = is_preferred
  308. @property
  309. def __dict__(self) -> dict[str, Any]: # type: ignore
  310. return {
  311. "path": self.path,
  312. "encoding": self.encoding,
  313. "encoding_aliases": self.encoding_aliases,
  314. "alternative_encodings": self.alternative_encodings,
  315. "language": self.language,
  316. "alphabets": self.alphabets,
  317. "has_sig_or_bom": self.has_sig_or_bom,
  318. "chaos": self.chaos,
  319. "coherence": self.coherence,
  320. "unicode_path": self.unicode_path,
  321. "is_preferred": self.is_preferred,
  322. }
  323. def to_json(self) -> str:
  324. from json import dumps
  325. return dumps(self.__dict__, ensure_ascii=True, indent=4)