Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/charset_normalizer/api.py: 6%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

299 statements  

1from __future__ import annotations 

2 

3import logging 

4from os import PathLike 

5from typing import BinaryIO 

6 

7from .cd import ( 

8 coherence_ratio, 

9 encoding_languages, 

10 mb_encoding_languages, 

11 merge_coherence_ratios, 

12) 

13from .constant import ( 

14 IANA_SUPPORTED, 

15 IANA_SUPPORTED_SIMILAR, 

16 TOO_BIG_SEQUENCE, 

17 TOO_SMALL_SEQUENCE, 

18 TRACE, 

19 _CJK_DECODERS, 

20 _KNOWN_MB_DECODERS, 

21 _SINGLE_BYTE_DECODERS, 

22) 

23from .md import mess_ratio 

24from .models import CharsetMatch, CharsetMatches, CoherenceMatches 

25from .utils import ( 

26 any_specified_encoding, 

27 cut_sequence_chunks, 

28 iana_name, 

29 identify_sig_or_bom, 

30 should_strip_sig_or_bom, 

31) 

32 

33logger = logging.getLogger("charset_normalizer") 

34explain_handler = logging.StreamHandler() 

35explain_handler.setFormatter( 

36 logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") 

37) 

38 

39# Try known multibyte codecs first so a strong CJK match can skip single-byte 

40# candidates. The stable sort preserves IANA order within each group. 

41IANA_SUPPORTED_MB_FIRST: list[str] = sorted( 

42 IANA_SUPPORTED, key=_KNOWN_MB_DECODERS.__contains__, reverse=True 

43) 

44 

45 

46def from_bytes( 

47 sequences: bytes | bytearray, 

48 steps: int = 5, 

49 chunk_size: int = 512, 

50 threshold: float = 0.2, 

51 cp_isolation: list[str] | None = None, 

52 cp_exclusion: list[str] | None = None, 

53 preemptive_behaviour: bool = True, 

54 explain: bool = False, 

55 language_threshold: float = 0.1, 

56 enable_fallback: bool = True, 

57) -> CharsetMatches: 

58 """ 

59 Given a raw bytes sequence, return the best possibles charset usable to render str objects. 

60 If there is no results, it is a strong indicator that the source is binary/not text. 

61 By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence. 

62 And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will. 

63 

64 The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page 

65 but never take it for granted. Can improve the performance. 

66 

67 You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that 

68 purpose. 

69 

70 This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32. 

71 By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain' 

72 toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging. 

73 Custom logging format and handler can be set manually. 

74 """ 

75 

76 if not isinstance(sequences, (bytearray, bytes)): 

77 raise TypeError( 

78 "Expected object of type bytes or bytearray, got: {}".format( 

79 type(sequences) 

80 ) 

81 ) 

82 

83 if explain: 

84 previous_logger_level: int = logger.level 

85 logger.addHandler(explain_handler) 

86 logger.setLevel(TRACE) 

87 

88 length: int = len(sequences) 

89 

90 if length == 0: 

91 logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.") 

92 if explain: # Defensive: ensure exit path clean handler 

93 logger.removeHandler(explain_handler) 

94 logger.setLevel(previous_logger_level) 

95 return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")]) 

96 

97 # Snapshot TRACE for this call after explain has configured the logger. 

98 trace_enabled: bool = logger.isEnabledFor(TRACE) and not logger.disabled 

99 

100 if cp_isolation is not None: 

101 if trace_enabled: 

102 logger.log( 

103 TRACE, 

104 "cp_isolation is set. use this flag for debugging purpose. " 

105 "limited list of encoding allowed : %s.", 

106 ", ".join(cp_isolation), 

107 ) 

108 cp_isolation = [iana_name(cp, False) for cp in cp_isolation] 

109 else: 

110 cp_isolation = [] 

111 

112 if cp_exclusion is not None: 

113 if trace_enabled: 

114 logger.log( 

115 TRACE, 

116 "cp_exclusion is set. use this flag for debugging purpose. " 

117 "limited list of encoding excluded : %s.", 

118 ", ".join(cp_exclusion), 

119 ) 

120 cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion] 

121 else: 

122 cp_exclusion = [] 

123 

124 if length <= (chunk_size * steps): 

125 if trace_enabled: 

126 logger.log( 

127 TRACE, 

128 "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.", 

129 steps, 

130 chunk_size, 

131 length, 

132 ) 

133 steps = 1 

134 chunk_size = length 

135 

136 if steps > 1 and length / steps < chunk_size: 

137 chunk_size = int(length / steps) 

138 

139 is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE 

140 is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE 

141 

142 if is_too_small_sequence: 

143 if trace_enabled: 

144 logger.log( 

145 TRACE, 

146 "Trying to detect encoding from a tiny portion of (%i) byte(s).", 

147 length, 

148 ) 

149 elif is_too_large_sequence: 

150 if trace_enabled: 

151 logger.log( 

152 TRACE, 

153 "Using lazy str decoding because the payload is quite large, (%i) byte(s).", 

154 length, 

155 ) 

156 

157 prioritized_encodings: list[str] = [] 

158 

159 specified_encoding: str | None = ( 

160 any_specified_encoding(sequences) if preemptive_behaviour else None 

161 ) 

162 

163 if specified_encoding is not None: 

164 prioritized_encodings.append(specified_encoding) 

165 if trace_enabled: 

166 logger.log( 

167 TRACE, 

168 "Detected declarative mark in sequence. Priority +1 given for %s.", 

169 specified_encoding, 

170 ) 

171 

172 tested: set[str] = set() 

173 soft_failure_skip: set[str] = set() 

174 

175 # Thresholds and the explain setting are shared by every chunk in this call. 

176 mess_by_chunk: dict[str, float] = {} 

177 coherence_by_chunk: dict[tuple[str, str | None], CoherenceMatches] = {} 

178 explain_mess = explain and 1 <= len(cp_isolation) <= 2 

179 

180 # When a definitive result (chaos=0.0 and good coherence) is found after testing 

181 # the prioritized encodings (ascii, utf_8), we can significantly reduce the remaining 

182 # work. Encodings that target completely different language families (e.g., Cyrillic 

183 # when the definitive match is Latin) are skipped entirely. 

184 # Additionally, for same-family encodings that pass chaos probing, we reuse the 

185 # definitive match's coherence ratios instead of recomputing them — a major savings 

186 # since coherence_ratio accounts for ~30% of total time on slow Latin files. 

187 definitive_match_found: bool = False 

188 definitive_target_languages: set[str] = set() 

189 # After the definitive match fires, we cap the number of additional same-family 

190 # single-byte encodings that pass chaos probing. Once we've accumulated enough 

191 # good candidates (N), further same-family SB encodings are unlikely to produce 

192 # a better best() result and just waste mess_ratio + coherence_ratio time. 

193 # The first encoding to trigger the definitive match is NOT counted (it's already in). 

194 post_definitive_sb_success_count: int = 0 

195 POST_DEFINITIVE_SB_CAP: int = 7 

196 

197 # A strong CJK match can rule out further single-byte probes. 

198 mb_definitive_match_found: bool = False 

199 

200 fallback_ascii: CharsetMatch | None = None 

201 fallback_u8: CharsetMatch | None = None 

202 fallback_specified: CharsetMatch | None = None 

203 

204 results: CharsetMatches = CharsetMatches() 

205 

206 early_stop_results: CharsetMatches = CharsetMatches() 

207 

208 sig_encoding, sig_payload = identify_sig_or_bom(sequences) 

209 

210 if sig_encoding is not None: 

211 prioritized_encodings.insert(0, sig_encoding) 

212 if trace_enabled: 

213 logger.log( 

214 TRACE, 

215 "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.", 

216 len(sig_payload), 

217 sig_encoding, 

218 ) 

219 

220 prioritized_encodings.append("ascii") 

221 

222 if "utf_8" not in prioritized_encodings: 

223 prioritized_encodings.append("utf_8") 

224 

225 sample_offsets: range | None = None 

226 for encoding_iana in prioritized_encodings + IANA_SUPPORTED_MB_FIRST: 

227 if cp_isolation and encoding_iana not in cp_isolation: 

228 continue 

229 

230 if cp_exclusion and encoding_iana in cp_exclusion: 

231 continue 

232 

233 if encoding_iana in tested: 

234 continue 

235 

236 tested.add(encoding_iana) 

237 

238 decoded_payload: str | None = None 

239 bom_or_sig_available: bool = sig_encoding == encoding_iana 

240 strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom( 

241 encoding_iana 

242 ) 

243 

244 if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available: 

245 if trace_enabled: 

246 logger.log( 

247 TRACE, 

248 "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.", 

249 encoding_iana, 

250 ) 

251 continue 

252 if encoding_iana in {"utf_7"} and not bom_or_sig_available: 

253 if trace_enabled: 

254 logger.log( 

255 TRACE, 

256 "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.", 

257 encoding_iana, 

258 ) 

259 continue 

260 

261 # Skip encodings similar to ones that already soft-failed (high mess ratio). 

262 # Checked BEFORE the expensive decode attempt. 

263 if encoding_iana in soft_failure_skip: 

264 if trace_enabled: 

265 logger.log( 

266 TRACE, 

267 "%s is deemed too similar to a code page that was already considered unsuited. Continuing!", 

268 encoding_iana, 

269 ) 

270 continue 

271 

272 is_multi_byte_decoder = encoding_iana not in _SINGLE_BYTE_DECODERS 

273 

274 # When we've already found a definitive match (chaos=0.0 with good coherence) 

275 # after testing the prioritized encodings, skip encodings that target 

276 # completely different language families. This avoids running expensive 

277 # mess_ratio + coherence_ratio on clearly unrelated candidates (e.g., Cyrillic 

278 # when the definitive match is Latin-based). 

279 if definitive_match_found and ( 

280 not is_multi_byte_decoder or encoding_iana in _KNOWN_MB_DECODERS 

281 ): 

282 if not is_multi_byte_decoder: 

283 enc_languages = encoding_languages(encoding_iana) 

284 else: 

285 enc_languages = mb_encoding_languages(encoding_iana) 

286 if definitive_target_languages.isdisjoint(enc_languages): 

287 if trace_enabled: 

288 logger.log( 

289 TRACE, 

290 "Skipping %s: definitive match already found, this encoding targets different languages (%s vs %s).", 

291 encoding_iana, 

292 set(enc_languages), 

293 definitive_target_languages, 

294 ) 

295 continue 

296 

297 # After the definitive match, cap the number of additional same-family 

298 # single-byte encodings that pass chaos probing. This avoids testing the 

299 # tail of rare, low-value same-family encodings (mac_iceland, cp860, etc.) 

300 # that almost never change best() but each cost ~1-2ms of mess_ratio + coherence. 

301 if ( 

302 definitive_match_found 

303 and not is_multi_byte_decoder 

304 and post_definitive_sb_success_count >= POST_DEFINITIVE_SB_CAP 

305 ): 

306 if trace_enabled: 

307 logger.log( 

308 TRACE, 

309 "Skipping %s: already accumulated %d same-family results after definitive match (cap=%d).", 

310 encoding_iana, 

311 post_definitive_sb_success_count, 

312 POST_DEFINITIVE_SB_CAP, 

313 ) 

314 continue 

315 

316 # When a multibyte encoding with significant multibyte content has already 

317 # passed chaos probing, skip all single-byte encodings. They will either fail 

318 # chaos probing (wasting mess_ratio time) or produce inferior results. 

319 if mb_definitive_match_found and not is_multi_byte_decoder: 

320 if trace_enabled: 

321 logger.log( 

322 TRACE, 

323 "Skipping single-byte %s: multi-byte definitive match already found.", 

324 encoding_iana, 

325 ) 

326 continue 

327 

328 # Single-byte candidates of regular size defer the expensive whole 

329 # payload decode until after chunk probing: single-byte codecs are 

330 # stateless (1 byte == 1 char) so decoding chunk slices is provably 

331 # identical to slicing the decoded payload, and candidates rejected 

332 # by chaos probing (the common case) never pay the full decode nor 

333 # the payload hash. 

334 deferred_decoding: bool = ( 

335 not is_multi_byte_decoder and not is_too_large_sequence 

336 ) 

337 

338 try: 

339 if is_too_large_sequence and not is_multi_byte_decoder: 

340 str( 

341 ( 

342 sequences[: int(50e4)] 

343 if not strip_sig_or_bom 

344 else sequences[len(sig_payload) : int(50e4)] 

345 ), 

346 encoding=encoding_iana, 

347 ) 

348 elif not deferred_decoding: 

349 # UTF-7 BOM is encoded in modified Base64 whose byte boundary 

350 # can overlap with the next character. Stripping raw SIG bytes 

351 # before decoding may leave stray bytes that decode as garbage. 

352 # Decode the full sequence and remove the leading BOM char instead. 

353 # see https://github.com/jawah/charset_normalizer/issues/718 

354 # and https://github.com/jawah/charset_normalizer/issues/716 

355 if encoding_iana == "utf_7" and bom_or_sig_available: 

356 decoded_payload = str( 

357 sequences, 

358 encoding=encoding_iana, 

359 ) 

360 if decoded_payload and decoded_payload[0] == "\ufeff": 

361 decoded_payload = decoded_payload[1:] 

362 else: 

363 decoded_payload = str( 

364 ( 

365 sequences 

366 if not strip_sig_or_bom 

367 else sequences[len(sig_payload) :] 

368 ), 

369 encoding=encoding_iana, 

370 ) 

371 except (UnicodeDecodeError, LookupError) as e: 

372 if not isinstance(e, LookupError): 

373 if trace_enabled: 

374 logger.log( 

375 TRACE, 

376 "Code page %s does not fit given bytes sequence at ALL. %s", 

377 encoding_iana, 

378 str(e), 

379 ) 

380 continue 

381 

382 # Candidates with the same starting offset use the same samples and cutoff. 

383 sample_start = len(sig_payload) if bom_or_sig_available else 0 

384 if sample_offsets is None or sample_offsets.start != sample_start: 

385 sample_offsets = range(sample_start, length, int(length / steps)) 

386 max_chunk_gave_up = max(2, int(len(sample_offsets) / 4)) 

387 

388 multi_byte_bonus: bool = ( 

389 is_multi_byte_decoder 

390 and decoded_payload is not None 

391 and len(decoded_payload) < length 

392 ) 

393 

394 if multi_byte_bonus: 

395 if trace_enabled: 

396 logger.log( 

397 TRACE, 

398 "Code page %s is a multi byte encoding table and it appear that at least one character " 

399 "was encoded using n-bytes.", 

400 encoding_iana, 

401 ) 

402 

403 early_stop_count: int = 0 

404 lazy_str_hard_failure = False 

405 

406 md_chunks: list[str] = [] 

407 md_ratios = [] 

408 

409 try: 

410 for chunk in cut_sequence_chunks( 

411 sequences, 

412 encoding_iana, 

413 sample_offsets, 

414 chunk_size, 

415 bom_or_sig_available, 

416 strip_sig_or_bom, 

417 sig_payload, 

418 is_multi_byte_decoder, 

419 decoded_payload, 

420 deferred_decoding, 

421 ): 

422 md_chunks.append(chunk) 

423 

424 chunk_mess = mess_by_chunk.get(chunk) 

425 if chunk_mess is None: 

426 chunk_mess = mess_ratio(chunk, threshold, explain_mess) 

427 mess_by_chunk[chunk] = chunk_mess 

428 md_ratios.append(chunk_mess) 

429 

430 if chunk_mess >= threshold: 

431 early_stop_count += 1 

432 

433 if (early_stop_count >= max_chunk_gave_up) or ( 

434 bom_or_sig_available and not strip_sig_or_bom 

435 ): 

436 break 

437 except ( 

438 UnicodeDecodeError, 

439 LookupError, 

440 ) as e: # Lazy str loading may have missed something there 

441 if deferred_decoding: 

442 # Deferred single-byte validation failed on a chunk (or the 

443 # codec is unavailable on this interpreter build): identical 

444 # outcome and bookkeeping to the eager full-decode failure. 

445 if trace_enabled: 

446 logger.log( 

447 TRACE, 

448 "Code page %s does not fit given bytes sequence at ALL. %s", 

449 encoding_iana, 

450 str(e), 

451 ) 

452 continue 

453 if trace_enabled: 

454 logger.log( 

455 TRACE, 

456 "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s", 

457 encoding_iana, 

458 str(e), 

459 ) 

460 early_stop_count = max_chunk_gave_up 

461 lazy_str_hard_failure = True 

462 

463 mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0 

464 

465 # We might want to check the sequence again with the whole content, 

466 # but only if initial MD tests passed. 

467 if ( 

468 not lazy_str_hard_failure 

469 and is_too_large_sequence 

470 and not is_multi_byte_decoder 

471 and mean_mess_ratio < threshold 

472 and early_stop_count < max_chunk_gave_up 

473 ): 

474 try: 

475 sequences[int(50e3) :].decode(encoding_iana, errors="strict") 

476 except UnicodeDecodeError as e: 

477 if trace_enabled: 

478 logger.log( 

479 TRACE, 

480 "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s", 

481 encoding_iana, 

482 str(e), 

483 ) 

484 continue 

485 

486 if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up: 

487 if encoding_iana in IANA_SUPPORTED_SIMILAR: 

488 soft_failure_skip.update(IANA_SUPPORTED_SIMILAR[encoding_iana]) 

489 if trace_enabled: 

490 logger.log( 

491 TRACE, 

492 "%s was excluded because of initial chaos probing. Gave up %i time(s). " 

493 "Computed mean chaos is %f %%.", 

494 encoding_iana, 

495 early_stop_count, 

496 round(mean_mess_ratio * 100, ndigits=3), 

497 ) 

498 # Preparing those fallbacks in case we got nothing. 

499 if ( 

500 enable_fallback 

501 and encoding_iana 

502 in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"] 

503 and not lazy_str_hard_failure 

504 ): 

505 # Always fully decode payload before. 

506 # We've missed a UnicodeDecodeError proof 

507 # while issuing release 3.4.8 

508 # see https://github.com/jawah/charset_normalizer/issues/771 

509 if decoded_payload is None: 

510 try: 

511 decoded_payload = str( 

512 ( 

513 sequences 

514 if not strip_sig_or_bom 

515 else sequences[len(sig_payload) :] 

516 ), 

517 encoding=encoding_iana, 

518 ) 

519 except (UnicodeDecodeError, LookupError): 

520 if trace_enabled: 

521 logger.log( 

522 TRACE, 

523 "%s does not decode the whole payload: fallback entry withheld.", 

524 encoding_iana, 

525 ) 

526 continue 

527 if is_too_large_sequence: 

528 # Don't retain huge payload in RAM. 

529 decoded_payload = None 

530 

531 fallback_entry = CharsetMatch( 

532 sequences, 

533 encoding_iana, 

534 threshold, 

535 bom_or_sig_available, 

536 [], 

537 decoded_payload, 

538 preemptive_declaration=specified_encoding, 

539 ) 

540 if encoding_iana == specified_encoding: 

541 fallback_specified = fallback_entry 

542 elif encoding_iana == "ascii": 

543 fallback_ascii = fallback_entry 

544 else: 

545 fallback_u8 = fallback_entry 

546 continue 

547 

548 if deferred_decoding: 

549 # The candidate passed chaos probing: perform the whole payload 

550 # decode (validation + payload reuse) that was deferred earlier. 

551 try: 

552 decoded_payload = str( 

553 ( 

554 sequences 

555 if not strip_sig_or_bom 

556 else sequences[len(sig_payload) :] 

557 ), 

558 encoding=encoding_iana, 

559 ) 

560 except (UnicodeDecodeError, LookupError) as e: 

561 if trace_enabled: 

562 logger.log( 

563 TRACE, 

564 "Code page %s does not fit given bytes sequence at ALL. %s", 

565 encoding_iana, 

566 str(e), 

567 ) 

568 continue 

569 

570 if trace_enabled: 

571 logger.log( 

572 TRACE, 

573 "%s passed initial chaos probing. Mean measured chaos is %f %%", 

574 encoding_iana, 

575 round(mean_mess_ratio * 100, ndigits=3), 

576 ) 

577 

578 if not is_multi_byte_decoder: 

579 target_languages: list[str] = encoding_languages(encoding_iana) 

580 else: 

581 target_languages = mb_encoding_languages(encoding_iana) 

582 

583 if target_languages: 

584 if trace_enabled: 

585 logger.log( 

586 TRACE, 

587 "%s should target any language(s) of %s", 

588 encoding_iana, 

589 target_languages, 

590 ) 

591 

592 cd_ratios = [] 

593 

594 # Run coherence detection on all chunks. We previously tried limiting to 

595 # 1-2 chunks for post-definitive encodings to save time, but this caused 

596 # coverage regressions by producing unrepresentative coherence scores. 

597 # The SB cap and language-family skip optimizations provide sufficient 

598 # speedup without sacrificing coherence accuracy. 

599 if encoding_iana != "ascii": 

600 # We shall skip the CD when its about ASCII 

601 # Most of the time its not relevant to run "language-detection" on it. 

602 lg_inclusion: str | None = ( 

603 ",".join(target_languages) if target_languages else None 

604 ) 

605 

606 for chunk in md_chunks: 

607 key = (chunk, lg_inclusion) 

608 chunk_languages = coherence_by_chunk.get(key) 

609 if chunk_languages is None: 

610 chunk_languages = coherence_ratio( 

611 chunk, language_threshold, lg_inclusion 

612 ) 

613 coherence_by_chunk[key] = chunk_languages 

614 cd_ratios.append(chunk_languages) 

615 

616 # One chunk is already normalized, rounded and sorted by coherence_ratio. 

617 cd_ratios_merged = ( 

618 list(cd_ratios[0]) 

619 if len(cd_ratios) == 1 

620 else merge_coherence_ratios(cd_ratios) 

621 ) 

622 

623 if cd_ratios_merged: 

624 if trace_enabled: 

625 logger.log( 

626 TRACE, 

627 "We detected language %s using %s", 

628 cd_ratios_merged, 

629 encoding_iana, 

630 ) 

631 

632 current_match = CharsetMatch( 

633 sequences, 

634 encoding_iana, 

635 mean_mess_ratio, 

636 bom_or_sig_available, 

637 cd_ratios_merged, 

638 ( 

639 decoded_payload 

640 if ( 

641 not is_too_large_sequence 

642 or encoding_iana in [specified_encoding, "ascii", "utf_8"] 

643 ) 

644 else None 

645 ), 

646 preemptive_declaration=specified_encoding, 

647 ) 

648 

649 results.append(current_match) 

650 

651 # Count post-definitive same-family SB successes for the early termination cap. 

652 # Only count low-mess encodings (< 2%) toward the cap. High-mess encodings are 

653 # marginal results that shouldn't prevent better-quality candidates from being 

654 # tested. For example, iso8859_4 (mess=0%) should not be skipped just because 

655 # 7 high-mess Latin encodings (cp1252 at 8%, etc.) were tried first. 

656 if ( 

657 definitive_match_found 

658 and not is_multi_byte_decoder 

659 and mean_mess_ratio < 0.02 

660 ): 

661 post_definitive_sb_success_count += 1 

662 

663 if ( 

664 encoding_iana in [specified_encoding, "ascii", "utf_8"] 

665 and mean_mess_ratio < 0.1 

666 ): 

667 # If md says nothing to worry about, then... stop immediately! 

668 if mean_mess_ratio == 0.0: 

669 logger.debug( 

670 "Encoding detection: %s is most likely the one.", 

671 current_match.encoding, 

672 ) 

673 if explain: # Defensive: ensure exit path clean handler 

674 logger.removeHandler(explain_handler) 

675 logger.setLevel(previous_logger_level) 

676 return CharsetMatches([current_match]) 

677 

678 early_stop_results.append(current_match) 

679 

680 if ( 

681 len(early_stop_results) 

682 and (specified_encoding is None or specified_encoding in tested) 

683 and "ascii" in tested 

684 and "utf_8" in tested 

685 ): 

686 probable_result = early_stop_results.best() 

687 assert probable_result is not None 

688 logger.debug( 

689 "Encoding detection: %s is most likely the one.", 

690 probable_result.encoding, 

691 ) 

692 if explain: # Defensive: ensure exit path clean handler 

693 logger.removeHandler(explain_handler) 

694 logger.setLevel(previous_logger_level) 

695 

696 return CharsetMatches([probable_result]) 

697 

698 # Once we find a result with good coherence (>= 0.5) after testing the 

699 # prioritized encodings (ascii, utf_8), activate "definitive mode": skip 

700 # encodings that target completely different language families. This avoids 

701 # running expensive mess_ratio + coherence_ratio on clearly unrelated 

702 # candidates (e.g., Cyrillic encodings when the match is Latin-based). 

703 # We require coherence >= 0.5 to avoid false positives (e.g., cp1251 decoding 

704 # Hebrew text with 0.0 chaos but wrong language detection at coherence 0.33). 

705 if not definitive_match_found and not is_multi_byte_decoder: 

706 best_coherence = cd_ratios_merged[0][1] if cd_ratios_merged else 0.0 

707 if best_coherence >= 0.5 and "ascii" in tested and "utf_8" in tested: 

708 definitive_match_found = True 

709 definitive_target_languages.update(target_languages) 

710 if trace_enabled: 

711 logger.log( 

712 TRACE, 

713 "Definitive match found: %s (chaos=%.3f, coherence=%.2f). Encodings targeting different language families will be skipped.", 

714 encoding_iana, 

715 mean_mess_ratio, 

716 best_coherence, 

717 ) 

718 

719 # A few valid byte pairs can occur by chance (e.g. Big5 on cp424/_ude_1.txt). 

720 # Even above the 2% cutoff, noisy text needs language evidence. Clean CJK 

721 # text can have too few letters for a coherence score. 

722 if ( 

723 not mb_definitive_match_found 

724 and is_multi_byte_decoder 

725 and multi_byte_bonus 

726 and decoded_payload is not None 

727 and len(decoded_payload) < length * 0.98 

728 and encoding_iana in _CJK_DECODERS 

729 and (mean_mess_ratio == 0.0 or cd_ratios_merged) 

730 and "ascii" in tested 

731 and "utf_8" in tested 

732 ): 

733 mb_definitive_match_found = True 

734 if trace_enabled: 

735 logger.log( 

736 TRACE, 

737 "Multi-byte definitive match: %s (chaos=%.3f, decoded=%d/%d=%.1f%%). Single-byte encodings will be skipped.", 

738 encoding_iana, 

739 mean_mess_ratio, 

740 len(decoded_payload), 

741 length, 

742 len(decoded_payload) / length * 100, 

743 ) 

744 

745 if encoding_iana == sig_encoding: 

746 logger.debug( 

747 "Encoding detection: %s is most likely the one as we detected a BOM or SIG within " 

748 "the beginning of the sequence.", 

749 encoding_iana, 

750 ) 

751 if explain: # Defensive: ensure exit path clean handler 

752 logger.removeHandler(explain_handler) 

753 logger.setLevel(previous_logger_level) 

754 return CharsetMatches([results[encoding_iana]]) 

755 

756 if len(results) == 0: 

757 if fallback_u8 or fallback_ascii or fallback_specified: 

758 if trace_enabled: 

759 logger.log( 

760 TRACE, 

761 "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.", 

762 ) 

763 

764 if fallback_specified: 

765 logger.debug( 

766 "Encoding detection: %s will be used as a fallback match", 

767 fallback_specified.encoding, 

768 ) 

769 results.append(fallback_specified) 

770 elif fallback_u8 is not None: 

771 logger.debug("Encoding detection: utf_8 will be used as a fallback match") 

772 results.append(fallback_u8) 

773 elif fallback_ascii: 

774 logger.debug("Encoding detection: ascii will be used as a fallback match") 

775 results.append(fallback_ascii) 

776 

777 if results: 

778 logger.debug( 

779 "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.", 

780 results.best().encoding, # type: ignore 

781 len(results) - 1, 

782 ) 

783 else: 

784 logger.debug("Encoding detection: Unable to determine any suitable charset.") 

785 

786 if explain: 

787 logger.removeHandler(explain_handler) 

788 logger.setLevel(previous_logger_level) 

789 

790 return results 

791 

792 

793def from_fp( 

794 fp: BinaryIO, 

795 steps: int = 5, 

796 chunk_size: int = 512, 

797 threshold: float = 0.20, 

798 cp_isolation: list[str] | None = None, 

799 cp_exclusion: list[str] | None = None, 

800 preemptive_behaviour: bool = True, 

801 explain: bool = False, 

802 language_threshold: float = 0.1, 

803 enable_fallback: bool = True, 

804) -> CharsetMatches: 

805 """ 

806 Same thing than the function from_bytes but using a file pointer that is already ready. 

807 Will not close the file pointer. 

808 """ 

809 return from_bytes( 

810 fp.read(), 

811 steps, 

812 chunk_size, 

813 threshold, 

814 cp_isolation, 

815 cp_exclusion, 

816 preemptive_behaviour, 

817 explain, 

818 language_threshold, 

819 enable_fallback, 

820 ) 

821 

822 

823def from_path( 

824 path: str | bytes | PathLike, # type: ignore[type-arg] 

825 steps: int = 5, 

826 chunk_size: int = 512, 

827 threshold: float = 0.20, 

828 cp_isolation: list[str] | None = None, 

829 cp_exclusion: list[str] | None = None, 

830 preemptive_behaviour: bool = True, 

831 explain: bool = False, 

832 language_threshold: float = 0.1, 

833 enable_fallback: bool = True, 

834) -> CharsetMatches: 

835 """ 

836 Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode. 

837 Can raise IOError. 

838 """ 

839 with open(path, "rb") as fp: 

840 return from_fp( 

841 fp, 

842 steps, 

843 chunk_size, 

844 threshold, 

845 cp_isolation, 

846 cp_exclusion, 

847 preemptive_behaviour, 

848 explain, 

849 language_threshold, 

850 enable_fallback, 

851 ) 

852 

853 

854def is_binary( 

855 fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg] 

856 steps: int = 5, 

857 chunk_size: int = 512, 

858 threshold: float = 0.20, 

859 cp_isolation: list[str] | None = None, 

860 cp_exclusion: list[str] | None = None, 

861 preemptive_behaviour: bool = True, 

862 explain: bool = False, 

863 language_threshold: float = 0.1, 

864 enable_fallback: bool = False, 

865) -> bool: 

866 """ 

867 Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string. 

868 Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match 

869 are disabled to be stricter around ASCII-compatible but unlikely to be a string. 

870 """ 

871 if isinstance(fp_or_path_or_payload, (str, PathLike)): 

872 guesses = from_path( 

873 fp_or_path_or_payload, 

874 steps=steps, 

875 chunk_size=chunk_size, 

876 threshold=threshold, 

877 cp_isolation=cp_isolation, 

878 cp_exclusion=cp_exclusion, 

879 preemptive_behaviour=preemptive_behaviour, 

880 explain=explain, 

881 language_threshold=language_threshold, 

882 enable_fallback=enable_fallback, 

883 ) 

884 elif isinstance( 

885 fp_or_path_or_payload, 

886 ( 

887 bytes, 

888 bytearray, 

889 ), 

890 ): 

891 guesses = from_bytes( 

892 fp_or_path_or_payload, 

893 steps=steps, 

894 chunk_size=chunk_size, 

895 threshold=threshold, 

896 cp_isolation=cp_isolation, 

897 cp_exclusion=cp_exclusion, 

898 preemptive_behaviour=preemptive_behaviour, 

899 explain=explain, 

900 language_threshold=language_threshold, 

901 enable_fallback=enable_fallback, 

902 ) 

903 else: 

904 guesses = from_fp( 

905 fp_or_path_or_payload, 

906 steps=steps, 

907 chunk_size=chunk_size, 

908 threshold=threshold, 

909 cp_isolation=cp_isolation, 

910 cp_exclusion=cp_exclusion, 

911 preemptive_behaviour=preemptive_behaviour, 

912 explain=explain, 

913 language_threshold=language_threshold, 

914 enable_fallback=enable_fallback, 

915 ) 

916 

917 return not guesses