api.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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 (%i) byte(s).",
  125. length,
  126. )
  127. elif is_too_large_sequence:
  128. logger.log(
  129. TRACE,
  130. "Using lazy str decoding because the payload is quite large, (%i) byte(s).",
  131. length,
  132. )
  133. prioritized_encodings: list[str] = []
  134. specified_encoding: str | None = (
  135. any_specified_encoding(sequences) if preemptive_behaviour else None
  136. )
  137. if specified_encoding is not None:
  138. prioritized_encodings.append(specified_encoding)
  139. logger.log(
  140. TRACE,
  141. "Detected declarative mark in sequence. Priority +1 given for %s.",
  142. specified_encoding,
  143. )
  144. tested: set[str] = set()
  145. tested_but_hard_failure: list[str] = []
  146. tested_but_soft_failure: list[str] = []
  147. soft_failure_skip: set[str] = set()
  148. # Avoid unoptimized RSS usage.
  149. # this cache is mostly interesting for
  150. # local usage. Garbage collected at the
  151. # end. Like it should.
  152. cached_mess_ratio = lru_cache(maxsize=None)(mess_ratio)
  153. cached_coherence_ratio = lru_cache(maxsize=None)(coherence_ratio)
  154. # When a definitive result (chaos=0.0 and good coherence) is found after testing
  155. # the prioritized encodings (ascii, utf_8), we can significantly reduce the remaining
  156. # work. Encodings that target completely different language families (e.g., Cyrillic
  157. # when the definitive match is Latin) are skipped entirely.
  158. # Additionally, for same-family encodings that pass chaos probing, we reuse the
  159. # definitive match's coherence ratios instead of recomputing them — a major savings
  160. # since coherence_ratio accounts for ~30% of total time on slow Latin files.
  161. definitive_match_found: bool = False
  162. definitive_target_languages: set[str] = set()
  163. # After the definitive match fires, we cap the number of additional same-family
  164. # single-byte encodings that pass chaos probing. Once we've accumulated enough
  165. # good candidates (N), further same-family SB encodings are unlikely to produce
  166. # a better best() result and just waste mess_ratio + coherence_ratio time.
  167. # The first encoding to trigger the definitive match is NOT counted (it's already in).
  168. post_definitive_sb_success_count: int = 0
  169. POST_DEFINITIVE_SB_CAP: int = 7
  170. # When a non-UTF multibyte encoding passes chaos probing with significant multibyte
  171. # content (decoded length < 98% of raw length), skip all remaining single-byte encodings.
  172. # Rationale: multi-byte decoders (CJK) have strict byte-sequence validation — if they
  173. # decode without error AND pass chaos probing with substantial multibyte content, the
  174. # data is genuinely multibyte encoded. Single-byte encodings will always decode (every
  175. # byte maps to something) but waste time on mess_ratio before failing.
  176. # The 98% threshold prevents false triggers on files that happen to have a few valid
  177. # multibyte pairs (e.g., cp424/_ude_1.txt where big5 decodes with 99% ratio).
  178. mb_definitive_match_found: bool = False
  179. fallback_ascii: CharsetMatch | None = None
  180. fallback_u8: CharsetMatch | None = None
  181. fallback_specified: CharsetMatch | None = None
  182. results: CharsetMatches = CharsetMatches()
  183. early_stop_results: CharsetMatches = CharsetMatches()
  184. sig_encoding, sig_payload = identify_sig_or_bom(sequences)
  185. if sig_encoding is not None:
  186. prioritized_encodings.insert(0, sig_encoding)
  187. logger.log(
  188. TRACE,
  189. "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.",
  190. len(sig_payload),
  191. sig_encoding,
  192. )
  193. prioritized_encodings.append("ascii")
  194. if "utf_8" not in prioritized_encodings:
  195. prioritized_encodings.append("utf_8")
  196. for encoding_iana in prioritized_encodings + IANA_SUPPORTED_MB_FIRST:
  197. if cp_isolation and encoding_iana not in cp_isolation:
  198. continue
  199. if cp_exclusion and encoding_iana in cp_exclusion:
  200. continue
  201. if encoding_iana in tested:
  202. continue
  203. tested.add(encoding_iana)
  204. decoded_payload: str | None = None
  205. bom_or_sig_available: bool = sig_encoding == encoding_iana
  206. strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom(
  207. encoding_iana
  208. )
  209. if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available:
  210. logger.log(
  211. TRACE,
  212. "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.",
  213. encoding_iana,
  214. )
  215. continue
  216. if encoding_iana in {"utf_7"} and not bom_or_sig_available:
  217. logger.log(
  218. TRACE,
  219. "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.",
  220. encoding_iana,
  221. )
  222. continue
  223. # Skip encodings similar to ones that already soft-failed (high mess ratio).
  224. # Checked BEFORE the expensive decode attempt.
  225. if encoding_iana in soft_failure_skip:
  226. logger.log(
  227. TRACE,
  228. "%s is deemed too similar to a code page that was already considered unsuited. Continuing!",
  229. encoding_iana,
  230. )
  231. continue
  232. try:
  233. is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana)
  234. except (ModuleNotFoundError, ImportError): # Defensive:
  235. logger.log(
  236. TRACE,
  237. "Encoding %s does not provide an IncrementalDecoder",
  238. encoding_iana,
  239. )
  240. continue
  241. # When we've already found a definitive match (chaos=0.0 with good coherence)
  242. # after testing the prioritized encodings, skip encodings that target
  243. # completely different language families. This avoids running expensive
  244. # mess_ratio + coherence_ratio on clearly unrelated candidates (e.g., Cyrillic
  245. # when the definitive match is Latin-based).
  246. if definitive_match_found:
  247. if not is_multi_byte_decoder:
  248. enc_languages = set(encoding_languages(encoding_iana))
  249. else:
  250. enc_languages = set(mb_encoding_languages(encoding_iana))
  251. if not enc_languages.intersection(definitive_target_languages):
  252. logger.log(
  253. TRACE,
  254. "Skipping %s: definitive match already found, this encoding targets different languages (%s vs %s).",
  255. encoding_iana,
  256. enc_languages,
  257. definitive_target_languages,
  258. )
  259. continue
  260. # After the definitive match, cap the number of additional same-family
  261. # single-byte encodings that pass chaos probing. This avoids testing the
  262. # tail of rare, low-value same-family encodings (mac_iceland, cp860, etc.)
  263. # that almost never change best() but each cost ~1-2ms of mess_ratio + coherence.
  264. if (
  265. definitive_match_found
  266. and not is_multi_byte_decoder
  267. and post_definitive_sb_success_count >= POST_DEFINITIVE_SB_CAP
  268. ):
  269. logger.log(
  270. TRACE,
  271. "Skipping %s: already accumulated %d same-family results after definitive match (cap=%d).",
  272. encoding_iana,
  273. post_definitive_sb_success_count,
  274. POST_DEFINITIVE_SB_CAP,
  275. )
  276. continue
  277. # When a multibyte encoding with significant multibyte content has already
  278. # passed chaos probing, skip all single-byte encodings. They will either fail
  279. # chaos probing (wasting mess_ratio time) or produce inferior results.
  280. if mb_definitive_match_found and not is_multi_byte_decoder:
  281. logger.log(
  282. TRACE,
  283. "Skipping single-byte %s: multi-byte definitive match already found.",
  284. encoding_iana,
  285. )
  286. continue
  287. # Single-byte candidates of regular size defer the expensive whole
  288. # payload decode until after chunk probing: single-byte codecs are
  289. # stateless (1 byte == 1 char) so decoding chunk slices is provably
  290. # identical to slicing the decoded payload, and candidates rejected
  291. # by chaos probing (the common case) never pay the full decode nor
  292. # the payload hash.
  293. deferred_decoding: bool = (
  294. not is_multi_byte_decoder and not is_too_large_sequence
  295. )
  296. try:
  297. if is_too_large_sequence and not is_multi_byte_decoder:
  298. str(
  299. (
  300. sequences[: int(50e4)]
  301. if not strip_sig_or_bom
  302. else sequences[len(sig_payload) : int(50e4)]
  303. ),
  304. encoding=encoding_iana,
  305. )
  306. elif not deferred_decoding:
  307. # UTF-7 BOM is encoded in modified Base64 whose byte boundary
  308. # can overlap with the next character. Stripping raw SIG bytes
  309. # before decoding may leave stray bytes that decode as garbage.
  310. # Decode the full sequence and remove the leading BOM char instead.
  311. # see https://github.com/jawah/charset_normalizer/issues/718
  312. # and https://github.com/jawah/charset_normalizer/issues/716
  313. if encoding_iana == "utf_7" and bom_or_sig_available:
  314. decoded_payload = str(
  315. sequences,
  316. encoding=encoding_iana,
  317. )
  318. if decoded_payload and decoded_payload[0] == "\ufeff":
  319. decoded_payload = decoded_payload[1:]
  320. else:
  321. decoded_payload = str(
  322. (
  323. sequences
  324. if not strip_sig_or_bom
  325. else sequences[len(sig_payload) :]
  326. ),
  327. encoding=encoding_iana,
  328. )
  329. except (UnicodeDecodeError, LookupError) as e:
  330. if not isinstance(e, LookupError):
  331. logger.log(
  332. TRACE,
  333. "Code page %s does not fit given bytes sequence at ALL. %s",
  334. encoding_iana,
  335. str(e),
  336. )
  337. tested_but_hard_failure.append(encoding_iana)
  338. continue
  339. r_ = range(
  340. 0 if not bom_or_sig_available else len(sig_payload),
  341. length,
  342. int(length / steps),
  343. )
  344. multi_byte_bonus: bool = (
  345. is_multi_byte_decoder
  346. and decoded_payload is not None
  347. and len(decoded_payload) < length
  348. )
  349. if multi_byte_bonus:
  350. logger.log(
  351. TRACE,
  352. "Code page %s is a multi byte encoding table and it appear that at least one character "
  353. "was encoded using n-bytes.",
  354. encoding_iana,
  355. )
  356. max_chunk_gave_up: int = int(len(r_) / 4)
  357. max_chunk_gave_up = max(max_chunk_gave_up, 2)
  358. early_stop_count: int = 0
  359. lazy_str_hard_failure = False
  360. md_chunks: list[str] = []
  361. md_ratios = []
  362. try:
  363. for chunk in cut_sequence_chunks(
  364. sequences,
  365. encoding_iana,
  366. r_,
  367. chunk_size,
  368. bom_or_sig_available,
  369. strip_sig_or_bom,
  370. sig_payload,
  371. is_multi_byte_decoder,
  372. decoded_payload,
  373. deferred_decoding,
  374. ):
  375. md_chunks.append(chunk)
  376. md_ratios.append(
  377. cached_mess_ratio(
  378. chunk,
  379. threshold,
  380. explain and 1 <= len(cp_isolation) <= 2,
  381. )
  382. )
  383. if md_ratios[-1] >= threshold:
  384. early_stop_count += 1
  385. if (early_stop_count >= max_chunk_gave_up) or (
  386. bom_or_sig_available and not strip_sig_or_bom
  387. ):
  388. break
  389. except (
  390. UnicodeDecodeError,
  391. LookupError,
  392. ) as e: # Lazy str loading may have missed something there
  393. if deferred_decoding:
  394. # Deferred single-byte validation failed on a chunk (or the
  395. # codec is unavailable on this interpreter build): identical
  396. # outcome and bookkeeping to the eager full-decode failure.
  397. logger.log(
  398. TRACE,
  399. "Code page %s does not fit given bytes sequence at ALL. %s",
  400. encoding_iana,
  401. str(e),
  402. )
  403. tested_but_hard_failure.append(encoding_iana)
  404. continue
  405. logger.log(
  406. TRACE,
  407. "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s",
  408. encoding_iana,
  409. str(e),
  410. )
  411. early_stop_count = max_chunk_gave_up
  412. lazy_str_hard_failure = True
  413. mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0
  414. # We might want to check the sequence again with the whole content,
  415. # but only if initial MD tests passed.
  416. if (
  417. not lazy_str_hard_failure
  418. and is_too_large_sequence
  419. and not is_multi_byte_decoder
  420. and mean_mess_ratio < threshold
  421. and early_stop_count < max_chunk_gave_up
  422. ):
  423. try:
  424. sequences[int(50e3) :].decode(encoding_iana, errors="strict")
  425. except UnicodeDecodeError as e:
  426. logger.log(
  427. TRACE,
  428. "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s",
  429. encoding_iana,
  430. str(e),
  431. )
  432. tested_but_hard_failure.append(encoding_iana)
  433. continue
  434. if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up:
  435. tested_but_soft_failure.append(encoding_iana)
  436. if encoding_iana in IANA_SUPPORTED_SIMILAR:
  437. soft_failure_skip.update(IANA_SUPPORTED_SIMILAR[encoding_iana])
  438. logger.log(
  439. TRACE,
  440. "%s was excluded because of initial chaos probing. Gave up %i time(s). "
  441. "Computed mean chaos is %f %%.",
  442. encoding_iana,
  443. early_stop_count,
  444. round(mean_mess_ratio * 100, ndigits=3),
  445. )
  446. # Preparing those fallbacks in case we got nothing.
  447. if (
  448. enable_fallback
  449. and encoding_iana
  450. in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"]
  451. and not lazy_str_hard_failure
  452. ):
  453. # Always fully decode payload before.
  454. # We've missed a UnicodeDecodeError proof
  455. # while issuing release 3.4.8
  456. # see https://github.com/jawah/charset_normalizer/issues/771
  457. if decoded_payload is None:
  458. try:
  459. decoded_payload = str(
  460. (
  461. sequences
  462. if not strip_sig_or_bom
  463. else sequences[len(sig_payload) :]
  464. ),
  465. encoding=encoding_iana,
  466. )
  467. except (UnicodeDecodeError, LookupError):
  468. logger.log(
  469. TRACE,
  470. "%s does not decode the whole payload: fallback entry withheld.",
  471. encoding_iana,
  472. )
  473. continue
  474. if is_too_large_sequence:
  475. # Don't retain huge payload in RAM.
  476. decoded_payload = None
  477. fallback_entry = CharsetMatch(
  478. sequences,
  479. encoding_iana,
  480. threshold,
  481. bom_or_sig_available,
  482. [],
  483. decoded_payload,
  484. preemptive_declaration=specified_encoding,
  485. )
  486. if encoding_iana == specified_encoding:
  487. fallback_specified = fallback_entry
  488. elif encoding_iana == "ascii":
  489. fallback_ascii = fallback_entry
  490. else:
  491. fallback_u8 = fallback_entry
  492. continue
  493. if deferred_decoding:
  494. # The candidate passed chaos probing: perform the whole payload
  495. # decode (validation + payload reuse) that was deferred earlier.
  496. try:
  497. decoded_payload = str(
  498. (
  499. sequences
  500. if not strip_sig_or_bom
  501. else sequences[len(sig_payload) :]
  502. ),
  503. encoding=encoding_iana,
  504. )
  505. except (UnicodeDecodeError, LookupError) as e:
  506. logger.log(
  507. TRACE,
  508. "Code page %s does not fit given bytes sequence at ALL. %s",
  509. encoding_iana,
  510. str(e),
  511. )
  512. tested_but_hard_failure.append(encoding_iana)
  513. continue
  514. logger.log(
  515. TRACE,
  516. "%s passed initial chaos probing. Mean measured chaos is %f %%",
  517. encoding_iana,
  518. round(mean_mess_ratio * 100, ndigits=3),
  519. )
  520. if not is_multi_byte_decoder:
  521. target_languages: list[str] = encoding_languages(encoding_iana)
  522. else:
  523. target_languages = mb_encoding_languages(encoding_iana)
  524. if target_languages:
  525. logger.log(
  526. TRACE,
  527. "%s should target any language(s) of %s",
  528. encoding_iana,
  529. target_languages,
  530. )
  531. cd_ratios = []
  532. # Run coherence detection on all chunks. We previously tried limiting to
  533. # 1-2 chunks for post-definitive encodings to save time, but this caused
  534. # coverage regressions by producing unrepresentative coherence scores.
  535. # The SB cap and language-family skip optimizations provide sufficient
  536. # speedup without sacrificing coherence accuracy.
  537. if encoding_iana != "ascii":
  538. # We shall skip the CD when its about ASCII
  539. # Most of the time its not relevant to run "language-detection" on it.
  540. lg_inclusion: str | None = (
  541. ",".join(target_languages) if target_languages else None
  542. )
  543. for chunk in md_chunks:
  544. chunk_languages = cached_coherence_ratio(
  545. chunk,
  546. language_threshold,
  547. lg_inclusion,
  548. )
  549. cd_ratios.append(chunk_languages)
  550. cd_ratios_merged = merge_coherence_ratios(cd_ratios)
  551. if cd_ratios_merged:
  552. logger.log(
  553. TRACE,
  554. "We detected language %s using %s",
  555. cd_ratios_merged,
  556. encoding_iana,
  557. )
  558. current_match = CharsetMatch(
  559. sequences,
  560. encoding_iana,
  561. mean_mess_ratio,
  562. bom_or_sig_available,
  563. cd_ratios_merged,
  564. (
  565. decoded_payload
  566. if (
  567. not is_too_large_sequence
  568. or encoding_iana in [specified_encoding, "ascii", "utf_8"]
  569. )
  570. else None
  571. ),
  572. preemptive_declaration=specified_encoding,
  573. )
  574. results.append(current_match)
  575. # Count post-definitive same-family SB successes for the early termination cap.
  576. # Only count low-mess encodings (< 2%) toward the cap. High-mess encodings are
  577. # marginal results that shouldn't prevent better-quality candidates from being
  578. # tested. For example, iso8859_4 (mess=0%) should not be skipped just because
  579. # 7 high-mess Latin encodings (cp1252 at 8%, etc.) were tried first.
  580. if (
  581. definitive_match_found
  582. and not is_multi_byte_decoder
  583. and mean_mess_ratio < 0.02
  584. ):
  585. post_definitive_sb_success_count += 1
  586. if (
  587. encoding_iana in [specified_encoding, "ascii", "utf_8"]
  588. and mean_mess_ratio < 0.1
  589. ):
  590. # If md says nothing to worry about, then... stop immediately!
  591. if mean_mess_ratio == 0.0:
  592. logger.debug(
  593. "Encoding detection: %s is most likely the one.",
  594. current_match.encoding,
  595. )
  596. if explain: # Defensive: ensure exit path clean handler
  597. logger.removeHandler(explain_handler)
  598. logger.setLevel(previous_logger_level)
  599. return CharsetMatches([current_match])
  600. early_stop_results.append(current_match)
  601. if (
  602. len(early_stop_results)
  603. and (specified_encoding is None or specified_encoding in tested)
  604. and "ascii" in tested
  605. and "utf_8" in tested
  606. ):
  607. probable_result = early_stop_results.best()
  608. assert probable_result is not None
  609. logger.debug(
  610. "Encoding detection: %s is most likely the one.",
  611. probable_result.encoding,
  612. )
  613. if explain: # Defensive: ensure exit path clean handler
  614. logger.removeHandler(explain_handler)
  615. logger.setLevel(previous_logger_level)
  616. return CharsetMatches([probable_result])
  617. # Once we find a result with good coherence (>= 0.5) after testing the
  618. # prioritized encodings (ascii, utf_8), activate "definitive mode": skip
  619. # encodings that target completely different language families. This avoids
  620. # running expensive mess_ratio + coherence_ratio on clearly unrelated
  621. # candidates (e.g., Cyrillic encodings when the match is Latin-based).
  622. # We require coherence >= 0.5 to avoid false positives (e.g., cp1251 decoding
  623. # Hebrew text with 0.0 chaos but wrong language detection at coherence 0.33).
  624. if not definitive_match_found and not is_multi_byte_decoder:
  625. best_coherence = (
  626. max((v for _, v in cd_ratios_merged), default=0.0)
  627. if cd_ratios_merged
  628. else 0.0
  629. )
  630. if best_coherence >= 0.5 and "ascii" in tested and "utf_8" in tested:
  631. definitive_match_found = True
  632. definitive_target_languages.update(target_languages)
  633. logger.log(
  634. TRACE,
  635. "Definitive match found: %s (chaos=%.3f, coherence=%.2f). Encodings targeting different language families will be skipped.",
  636. encoding_iana,
  637. mean_mess_ratio,
  638. best_coherence,
  639. )
  640. # When a non-UTF multibyte encoding passes chaos probing with significant
  641. # multibyte content (decoded < 98% of raw), activate mb_definitive_match.
  642. # This skips all remaining single-byte encodings which would either soft-fail
  643. # (running expensive mess_ratio for nothing) or produce inferior results.
  644. if (
  645. not mb_definitive_match_found
  646. and is_multi_byte_decoder
  647. and multi_byte_bonus
  648. and decoded_payload is not None
  649. and len(decoded_payload) < length * 0.98
  650. and encoding_iana
  651. not in {
  652. "utf_8",
  653. "utf_8_sig",
  654. "utf_16",
  655. "utf_16_be",
  656. "utf_16_le",
  657. "utf_32",
  658. "utf_32_be",
  659. "utf_32_le",
  660. "utf_7",
  661. }
  662. and "ascii" in tested
  663. and "utf_8" in tested
  664. ):
  665. mb_definitive_match_found = True
  666. logger.log(
  667. TRACE,
  668. "Multi-byte definitive match: %s (chaos=%.3f, decoded=%d/%d=%.1f%%). Single-byte encodings will be skipped.",
  669. encoding_iana,
  670. mean_mess_ratio,
  671. len(decoded_payload),
  672. length,
  673. len(decoded_payload) / length * 100,
  674. )
  675. if encoding_iana == sig_encoding:
  676. logger.debug(
  677. "Encoding detection: %s is most likely the one as we detected a BOM or SIG within "
  678. "the beginning of the sequence.",
  679. encoding_iana,
  680. )
  681. if explain: # Defensive: ensure exit path clean handler
  682. logger.removeHandler(explain_handler)
  683. logger.setLevel(previous_logger_level)
  684. return CharsetMatches([results[encoding_iana]])
  685. if len(results) == 0:
  686. if fallback_u8 or fallback_ascii or fallback_specified:
  687. logger.log(
  688. TRACE,
  689. "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.",
  690. )
  691. if fallback_specified:
  692. logger.debug(
  693. "Encoding detection: %s will be used as a fallback match",
  694. fallback_specified.encoding,
  695. )
  696. results.append(fallback_specified)
  697. elif (
  698. (fallback_u8 and fallback_ascii is None)
  699. or (
  700. fallback_u8
  701. and fallback_ascii
  702. and fallback_u8.fingerprint != fallback_ascii.fingerprint
  703. )
  704. or (fallback_u8 is not None)
  705. ):
  706. logger.debug("Encoding detection: utf_8 will be used as a fallback match")
  707. results.append(fallback_u8)
  708. elif fallback_ascii:
  709. logger.debug("Encoding detection: ascii will be used as a fallback match")
  710. results.append(fallback_ascii)
  711. if results:
  712. logger.debug(
  713. "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.",
  714. results.best().encoding, # type: ignore
  715. len(results) - 1,
  716. )
  717. else:
  718. logger.debug("Encoding detection: Unable to determine any suitable charset.")
  719. if explain:
  720. logger.removeHandler(explain_handler)
  721. logger.setLevel(previous_logger_level)
  722. return results
  723. def from_fp(
  724. fp: BinaryIO,
  725. steps: int = 5,
  726. chunk_size: int = 512,
  727. threshold: float = 0.20,
  728. cp_isolation: list[str] | None = None,
  729. cp_exclusion: list[str] | None = None,
  730. preemptive_behaviour: bool = True,
  731. explain: bool = False,
  732. language_threshold: float = 0.1,
  733. enable_fallback: bool = True,
  734. ) -> CharsetMatches:
  735. """
  736. Same thing than the function from_bytes but using a file pointer that is already ready.
  737. Will not close the file pointer.
  738. """
  739. return from_bytes(
  740. fp.read(),
  741. steps,
  742. chunk_size,
  743. threshold,
  744. cp_isolation,
  745. cp_exclusion,
  746. preemptive_behaviour,
  747. explain,
  748. language_threshold,
  749. enable_fallback,
  750. )
  751. def from_path(
  752. path: str | bytes | PathLike, # type: ignore[type-arg]
  753. steps: int = 5,
  754. chunk_size: int = 512,
  755. threshold: float = 0.20,
  756. cp_isolation: list[str] | None = None,
  757. cp_exclusion: list[str] | None = None,
  758. preemptive_behaviour: bool = True,
  759. explain: bool = False,
  760. language_threshold: float = 0.1,
  761. enable_fallback: bool = True,
  762. ) -> CharsetMatches:
  763. """
  764. Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode.
  765. Can raise IOError.
  766. """
  767. with open(path, "rb") as fp:
  768. return from_fp(
  769. fp,
  770. steps,
  771. chunk_size,
  772. threshold,
  773. cp_isolation,
  774. cp_exclusion,
  775. preemptive_behaviour,
  776. explain,
  777. language_threshold,
  778. enable_fallback,
  779. )
  780. def is_binary(
  781. fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg]
  782. steps: int = 5,
  783. chunk_size: int = 512,
  784. threshold: float = 0.20,
  785. cp_isolation: list[str] | None = None,
  786. cp_exclusion: list[str] | None = None,
  787. preemptive_behaviour: bool = True,
  788. explain: bool = False,
  789. language_threshold: float = 0.1,
  790. enable_fallback: bool = False,
  791. ) -> bool:
  792. """
  793. Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string.
  794. Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match
  795. are disabled to be stricter around ASCII-compatible but unlikely to be a string.
  796. """
  797. if isinstance(fp_or_path_or_payload, (str, PathLike)):
  798. guesses = from_path(
  799. fp_or_path_or_payload,
  800. steps=steps,
  801. chunk_size=chunk_size,
  802. threshold=threshold,
  803. cp_isolation=cp_isolation,
  804. cp_exclusion=cp_exclusion,
  805. preemptive_behaviour=preemptive_behaviour,
  806. explain=explain,
  807. language_threshold=language_threshold,
  808. enable_fallback=enable_fallback,
  809. )
  810. elif isinstance(
  811. fp_or_path_or_payload,
  812. (
  813. bytes,
  814. bytearray,
  815. ),
  816. ):
  817. guesses = from_bytes(
  818. fp_or_path_or_payload,
  819. steps=steps,
  820. chunk_size=chunk_size,
  821. threshold=threshold,
  822. cp_isolation=cp_isolation,
  823. cp_exclusion=cp_exclusion,
  824. preemptive_behaviour=preemptive_behaviour,
  825. explain=explain,
  826. language_threshold=language_threshold,
  827. enable_fallback=enable_fallback,
  828. )
  829. else:
  830. guesses = from_fp(
  831. fp_or_path_or_payload,
  832. steps=steps,
  833. chunk_size=chunk_size,
  834. threshold=threshold,
  835. cp_isolation=cp_isolation,
  836. cp_exclusion=cp_exclusion,
  837. preemptive_behaviour=preemptive_behaviour,
  838. explain=explain,
  839. language_threshold=language_threshold,
  840. enable_fallback=enable_fallback,
  841. )
  842. return not guesses