api.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. import logging
  2. from os.path import basename, splitext
  3. from typing import BinaryIO, List, Optional, Set
  4. try:
  5. from os import PathLike
  6. except ImportError: # pragma: no cover
  7. PathLike = str # type: ignore
  8. from .cd import (
  9. coherence_ratio,
  10. encoding_languages,
  11. mb_encoding_languages,
  12. merge_coherence_ratios,
  13. )
  14. from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE
  15. from .md import mess_ratio
  16. from .models import CharsetMatch, CharsetMatches
  17. from .utils import (
  18. any_specified_encoding,
  19. iana_name,
  20. identify_sig_or_bom,
  21. is_cp_similar,
  22. is_multi_byte_encoding,
  23. should_strip_sig_or_bom,
  24. )
  25. logger = logging.getLogger("charset_normalizer")
  26. explain_handler = logging.StreamHandler()
  27. explain_handler.setFormatter(
  28. logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
  29. )
  30. def from_bytes(
  31. sequences: bytes,
  32. steps: int = 5,
  33. chunk_size: int = 512,
  34. threshold: float = 0.2,
  35. cp_isolation: List[str] = None,
  36. cp_exclusion: List[str] = None,
  37. preemptive_behaviour: bool = True,
  38. explain: bool = False,
  39. ) -> CharsetMatches:
  40. """
  41. Given a raw bytes sequence, return the best possibles charset usable to render str objects.
  42. If there is no results, it is a strong indicator that the source is binary/not text.
  43. By default, the process will extract 5 blocs of 512o each to assess the mess and coherence of a given sequence.
  44. And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.
  45. The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page
  46. but never take it for granted. Can improve the performance.
  47. You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that
  48. purpose.
  49. This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32.
  50. By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain'
  51. toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging.
  52. Custom logging format and handler can be set manually.
  53. """
  54. if not isinstance(sequences, (bytearray, bytes)):
  55. raise TypeError(
  56. "Expected object of type bytes or bytearray, got: {0}".format(
  57. type(sequences)
  58. )
  59. )
  60. if explain:
  61. previous_logger_level = logger.level # type: int
  62. logger.addHandler(explain_handler)
  63. logger.setLevel(logging.DEBUG)
  64. length = len(sequences) # type: int
  65. if length == 0:
  66. logger.warning("Encoding detection on empty bytes, assuming utf_8 intention.")
  67. if explain:
  68. logger.removeHandler(explain_handler)
  69. logger.setLevel(previous_logger_level or logging.WARNING)
  70. return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])
  71. if cp_isolation is not None:
  72. logger.debug(
  73. "cp_isolation is set. use this flag for debugging purpose. "
  74. "limited list of encoding allowed : %s.",
  75. ", ".join(cp_isolation),
  76. )
  77. cp_isolation = [iana_name(cp, False) for cp in cp_isolation]
  78. else:
  79. cp_isolation = []
  80. if cp_exclusion is not None:
  81. logger.debug(
  82. "cp_exclusion is set. use this flag for debugging purpose. "
  83. "limited list of encoding excluded : %s.",
  84. ", ".join(cp_exclusion),
  85. )
  86. cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion]
  87. else:
  88. cp_exclusion = []
  89. if length <= (chunk_size * steps):
  90. logger.debug(
  91. "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.",
  92. steps,
  93. chunk_size,
  94. length,
  95. )
  96. steps = 1
  97. chunk_size = length
  98. if steps > 1 and length / steps < chunk_size:
  99. chunk_size = int(length / steps)
  100. is_too_small_sequence = len(sequences) < TOO_SMALL_SEQUENCE # type: bool
  101. is_too_large_sequence = len(sequences) >= TOO_BIG_SEQUENCE # type: bool
  102. if is_too_small_sequence:
  103. logger.warning(
  104. "Trying to detect encoding from a tiny portion of ({}) byte(s).".format(
  105. length
  106. )
  107. )
  108. elif is_too_large_sequence:
  109. logger.info(
  110. "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format(
  111. length
  112. )
  113. )
  114. prioritized_encodings = [] # type: List[str]
  115. specified_encoding = (
  116. any_specified_encoding(sequences) if preemptive_behaviour else None
  117. ) # type: Optional[str]
  118. if specified_encoding is not None:
  119. prioritized_encodings.append(specified_encoding)
  120. logger.info(
  121. "Detected declarative mark in sequence. Priority +1 given for %s.",
  122. specified_encoding,
  123. )
  124. tested = set() # type: Set[str]
  125. tested_but_hard_failure = [] # type: List[str]
  126. tested_but_soft_failure = [] # type: List[str]
  127. fallback_ascii = None # type: Optional[CharsetMatch]
  128. fallback_u8 = None # type: Optional[CharsetMatch]
  129. fallback_specified = None # type: Optional[CharsetMatch]
  130. results = CharsetMatches() # type: CharsetMatches
  131. sig_encoding, sig_payload = identify_sig_or_bom(sequences)
  132. if sig_encoding is not None:
  133. prioritized_encodings.append(sig_encoding)
  134. logger.info(
  135. "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.",
  136. len(sig_payload),
  137. sig_encoding,
  138. )
  139. prioritized_encodings.append("ascii")
  140. if "utf_8" not in prioritized_encodings:
  141. prioritized_encodings.append("utf_8")
  142. for encoding_iana in prioritized_encodings + IANA_SUPPORTED:
  143. if cp_isolation and encoding_iana not in cp_isolation:
  144. continue
  145. if cp_exclusion and encoding_iana in cp_exclusion:
  146. continue
  147. if encoding_iana in tested:
  148. continue
  149. tested.add(encoding_iana)
  150. decoded_payload = None # type: Optional[str]
  151. bom_or_sig_available = sig_encoding == encoding_iana # type: bool
  152. strip_sig_or_bom = bom_or_sig_available and should_strip_sig_or_bom(
  153. encoding_iana
  154. ) # type: bool
  155. if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available:
  156. logger.debug(
  157. "Encoding %s wont be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.",
  158. encoding_iana,
  159. )
  160. continue
  161. try:
  162. is_multi_byte_decoder = is_multi_byte_encoding(encoding_iana) # type: bool
  163. except (ModuleNotFoundError, ImportError):
  164. logger.debug(
  165. "Encoding %s does not provide an IncrementalDecoder", encoding_iana
  166. )
  167. continue
  168. try:
  169. if is_too_large_sequence and is_multi_byte_decoder is False:
  170. str(
  171. sequences[: int(50e4)]
  172. if strip_sig_or_bom is False
  173. else sequences[len(sig_payload) : int(50e4)],
  174. encoding=encoding_iana,
  175. )
  176. else:
  177. decoded_payload = str(
  178. sequences
  179. if strip_sig_or_bom is False
  180. else sequences[len(sig_payload) :],
  181. encoding=encoding_iana,
  182. )
  183. except (UnicodeDecodeError, LookupError) as e:
  184. if not isinstance(e, LookupError):
  185. logger.debug(
  186. "Code page %s does not fit given bytes sequence at ALL. %s",
  187. encoding_iana,
  188. str(e),
  189. )
  190. tested_but_hard_failure.append(encoding_iana)
  191. continue
  192. similar_soft_failure_test = False # type: bool
  193. for encoding_soft_failed in tested_but_soft_failure:
  194. if is_cp_similar(encoding_iana, encoding_soft_failed):
  195. similar_soft_failure_test = True
  196. break
  197. if similar_soft_failure_test:
  198. logger.debug(
  199. "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!",
  200. encoding_iana,
  201. encoding_soft_failed,
  202. )
  203. continue
  204. r_ = range(
  205. 0 if not bom_or_sig_available else len(sig_payload),
  206. length,
  207. int(length / steps),
  208. )
  209. multi_byte_bonus = (
  210. is_multi_byte_decoder
  211. and decoded_payload is not None
  212. and len(decoded_payload) < length
  213. ) # type: bool
  214. if multi_byte_bonus:
  215. logger.debug(
  216. "Code page %s is a multi byte encoding table and it appear that at least one character "
  217. "was encoded using n-bytes.",
  218. encoding_iana,
  219. )
  220. max_chunk_gave_up = int(len(r_) / 4) # type: int
  221. max_chunk_gave_up = max(max_chunk_gave_up, 2)
  222. early_stop_count = 0 # type: int
  223. lazy_str_hard_failure = False
  224. md_chunks = [] # type: List[str]
  225. md_ratios = []
  226. for i in r_:
  227. if i + chunk_size > length + 8:
  228. continue
  229. cut_sequence = sequences[i : i + chunk_size]
  230. if bom_or_sig_available and strip_sig_or_bom is False:
  231. cut_sequence = sig_payload + cut_sequence
  232. try:
  233. chunk = cut_sequence.decode(
  234. encoding_iana,
  235. errors="ignore" if is_multi_byte_decoder else "strict",
  236. ) # type: str
  237. except UnicodeDecodeError as e: # Lazy str loading may have missed something there
  238. logger.debug(
  239. "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s",
  240. encoding_iana,
  241. str(e),
  242. )
  243. early_stop_count = max_chunk_gave_up
  244. lazy_str_hard_failure = True
  245. break
  246. # multi-byte bad cutting detector and adjustment
  247. # not the cleanest way to perform that fix but clever enough for now.
  248. if is_multi_byte_decoder and i > 0 and sequences[i] >= 0x80:
  249. chunk_partial_size_chk = min(chunk_size, 16) # type: int
  250. if (
  251. decoded_payload
  252. and chunk[:chunk_partial_size_chk] not in decoded_payload
  253. ):
  254. for j in range(i, i - 4, -1):
  255. cut_sequence = sequences[j : i + chunk_size]
  256. if bom_or_sig_available and strip_sig_or_bom is False:
  257. cut_sequence = sig_payload + cut_sequence
  258. chunk = cut_sequence.decode(encoding_iana, errors="ignore")
  259. if chunk[:chunk_partial_size_chk] in decoded_payload:
  260. break
  261. md_chunks.append(chunk)
  262. md_ratios.append(mess_ratio(chunk, threshold))
  263. if md_ratios[-1] >= threshold:
  264. early_stop_count += 1
  265. if (early_stop_count >= max_chunk_gave_up) or (
  266. bom_or_sig_available and strip_sig_or_bom is False
  267. ):
  268. break
  269. # We might want to check the sequence again with the whole content
  270. # Only if initial MD tests passes
  271. if (
  272. not lazy_str_hard_failure
  273. and is_too_large_sequence
  274. and not is_multi_byte_decoder
  275. ):
  276. try:
  277. sequences[int(50e3) :].decode(encoding_iana, errors="strict")
  278. except UnicodeDecodeError as e:
  279. logger.debug(
  280. "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s",
  281. encoding_iana,
  282. str(e),
  283. )
  284. tested_but_hard_failure.append(encoding_iana)
  285. continue
  286. mean_mess_ratio = (
  287. sum(md_ratios) / len(md_ratios) if md_ratios else 0.0
  288. ) # type: float
  289. if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up:
  290. tested_but_soft_failure.append(encoding_iana)
  291. logger.info(
  292. "%s was excluded because of initial chaos probing. Gave up %i time(s). "
  293. "Computed mean chaos is %f %%.",
  294. encoding_iana,
  295. early_stop_count,
  296. round(mean_mess_ratio * 100, ndigits=3),
  297. )
  298. # Preparing those fallbacks in case we got nothing.
  299. if (
  300. encoding_iana in ["ascii", "utf_8", specified_encoding]
  301. and not lazy_str_hard_failure
  302. ):
  303. fallback_entry = CharsetMatch(
  304. sequences, encoding_iana, threshold, False, [], decoded_payload
  305. )
  306. if encoding_iana == specified_encoding:
  307. fallback_specified = fallback_entry
  308. elif encoding_iana == "ascii":
  309. fallback_ascii = fallback_entry
  310. else:
  311. fallback_u8 = fallback_entry
  312. continue
  313. logger.info(
  314. "%s passed initial chaos probing. Mean measured chaos is %f %%",
  315. encoding_iana,
  316. round(mean_mess_ratio * 100, ndigits=3),
  317. )
  318. if not is_multi_byte_decoder:
  319. target_languages = encoding_languages(encoding_iana) # type: List[str]
  320. else:
  321. target_languages = mb_encoding_languages(encoding_iana)
  322. if target_languages:
  323. logger.debug(
  324. "{} should target any language(s) of {}".format(
  325. encoding_iana, str(target_languages)
  326. )
  327. )
  328. cd_ratios = []
  329. # We shall skip the CD when its about ASCII
  330. # Most of the time its not relevant to run "language-detection" on it.
  331. if encoding_iana != "ascii":
  332. for chunk in md_chunks:
  333. chunk_languages = coherence_ratio(
  334. chunk, 0.1, ",".join(target_languages) if target_languages else None
  335. )
  336. cd_ratios.append(chunk_languages)
  337. cd_ratios_merged = merge_coherence_ratios(cd_ratios)
  338. if cd_ratios_merged:
  339. logger.info(
  340. "We detected language {} using {}".format(
  341. cd_ratios_merged, encoding_iana
  342. )
  343. )
  344. results.append(
  345. CharsetMatch(
  346. sequences,
  347. encoding_iana,
  348. mean_mess_ratio,
  349. bom_or_sig_available,
  350. cd_ratios_merged,
  351. decoded_payload,
  352. )
  353. )
  354. if (
  355. encoding_iana in [specified_encoding, "ascii", "utf_8"]
  356. and mean_mess_ratio < 0.1
  357. ):
  358. logger.info(
  359. "%s is most likely the one. Stopping the process.", encoding_iana
  360. )
  361. if explain:
  362. logger.removeHandler(explain_handler)
  363. logger.setLevel(previous_logger_level)
  364. return CharsetMatches([results[encoding_iana]])
  365. if encoding_iana == sig_encoding:
  366. logger.info(
  367. "%s is most likely the one as we detected a BOM or SIG within the beginning of the sequence.",
  368. encoding_iana,
  369. )
  370. if explain:
  371. logger.removeHandler(explain_handler)
  372. logger.setLevel(previous_logger_level)
  373. return CharsetMatches([results[encoding_iana]])
  374. if len(results) == 0:
  375. if fallback_u8 or fallback_ascii or fallback_specified:
  376. logger.debug(
  377. "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback."
  378. )
  379. if fallback_specified:
  380. logger.debug(
  381. "%s will be used as a fallback match", fallback_specified.encoding
  382. )
  383. results.append(fallback_specified)
  384. elif (
  385. (fallback_u8 and fallback_ascii is None)
  386. or (
  387. fallback_u8
  388. and fallback_ascii
  389. and fallback_u8.fingerprint != fallback_ascii.fingerprint
  390. )
  391. or (fallback_u8 is not None)
  392. ):
  393. logger.warning("utf_8 will be used as a fallback match")
  394. results.append(fallback_u8)
  395. elif fallback_ascii:
  396. logger.warning("ascii will be used as a fallback match")
  397. results.append(fallback_ascii)
  398. if explain:
  399. logger.removeHandler(explain_handler)
  400. logger.setLevel(previous_logger_level)
  401. return results
  402. def from_fp(
  403. fp: BinaryIO,
  404. steps: int = 5,
  405. chunk_size: int = 512,
  406. threshold: float = 0.20,
  407. cp_isolation: List[str] = None,
  408. cp_exclusion: List[str] = None,
  409. preemptive_behaviour: bool = True,
  410. explain: bool = False,
  411. ) -> CharsetMatches:
  412. """
  413. Same thing than the function from_bytes but using a file pointer that is already ready.
  414. Will not close the file pointer.
  415. """
  416. return from_bytes(
  417. fp.read(),
  418. steps,
  419. chunk_size,
  420. threshold,
  421. cp_isolation,
  422. cp_exclusion,
  423. preemptive_behaviour,
  424. explain,
  425. )
  426. def from_path(
  427. path: PathLike,
  428. steps: int = 5,
  429. chunk_size: int = 512,
  430. threshold: float = 0.20,
  431. cp_isolation: List[str] = None,
  432. cp_exclusion: List[str] = None,
  433. preemptive_behaviour: bool = True,
  434. explain: bool = False,
  435. ) -> CharsetMatches:
  436. """
  437. Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode.
  438. Can raise IOError.
  439. """
  440. with open(path, "rb") as fp:
  441. return from_fp(
  442. fp,
  443. steps,
  444. chunk_size,
  445. threshold,
  446. cp_isolation,
  447. cp_exclusion,
  448. preemptive_behaviour,
  449. explain,
  450. )
  451. def normalize(
  452. path: PathLike,
  453. steps: int = 5,
  454. chunk_size: int = 512,
  455. threshold: float = 0.20,
  456. cp_isolation: List[str] = None,
  457. cp_exclusion: List[str] = None,
  458. preemptive_behaviour: bool = True,
  459. ) -> CharsetMatch:
  460. """
  461. Take a (text-based) file path and try to create another file next to it, this time using UTF-8.
  462. """
  463. results = from_path(
  464. path,
  465. steps,
  466. chunk_size,
  467. threshold,
  468. cp_isolation,
  469. cp_exclusion,
  470. preemptive_behaviour,
  471. )
  472. filename = basename(path)
  473. target_extensions = list(splitext(filename))
  474. if len(results) == 0:
  475. raise IOError(
  476. 'Unable to normalize "{}", no encoding charset seems to fit.'.format(
  477. filename
  478. )
  479. )
  480. result = results.best()
  481. target_extensions[0] += "-" + result.encoding # type: ignore
  482. with open(
  483. "{}".format(str(path).replace(filename, "".join(target_extensions))), "wb"
  484. ) as fp:
  485. fp.write(result.output()) # type: ignore
  486. return result # type: ignore