api.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. from __future__ import annotations
  2. import logging
  3. from functools import lru_cache
  4. from os import PathLike
  5. from typing import BinaryIO
  6. from .cd import (
  7. coherence_ratio,
  8. encoding_languages,
  9. mb_encoding_languages,
  10. merge_coherence_ratios,
  11. )
  12. from .constant import (
  13. IANA_SUPPORTED,
  14. IANA_SUPPORTED_SIMILAR,
  15. TOO_BIG_SEQUENCE,
  16. TOO_SMALL_SEQUENCE,
  17. TRACE,
  18. )
  19. from .md import mess_ratio
  20. from .models import CharsetMatch, CharsetMatches
  21. from .utils import (
  22. any_specified_encoding,
  23. cut_sequence_chunks,
  24. iana_name,
  25. identify_sig_or_bom,
  26. is_multi_byte_encoding,
  27. should_strip_sig_or_bom,
  28. )
  29. logger = logging.getLogger("charset_normalizer")
  30. explain_handler = logging.StreamHandler()
  31. explain_handler.setFormatter(
  32. logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
  33. )
  34. # Pre-compute a reordered encoding list: multibyte first, then single-byte.
  35. # This allows the mb_definitive_match optimization to fire earlier, skipping
  36. # all single-byte encodings for genuine CJK content. Multibyte codecs
  37. # hard-fail (UnicodeDecodeError) on single-byte data almost instantly, so
  38. # testing them first costs negligible time for non-CJK files.
  39. # Stable sort on a boolean key: multibyte (False) first, IANA order kept
  40. # within each group.
  41. IANA_SUPPORTED_MB_FIRST: list[str] = sorted(
  42. IANA_SUPPORTED, key=lambda encoding: not is_multi_byte_encoding(encoding)
  43. )
  44. def from_bytes(
  45. sequences: bytes | bytearray,
  46. steps: int = 5,
  47. chunk_size: int = 512,
  48. threshold: float = 0.2,
  49. cp_isolation: list[str] | None = None,
  50. cp_exclusion: list[str] | None = None,
  51. preemptive_behaviour: bool = True,
  52. explain: bool = False,
  53. language_threshold: float = 0.1,
  54. enable_fallback: bool = True,
  55. ) -> CharsetMatches:
  56. """
  57. Given a raw bytes sequence, return the best possibles charset usable to render str objects.
  58. If there is no results, it is a strong indicator that the source is binary/not text.
  59. By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence.
  60. And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.
  61. The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page
  62. but never take it for granted. Can improve the performance.
  63. You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that
  64. purpose.
  65. This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32.
  66. By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain'
  67. toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging.
  68. Custom logging format and handler can be set manually.
  69. """
  70. if not isinstance(sequences, (bytearray, bytes)):
  71. raise TypeError(
  72. "Expected object of type bytes or bytearray, got: {}".format(
  73. type(sequences)
  74. )
  75. )
  76. if explain:
  77. previous_logger_level: int = logger.level
  78. logger.addHandler(explain_handler)
  79. logger.setLevel(TRACE)
  80. length: int = len(sequences)
  81. if length == 0:
  82. logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.")
  83. if explain: # Defensive: ensure exit path clean handler
  84. logger.removeHandler(explain_handler)
  85. logger.setLevel(previous_logger_level)
  86. return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])
  87. if cp_isolation is not None:
  88. logger.log(
  89. TRACE,
  90. "cp_isolation is set. use this flag for debugging purpose. "
  91. "limited list of encoding allowed : %s.",
  92. ", ".join(cp_isolation),
  93. )
  94. cp_isolation = [iana_name(cp, False) for cp in cp_isolation]
  95. else:
  96. cp_isolation = []
  97. if cp_exclusion is not None:
  98. logger.log(
  99. TRACE,
  100. "cp_exclusion is set. use this flag for debugging purpose. "
  101. "limited list of encoding excluded : %s.",
  102. ", ".join(cp_exclusion),
  103. )
  104. cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion]
  105. else:
  106. cp_exclusion = []
  107. if length <= (chunk_size * steps):
  108. logger.log(
  109. TRACE,
  110. "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.",
  111. steps,
  112. chunk_size,
  113. length,
  114. )
  115. steps = 1
  116. chunk_size = length
  117. if steps > 1 and length / steps < chunk_size:
  118. chunk_size = int(length / steps)
  119. is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE
  120. is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE
  121. if is_too_small_sequence:
  122. logger.log(
  123. TRACE,
  124. "Trying to detect encoding from a tiny portion of ({}) byte(s).".format(
  125. length
  126. ),
  127. )
  128. elif is_too_large_sequence:
  129. logger.log(
  130. TRACE,
  131. "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format(
  132. length
  133. ),
  134. )
  135. prioritized_encodings: list[str] = []
  136. specified_encoding: str | None = (
  137. any_specified_encoding(sequences) if preemptive_behaviour else None
  138. )
  139. if specified_encoding is not None:
  140. prioritized_encodings.append(specified_encoding)
  141. logger.log(
  142. TRACE,
  143. "Detected declarative mark in sequence. Priority +1 given for %s.",
  144. specified_encoding,
  145. )
  146. tested: set[str] = set()
  147. tested_but_hard_failure: list[str] = []
  148. tested_but_soft_failure: list[str] = []
  149. soft_failure_skip: set[str] = set()
  150. success_fast_tracked: set[str] = set()
  151. # Cache for decoded payload deduplication: hash(decoded_payload) -> (mean_mess_ratio, cd_ratios_merged, passed)
  152. # When multiple encodings decode to the exact same string, we can skip the expensive
  153. # mess_ratio and coherence_ratio analysis and reuse the results from the first encoding.
  154. payload_result_cache: dict[int, tuple[float, list[tuple[str, float]], bool]] = {}
  155. # Avoid unoptimized RSS usage.
  156. # this cache is mostly interesting for
  157. # local usage. Garbage collected at the
  158. # end. Like it should.
  159. cached_mess_ratio = lru_cache(maxsize=None)(mess_ratio)
  160. cached_coherence_ratio = lru_cache(maxsize=None)(coherence_ratio)
  161. # When a definitive result (chaos=0.0 and good coherence) is found after testing
  162. # the prioritized encodings (ascii, utf_8), we can significantly reduce the remaining
  163. # work. Encodings that target completely different language families (e.g., Cyrillic
  164. # when the definitive match is Latin) are skipped entirely.
  165. # Additionally, for same-family encodings that pass chaos probing, we reuse the
  166. # definitive match's coherence ratios instead of recomputing them — a major savings
  167. # since coherence_ratio accounts for ~30% of total time on slow Latin files.
  168. definitive_match_found: bool = False
  169. definitive_target_languages: set[str] = set()
  170. # After the definitive match fires, we cap the number of additional same-family
  171. # single-byte encodings that pass chaos probing. Once we've accumulated enough
  172. # good candidates (N), further same-family SB encodings are unlikely to produce
  173. # a better best() result and just waste mess_ratio + coherence_ratio time.
  174. # The first encoding to trigger the definitive match is NOT counted (it's already in).
  175. post_definitive_sb_success_count: int = 0
  176. POST_DEFINITIVE_SB_CAP: int = 7
  177. # When a non-UTF multibyte encoding passes chaos probing with significant multibyte
  178. # content (decoded length < 98% of raw length), skip all remaining single-byte encodings.
  179. # Rationale: multi-byte decoders (CJK) have strict byte-sequence validation — if they
  180. # decode without error AND pass chaos probing with substantial multibyte content, the
  181. # data is genuinely multibyte encoded. Single-byte encodings will always decode (every
  182. # byte maps to something) but waste time on mess_ratio before failing.
  183. # The 98% threshold prevents false triggers on files that happen to have a few valid
  184. # multibyte pairs (e.g., cp424/_ude_1.txt where big5 decodes with 99% ratio).
  185. mb_definitive_match_found: bool = False
  186. fallback_ascii: CharsetMatch | None = None
  187. fallback_u8: CharsetMatch | None = None
  188. fallback_specified: CharsetMatch | None = None
  189. results: CharsetMatches = CharsetMatches()
  190. early_stop_results: CharsetMatches = CharsetMatches()
  191. sig_encoding, sig_payload = identify_sig_or_bom(sequences)
  192. if sig_encoding is not None:
  193. prioritized_encodings.append(sig_encoding)
  194. logger.log(
  195. TRACE,
  196. "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.",
  197. len(sig_payload),
  198. sig_encoding,
  199. )
  200. prioritized_encodings.append("ascii")
  201. if "utf_8" not in prioritized_encodings:
  202. prioritized_encodings.append("utf_8")
  203. for encoding_iana in prioritized_encodings + IANA_SUPPORTED_MB_FIRST:
  204. if cp_isolation and encoding_iana not in cp_isolation:
  205. continue
  206. if cp_exclusion and encoding_iana in cp_exclusion:
  207. continue
  208. if encoding_iana in tested:
  209. continue
  210. tested.add(encoding_iana)
  211. decoded_payload: str | None = None
  212. bom_or_sig_available: bool = sig_encoding == encoding_iana
  213. strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom(
  214. encoding_iana
  215. )
  216. if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available:
  217. logger.log(
  218. TRACE,
  219. "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.",
  220. encoding_iana,
  221. )
  222. continue
  223. if encoding_iana in {"utf_7"} and not bom_or_sig_available:
  224. logger.log(
  225. TRACE,
  226. "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.",
  227. encoding_iana,
  228. )
  229. continue
  230. # Skip encodings similar to ones that already soft-failed (high mess ratio).
  231. # Checked BEFORE the expensive decode attempt.
  232. if encoding_iana in soft_failure_skip:
  233. logger.log(
  234. TRACE,
  235. "%s is deemed too similar to a code page that was already considered unsuited. Continuing!",
  236. encoding_iana,
  237. )
  238. continue
  239. # Skip encodings that were already fast-tracked from a similar successful encoding.
  240. if encoding_iana in success_fast_tracked:
  241. logger.log(
  242. TRACE,
  243. "Skipping %s: already fast-tracked from a similar successful encoding.",
  244. encoding_iana,
  245. )
  246. continue
  247. try:
  248. is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana)
  249. except (ModuleNotFoundError, ImportError): # Defensive:
  250. logger.log(
  251. TRACE,
  252. "Encoding %s does not provide an IncrementalDecoder",
  253. encoding_iana,
  254. )
  255. continue
  256. # When we've already found a definitive match (chaos=0.0 with good coherence)
  257. # after testing the prioritized encodings, skip encodings that target
  258. # completely different language families. This avoids running expensive
  259. # mess_ratio + coherence_ratio on clearly unrelated candidates (e.g., Cyrillic
  260. # when the definitive match is Latin-based).
  261. if definitive_match_found:
  262. if not is_multi_byte_decoder:
  263. enc_languages = set(encoding_languages(encoding_iana))
  264. else:
  265. enc_languages = set(mb_encoding_languages(encoding_iana))
  266. if not enc_languages.intersection(definitive_target_languages):
  267. logger.log(
  268. TRACE,
  269. "Skipping %s: definitive match already found, this encoding targets different languages (%s vs %s).",
  270. encoding_iana,
  271. enc_languages,
  272. definitive_target_languages,
  273. )
  274. continue
  275. # After the definitive match, cap the number of additional same-family
  276. # single-byte encodings that pass chaos probing. This avoids testing the
  277. # tail of rare, low-value same-family encodings (mac_iceland, cp860, etc.)
  278. # that almost never change best() but each cost ~1-2ms of mess_ratio + coherence.
  279. if (
  280. definitive_match_found
  281. and not is_multi_byte_decoder
  282. and post_definitive_sb_success_count >= POST_DEFINITIVE_SB_CAP
  283. ):
  284. logger.log(
  285. TRACE,
  286. "Skipping %s: already accumulated %d same-family results after definitive match (cap=%d).",
  287. encoding_iana,
  288. post_definitive_sb_success_count,
  289. POST_DEFINITIVE_SB_CAP,
  290. )
  291. continue
  292. # When a multibyte encoding with significant multibyte content has already
  293. # passed chaos probing, skip all single-byte encodings. They will either fail
  294. # chaos probing (wasting mess_ratio time) or produce inferior results.
  295. if mb_definitive_match_found and not is_multi_byte_decoder:
  296. logger.log(
  297. TRACE,
  298. "Skipping single-byte %s: multi-byte definitive match already found.",
  299. encoding_iana,
  300. )
  301. continue
  302. # Single-byte candidates of regular size defer the expensive whole
  303. # payload decode until after chunk probing: single-byte codecs are
  304. # stateless (1 byte == 1 char) so decoding chunk slices is provably
  305. # identical to slicing the decoded payload, and candidates rejected
  306. # by chaos probing (the common case) never pay the full decode nor
  307. # the payload hash.
  308. deferred_decoding: bool = (
  309. not is_multi_byte_decoder and not is_too_large_sequence
  310. )
  311. try:
  312. if is_too_large_sequence and not is_multi_byte_decoder:
  313. str(
  314. (
  315. sequences[: int(50e4)]
  316. if not strip_sig_or_bom
  317. else sequences[len(sig_payload) : int(50e4)]
  318. ),
  319. encoding=encoding_iana,
  320. )
  321. elif not deferred_decoding:
  322. # UTF-7 BOM is encoded in modified Base64 whose byte boundary
  323. # can overlap with the next character. Stripping raw SIG bytes
  324. # before decoding may leave stray bytes that decode as garbage.
  325. # Decode the full sequence and remove the leading BOM char instead.
  326. # see https://github.com/jawah/charset_normalizer/issues/718
  327. # and https://github.com/jawah/charset_normalizer/issues/716
  328. if encoding_iana == "utf_7" and bom_or_sig_available:
  329. decoded_payload = str(
  330. sequences,
  331. encoding=encoding_iana,
  332. )
  333. if decoded_payload and decoded_payload[0] == "\ufeff":
  334. decoded_payload = decoded_payload[1:]
  335. else:
  336. decoded_payload = str(
  337. (
  338. sequences
  339. if not strip_sig_or_bom
  340. else sequences[len(sig_payload) :]
  341. ),
  342. encoding=encoding_iana,
  343. )
  344. except (UnicodeDecodeError, LookupError) as e:
  345. if not isinstance(e, LookupError):
  346. logger.log(
  347. TRACE,
  348. "Code page %s does not fit given bytes sequence at ALL. %s",
  349. encoding_iana,
  350. str(e),
  351. )
  352. tested_but_hard_failure.append(encoding_iana)
  353. continue
  354. r_ = range(
  355. 0 if not bom_or_sig_available else len(sig_payload),
  356. length,
  357. int(length / steps),
  358. )
  359. multi_byte_bonus: bool = (
  360. is_multi_byte_decoder
  361. and decoded_payload is not None
  362. and len(decoded_payload) < length
  363. )
  364. if multi_byte_bonus:
  365. logger.log(
  366. TRACE,
  367. "Code page %s is a multi byte encoding table and it appear that at least one character "
  368. "was encoded using n-bytes.",
  369. encoding_iana,
  370. )
  371. max_chunk_gave_up: int = int(len(r_) / 4)
  372. max_chunk_gave_up = max(max_chunk_gave_up, 2)
  373. early_stop_count: int = 0
  374. lazy_str_hard_failure = False
  375. md_chunks: list[str] = []
  376. md_ratios = []
  377. try:
  378. for chunk in cut_sequence_chunks(
  379. sequences,
  380. encoding_iana,
  381. r_,
  382. chunk_size,
  383. bom_or_sig_available,
  384. strip_sig_or_bom,
  385. sig_payload,
  386. is_multi_byte_decoder,
  387. decoded_payload,
  388. deferred_decoding,
  389. ):
  390. md_chunks.append(chunk)
  391. md_ratios.append(
  392. cached_mess_ratio(
  393. chunk,
  394. threshold,
  395. explain and 1 <= len(cp_isolation) <= 2,
  396. )
  397. )
  398. if md_ratios[-1] >= threshold:
  399. early_stop_count += 1
  400. if (early_stop_count >= max_chunk_gave_up) or (
  401. bom_or_sig_available and not strip_sig_or_bom
  402. ):
  403. break
  404. except (
  405. UnicodeDecodeError,
  406. LookupError,
  407. ) as e: # Lazy str loading may have missed something there
  408. if deferred_decoding:
  409. # Deferred single-byte validation failed on a chunk (or the
  410. # codec is unavailable on this interpreter build): identical
  411. # outcome and bookkeeping to the eager full-decode failure.
  412. logger.log(
  413. TRACE,
  414. "Code page %s does not fit given bytes sequence at ALL. %s",
  415. encoding_iana,
  416. str(e),
  417. )
  418. tested_but_hard_failure.append(encoding_iana)
  419. continue
  420. logger.log(
  421. TRACE,
  422. "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s",
  423. encoding_iana,
  424. str(e),
  425. )
  426. early_stop_count = max_chunk_gave_up
  427. lazy_str_hard_failure = True
  428. # We might want to check the sequence again with the whole content
  429. # Only if initial MD tests passes
  430. if (
  431. not lazy_str_hard_failure
  432. and is_too_large_sequence
  433. and not is_multi_byte_decoder
  434. ):
  435. try:
  436. sequences[int(50e3) :].decode(encoding_iana, errors="strict")
  437. except UnicodeDecodeError as e:
  438. logger.log(
  439. TRACE,
  440. "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s",
  441. encoding_iana,
  442. str(e),
  443. )
  444. tested_but_hard_failure.append(encoding_iana)
  445. continue
  446. mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0
  447. if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up:
  448. tested_but_soft_failure.append(encoding_iana)
  449. if encoding_iana in IANA_SUPPORTED_SIMILAR:
  450. soft_failure_skip.update(IANA_SUPPORTED_SIMILAR[encoding_iana])
  451. # Cache this soft-failure so identical decoding from other encodings
  452. # can be skipped immediately.
  453. if decoded_payload is not None and not is_multi_byte_decoder:
  454. payload_result_cache.setdefault(
  455. hash(decoded_payload), (mean_mess_ratio, [], False)
  456. )
  457. logger.log(
  458. TRACE,
  459. "%s was excluded because of initial chaos probing. Gave up %i time(s). "
  460. "Computed mean chaos is %f %%.",
  461. encoding_iana,
  462. early_stop_count,
  463. round(mean_mess_ratio * 100, ndigits=3),
  464. )
  465. # Preparing those fallbacks in case we got nothing.
  466. if (
  467. enable_fallback
  468. and encoding_iana
  469. in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"]
  470. and not lazy_str_hard_failure
  471. ):
  472. # Always fully decode payload before.
  473. # We've missed a UnicodeDecodeError proof
  474. # while issuing release 3.4.8
  475. # see https://github.com/jawah/charset_normalizer/issues/771
  476. if decoded_payload is None:
  477. try:
  478. decoded_payload = str(
  479. (
  480. sequences
  481. if not strip_sig_or_bom
  482. else sequences[len(sig_payload) :]
  483. ),
  484. encoding=encoding_iana,
  485. )
  486. except (UnicodeDecodeError, LookupError):
  487. logger.log(
  488. TRACE,
  489. "%s does not decode the whole payload: fallback entry withheld.",
  490. encoding_iana,
  491. )
  492. continue
  493. if is_too_large_sequence:
  494. # Don't retain huge payload in RAM.
  495. decoded_payload = None
  496. fallback_entry = CharsetMatch(
  497. sequences,
  498. encoding_iana,
  499. threshold,
  500. bom_or_sig_available,
  501. [],
  502. decoded_payload,
  503. preemptive_declaration=specified_encoding,
  504. )
  505. if encoding_iana == specified_encoding:
  506. fallback_specified = fallback_entry
  507. elif encoding_iana == "ascii":
  508. fallback_ascii = fallback_entry
  509. else:
  510. fallback_u8 = fallback_entry
  511. continue
  512. if deferred_decoding:
  513. # The candidate passed chaos probing: perform the whole payload
  514. # decode (validation + payload reuse) that was deferred earlier.
  515. try:
  516. decoded_payload = str(
  517. (
  518. sequences
  519. if not strip_sig_or_bom
  520. else sequences[len(sig_payload) :]
  521. ),
  522. encoding=encoding_iana,
  523. )
  524. except (UnicodeDecodeError, LookupError) as e:
  525. logger.log(
  526. TRACE,
  527. "Code page %s does not fit given bytes sequence at ALL. %s",
  528. encoding_iana,
  529. str(e),
  530. )
  531. tested_but_hard_failure.append(encoding_iana)
  532. continue
  533. # Payload-hash deduplication: if another encoding already decoded to the
  534. # exact same string, reuse its mess_ratio and coherence results entirely.
  535. # This is strictly more general than the old IANA_SUPPORTED_SIMILAR approach
  536. # because it catches ALL identical decoding, not just pre-mapped ones.
  537. if decoded_payload is not None and not is_multi_byte_decoder:
  538. payload_hash: int = hash(decoded_payload)
  539. cached = payload_result_cache.get(payload_hash)
  540. if cached is not None:
  541. cached_mess, cached_cd, cached_passed = cached
  542. if cached_passed:
  543. # The previous encoding with identical output passed chaos probing.
  544. fast_match = CharsetMatch(
  545. sequences,
  546. encoding_iana,
  547. cached_mess,
  548. bom_or_sig_available,
  549. cached_cd,
  550. (
  551. decoded_payload
  552. if (
  553. not is_too_large_sequence
  554. or encoding_iana
  555. in [specified_encoding, "ascii", "utf_8"]
  556. )
  557. else None
  558. ),
  559. preemptive_declaration=specified_encoding,
  560. )
  561. results.append(fast_match)
  562. success_fast_tracked.add(encoding_iana)
  563. logger.log(
  564. TRACE,
  565. "%s fast-tracked (identical decoded payload to a prior encoding, chaos=%f %%).",
  566. encoding_iana,
  567. round(cached_mess * 100, ndigits=3),
  568. )
  569. if (
  570. encoding_iana in [specified_encoding, "ascii", "utf_8"]
  571. and cached_mess < 0.1
  572. ):
  573. if cached_mess == 0.0:
  574. logger.debug(
  575. "Encoding detection: %s is most likely the one.",
  576. fast_match.encoding,
  577. )
  578. if explain:
  579. logger.removeHandler(explain_handler)
  580. logger.setLevel(previous_logger_level)
  581. return CharsetMatches([fast_match])
  582. early_stop_results.append(fast_match)
  583. if (
  584. len(early_stop_results)
  585. and (specified_encoding is None or specified_encoding in tested)
  586. and "ascii" in tested
  587. and "utf_8" in tested
  588. ):
  589. probable_result: CharsetMatch = early_stop_results.best() # type: ignore[assignment]
  590. logger.debug(
  591. "Encoding detection: %s is most likely the one.",
  592. probable_result.encoding,
  593. )
  594. if explain:
  595. logger.removeHandler(explain_handler)
  596. logger.setLevel(previous_logger_level)
  597. return CharsetMatches([probable_result])
  598. continue
  599. else:
  600. # The previous encoding with identical output failed chaos
  601. # probing. Unreachable when the current candidate passed
  602. # probing on the identical payload (deterministic ratios),
  603. # kept for structural parity with the historic flow.
  604. tested_but_soft_failure.append(encoding_iana)
  605. logger.log(
  606. TRACE,
  607. "%s fast-skipped (identical decoded payload to a prior encoding that failed chaos probing).",
  608. encoding_iana,
  609. )
  610. # Prepare fallbacks for special encodings even when skipped.
  611. if enable_fallback and encoding_iana in [
  612. "ascii",
  613. "utf_8",
  614. specified_encoding,
  615. "utf_16",
  616. "utf_32",
  617. ]:
  618. fallback_entry = CharsetMatch(
  619. sequences,
  620. encoding_iana,
  621. threshold,
  622. bom_or_sig_available,
  623. [],
  624. decoded_payload,
  625. preemptive_declaration=specified_encoding,
  626. )
  627. if encoding_iana == specified_encoding:
  628. fallback_specified = fallback_entry
  629. elif encoding_iana == "ascii":
  630. fallback_ascii = fallback_entry
  631. else:
  632. fallback_u8 = fallback_entry
  633. continue
  634. logger.log(
  635. TRACE,
  636. "%s passed initial chaos probing. Mean measured chaos is %f %%",
  637. encoding_iana,
  638. round(mean_mess_ratio * 100, ndigits=3),
  639. )
  640. if not is_multi_byte_decoder:
  641. target_languages: list[str] = encoding_languages(encoding_iana)
  642. else:
  643. target_languages = mb_encoding_languages(encoding_iana)
  644. if target_languages:
  645. logger.log(
  646. TRACE,
  647. "{} should target any language(s) of {}".format(
  648. encoding_iana, str(target_languages)
  649. ),
  650. )
  651. cd_ratios = []
  652. # Run coherence detection on all chunks. We previously tried limiting to
  653. # 1-2 chunks for post-definitive encodings to save time, but this caused
  654. # coverage regressions by producing unrepresentative coherence scores.
  655. # The SB cap and language-family skip optimizations provide sufficient
  656. # speedup without sacrificing coherence accuracy.
  657. if encoding_iana != "ascii":
  658. # We shall skip the CD when its about ASCII
  659. # Most of the time its not relevant to run "language-detection" on it.
  660. lg_inclusion: str | None = (
  661. ",".join(target_languages) if target_languages else None
  662. )
  663. for chunk in md_chunks:
  664. chunk_languages = cached_coherence_ratio(
  665. chunk,
  666. language_threshold,
  667. lg_inclusion,
  668. )
  669. cd_ratios.append(chunk_languages)
  670. cd_ratios_merged = merge_coherence_ratios(cd_ratios)
  671. if cd_ratios_merged:
  672. logger.log(
  673. TRACE,
  674. "We detected language {} using {}".format(
  675. cd_ratios_merged, encoding_iana
  676. ),
  677. )
  678. current_match = CharsetMatch(
  679. sequences,
  680. encoding_iana,
  681. mean_mess_ratio,
  682. bom_or_sig_available,
  683. cd_ratios_merged,
  684. (
  685. decoded_payload
  686. if (
  687. not is_too_large_sequence
  688. or encoding_iana in [specified_encoding, "ascii", "utf_8"]
  689. )
  690. else None
  691. ),
  692. preemptive_declaration=specified_encoding,
  693. )
  694. results.append(current_match)
  695. # Cache the successful result for payload-hash deduplication.
  696. if decoded_payload is not None and not is_multi_byte_decoder:
  697. payload_result_cache.setdefault(
  698. hash(decoded_payload),
  699. (mean_mess_ratio, cd_ratios_merged, True),
  700. )
  701. # Count post-definitive same-family SB successes for the early termination cap.
  702. # Only count low-mess encodings (< 2%) toward the cap. High-mess encodings are
  703. # marginal results that shouldn't prevent better-quality candidates from being
  704. # tested. For example, iso8859_4 (mess=0%) should not be skipped just because
  705. # 7 high-mess Latin encodings (cp1252 at 8%, etc.) were tried first.
  706. if (
  707. definitive_match_found
  708. and not is_multi_byte_decoder
  709. and mean_mess_ratio < 0.02
  710. ):
  711. post_definitive_sb_success_count += 1
  712. if (
  713. encoding_iana in [specified_encoding, "ascii", "utf_8"]
  714. and mean_mess_ratio < 0.1
  715. ):
  716. # If md says nothing to worry about, then... stop immediately!
  717. if mean_mess_ratio == 0.0:
  718. logger.debug(
  719. "Encoding detection: %s is most likely the one.",
  720. current_match.encoding,
  721. )
  722. if explain: # Defensive: ensure exit path clean handler
  723. logger.removeHandler(explain_handler)
  724. logger.setLevel(previous_logger_level)
  725. return CharsetMatches([current_match])
  726. early_stop_results.append(current_match)
  727. if (
  728. len(early_stop_results)
  729. and (specified_encoding is None or specified_encoding in tested)
  730. and "ascii" in tested
  731. and "utf_8" in tested
  732. ):
  733. probable_result = early_stop_results.best() # type: ignore[assignment]
  734. logger.debug(
  735. "Encoding detection: %s is most likely the one.",
  736. probable_result.encoding, # type: ignore[union-attr]
  737. )
  738. if explain: # Defensive: ensure exit path clean handler
  739. logger.removeHandler(explain_handler)
  740. logger.setLevel(previous_logger_level)
  741. return CharsetMatches([probable_result])
  742. # Once we find a result with good coherence (>= 0.5) after testing the
  743. # prioritized encodings (ascii, utf_8), activate "definitive mode": skip
  744. # encodings that target completely different language families. This avoids
  745. # running expensive mess_ratio + coherence_ratio on clearly unrelated
  746. # candidates (e.g., Cyrillic encodings when the match is Latin-based).
  747. # We require coherence >= 0.5 to avoid false positives (e.g., cp1251 decoding
  748. # Hebrew text with 0.0 chaos but wrong language detection at coherence 0.33).
  749. if not definitive_match_found and not is_multi_byte_decoder:
  750. best_coherence = (
  751. max((v for _, v in cd_ratios_merged), default=0.0)
  752. if cd_ratios_merged
  753. else 0.0
  754. )
  755. if best_coherence >= 0.5 and "ascii" in tested and "utf_8" in tested:
  756. definitive_match_found = True
  757. definitive_target_languages.update(target_languages)
  758. logger.log(
  759. TRACE,
  760. "Definitive match found: %s (chaos=%.3f, coherence=%.2f). Encodings targeting different language families will be skipped.",
  761. encoding_iana,
  762. mean_mess_ratio,
  763. best_coherence,
  764. )
  765. # When a non-UTF multibyte encoding passes chaos probing with significant
  766. # multibyte content (decoded < 98% of raw), activate mb_definitive_match.
  767. # This skips all remaining single-byte encodings which would either soft-fail
  768. # (running expensive mess_ratio for nothing) or produce inferior results.
  769. if (
  770. not mb_definitive_match_found
  771. and is_multi_byte_decoder
  772. and multi_byte_bonus
  773. and decoded_payload is not None
  774. and len(decoded_payload) < length * 0.98
  775. and encoding_iana
  776. not in {
  777. "utf_8",
  778. "utf_8_sig",
  779. "utf_16",
  780. "utf_16_be",
  781. "utf_16_le",
  782. "utf_32",
  783. "utf_32_be",
  784. "utf_32_le",
  785. "utf_7",
  786. }
  787. and "ascii" in tested
  788. and "utf_8" in tested
  789. ):
  790. mb_definitive_match_found = True
  791. logger.log(
  792. TRACE,
  793. "Multi-byte definitive match: %s (chaos=%.3f, decoded=%d/%d=%.1f%%). Single-byte encodings will be skipped.",
  794. encoding_iana,
  795. mean_mess_ratio,
  796. len(decoded_payload),
  797. length,
  798. len(decoded_payload) / length * 100,
  799. )
  800. if encoding_iana == sig_encoding:
  801. logger.debug(
  802. "Encoding detection: %s is most likely the one as we detected a BOM or SIG within "
  803. "the beginning of the sequence.",
  804. encoding_iana,
  805. )
  806. if explain: # Defensive: ensure exit path clean handler
  807. logger.removeHandler(explain_handler)
  808. logger.setLevel(previous_logger_level)
  809. return CharsetMatches([results[encoding_iana]])
  810. if len(results) == 0:
  811. if fallback_u8 or fallback_ascii or fallback_specified:
  812. logger.log(
  813. TRACE,
  814. "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.",
  815. )
  816. if fallback_specified:
  817. logger.debug(
  818. "Encoding detection: %s will be used as a fallback match",
  819. fallback_specified.encoding,
  820. )
  821. results.append(fallback_specified)
  822. elif (
  823. (fallback_u8 and fallback_ascii is None)
  824. or (
  825. fallback_u8
  826. and fallback_ascii
  827. and fallback_u8.fingerprint != fallback_ascii.fingerprint
  828. )
  829. or (fallback_u8 is not None)
  830. ):
  831. logger.debug("Encoding detection: utf_8 will be used as a fallback match")
  832. results.append(fallback_u8)
  833. elif fallback_ascii:
  834. logger.debug("Encoding detection: ascii will be used as a fallback match")
  835. results.append(fallback_ascii)
  836. if results:
  837. logger.debug(
  838. "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.",
  839. results.best().encoding, # type: ignore
  840. len(results) - 1,
  841. )
  842. else:
  843. logger.debug("Encoding detection: Unable to determine any suitable charset.")
  844. if explain:
  845. logger.removeHandler(explain_handler)
  846. logger.setLevel(previous_logger_level)
  847. return results
  848. def from_fp(
  849. fp: BinaryIO,
  850. steps: int = 5,
  851. chunk_size: int = 512,
  852. threshold: float = 0.20,
  853. cp_isolation: list[str] | None = None,
  854. cp_exclusion: list[str] | None = None,
  855. preemptive_behaviour: bool = True,
  856. explain: bool = False,
  857. language_threshold: float = 0.1,
  858. enable_fallback: bool = True,
  859. ) -> CharsetMatches:
  860. """
  861. Same thing than the function from_bytes but using a file pointer that is already ready.
  862. Will not close the file pointer.
  863. """
  864. return from_bytes(
  865. fp.read(),
  866. steps,
  867. chunk_size,
  868. threshold,
  869. cp_isolation,
  870. cp_exclusion,
  871. preemptive_behaviour,
  872. explain,
  873. language_threshold,
  874. enable_fallback,
  875. )
  876. def from_path(
  877. path: str | bytes | PathLike, # type: ignore[type-arg]
  878. steps: int = 5,
  879. chunk_size: int = 512,
  880. threshold: float = 0.20,
  881. cp_isolation: list[str] | None = None,
  882. cp_exclusion: list[str] | None = None,
  883. preemptive_behaviour: bool = True,
  884. explain: bool = False,
  885. language_threshold: float = 0.1,
  886. enable_fallback: bool = True,
  887. ) -> CharsetMatches:
  888. """
  889. Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode.
  890. Can raise IOError.
  891. """
  892. with open(path, "rb") as fp:
  893. return from_fp(
  894. fp,
  895. steps,
  896. chunk_size,
  897. threshold,
  898. cp_isolation,
  899. cp_exclusion,
  900. preemptive_behaviour,
  901. explain,
  902. language_threshold,
  903. enable_fallback,
  904. )
  905. def is_binary(
  906. fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg]
  907. steps: int = 5,
  908. chunk_size: int = 512,
  909. threshold: float = 0.20,
  910. cp_isolation: list[str] | None = None,
  911. cp_exclusion: list[str] | None = None,
  912. preemptive_behaviour: bool = True,
  913. explain: bool = False,
  914. language_threshold: float = 0.1,
  915. enable_fallback: bool = False,
  916. ) -> bool:
  917. """
  918. Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string.
  919. Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match
  920. are disabled to be stricter around ASCII-compatible but unlikely to be a string.
  921. """
  922. if isinstance(fp_or_path_or_payload, (str, PathLike)):
  923. guesses = from_path(
  924. fp_or_path_or_payload,
  925. steps=steps,
  926. chunk_size=chunk_size,
  927. threshold=threshold,
  928. cp_isolation=cp_isolation,
  929. cp_exclusion=cp_exclusion,
  930. preemptive_behaviour=preemptive_behaviour,
  931. explain=explain,
  932. language_threshold=language_threshold,
  933. enable_fallback=enable_fallback,
  934. )
  935. elif isinstance(
  936. fp_or_path_or_payload,
  937. (
  938. bytes,
  939. bytearray,
  940. ),
  941. ):
  942. guesses = from_bytes(
  943. fp_or_path_or_payload,
  944. steps=steps,
  945. chunk_size=chunk_size,
  946. threshold=threshold,
  947. cp_isolation=cp_isolation,
  948. cp_exclusion=cp_exclusion,
  949. preemptive_behaviour=preemptive_behaviour,
  950. explain=explain,
  951. language_threshold=language_threshold,
  952. enable_fallback=enable_fallback,
  953. )
  954. else:
  955. guesses = from_fp(
  956. fp_or_path_or_payload,
  957. steps=steps,
  958. chunk_size=chunk_size,
  959. threshold=threshold,
  960. cp_isolation=cp_isolation,
  961. cp_exclusion=cp_exclusion,
  962. preemptive_behaviour=preemptive_behaviour,
  963. explain=explain,
  964. language_threshold=language_threshold,
  965. enable_fallback=enable_fallback,
  966. )
  967. return not guesses