models.py 13 KB

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