charset-normalizer 3.3.2__tar.gz → 3.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/CHANGELOG.md +11 -0
  2. {charset-normalizer-3.3.2/charset_normalizer.egg-info → charset_normalizer-3.4.0}/PKG-INFO +14 -2
  3. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/api.py +60 -18
  4. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/cli/__main__.py +30 -6
  5. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/constant.py +2 -0
  6. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/legacy.py +13 -2
  7. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/md.py +16 -3
  8. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/models.py +27 -8
  9. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/version.py +1 -1
  10. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0/charset_normalizer.egg-info}/PKG-INFO +14 -2
  11. charset_normalizer-3.4.0/dev-requirements.txt +15 -0
  12. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/community/featured.rst +1 -4
  13. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/setup.cfg +2 -1
  14. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_base_detection.py +11 -0
  15. charset_normalizer-3.4.0/tests/test_edge_case.py +42 -0
  16. charset_normalizer-3.4.0/tests/test_preemptive_detection.py +66 -0
  17. charset-normalizer-3.3.2/dev-requirements.txt +0 -14
  18. charset-normalizer-3.3.2/tests/test_edge_case.py +0 -12
  19. charset-normalizer-3.3.2/tests/test_preemptive_detection.py +0 -26
  20. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/LICENSE +0 -0
  21. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/MANIFEST.in +0 -0
  22. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/README.md +0 -0
  23. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/__init__.py +0 -0
  24. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/__main__.py +0 -0
  25. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/cd.py +0 -0
  26. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/cli/__init__.py +0 -0
  27. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/py.typed +0 -0
  28. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer/utils.py +0 -0
  29. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer.egg-info/SOURCES.txt +0 -0
  30. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer.egg-info/dependency_links.txt +0 -0
  31. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer.egg-info/entry_points.txt +0 -0
  32. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer.egg-info/requires.txt +0 -0
  33. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/charset_normalizer.egg-info/top_level.txt +0 -0
  34. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/NOTICE.md +0 -0
  35. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-arabic-1.txt +0 -0
  36. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-arabic.txt +0 -0
  37. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-bulgarian.txt +0 -0
  38. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-chinese.txt +0 -0
  39. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-english.bom.txt +0 -0
  40. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-french-1.txt +0 -0
  41. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-french.txt +0 -0
  42. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-greek-2.txt +0 -0
  43. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-greek.txt +0 -0
  44. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-hebrew-2.txt +0 -0
  45. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-hebrew-3.txt +0 -0
  46. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-korean.txt +0 -0
  47. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-polish.txt +0 -0
  48. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-russian-2.txt +0 -0
  49. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-russian-3.txt +0 -0
  50. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-russian.txt +0 -0
  51. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-spanish.txt +0 -0
  52. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/data/sample-turkish.txt +0 -0
  53. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/Makefile +0 -0
  54. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/api.rst +0 -0
  55. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/community/faq.rst +0 -0
  56. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/community/speedup.rst +0 -0
  57. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/community/why_migrate.rst +0 -0
  58. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/conf.py +0 -0
  59. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/index.rst +0 -0
  60. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/make.bat +0 -0
  61. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/requirements.txt +0 -0
  62. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/user/advanced_search.rst +0 -0
  63. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/user/cli.rst +0 -0
  64. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/user/getstarted.rst +0 -0
  65. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/user/handling_result.rst +0 -0
  66. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/user/miscellaneous.rst +0 -0
  67. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/docs/user/support.rst +0 -0
  68. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/setup.py +0 -0
  69. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/__init__.py +0 -0
  70. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_cli.py +0 -0
  71. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_coherence_detection.py +0 -0
  72. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_detect_legacy.py +0 -0
  73. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_full_detection.py +0 -0
  74. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_isbinary.py +0 -0
  75. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_large_payload.py +0 -0
  76. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_logging.py +0 -0
  77. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_mess_detection.py +0 -0
  78. {charset-normalizer-3.3.2 → charset_normalizer-3.4.0}/tests/test_utils.py +0 -0
@@ -2,6 +2,17 @@
2
2
  All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
3
3
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
4
4
 
5
+ ## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08)
6
+
7
+ ### Added
8
+ - Argument `--no-preemptive` in the CLI to prevent the detector to search for hints.
9
+ - Support for Python 3.13 (#512)
10
+
11
+ ### Fixed
12
+ - Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch.
13
+ - Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537)
14
+ - Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381)
15
+
5
16
  ## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31)
6
17
 
7
18
  ### Fixed
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: charset-normalizer
3
- Version: 3.3.2
3
+ Version: 3.4.0
4
4
  Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet.
5
5
  Home-page: https://github.com/Ousret/charset_normalizer
6
6
  Author: Ahmed TAHRI
7
- Author-email: ahmed.tahri@cloudnursery.dev
7
+ Author-email: tahri.ahmed@proton.me
8
8
  License: MIT
9
9
  Project-URL: Bug Reports, https://github.com/Ousret/charset_normalizer/issues
10
10
  Project-URL: Documentation, https://charset-normalizer.readthedocs.io/en/latest
@@ -22,6 +22,7 @@ Classifier: Programming Language :: Python :: 3.9
22
22
  Classifier: Programming Language :: Python :: 3.10
23
23
  Classifier: Programming Language :: Python :: 3.11
24
24
  Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
25
26
  Classifier: Programming Language :: Python :: Implementation :: PyPy
26
27
  Classifier: Topic :: Text Processing :: Linguistic
27
28
  Classifier: Topic :: Utilities
@@ -293,6 +294,17 @@ tools.
293
294
  All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
294
295
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
295
296
 
297
+ ## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08)
298
+
299
+ ### Added
300
+ - Argument `--no-preemptive` in the CLI to prevent the detector to search for hints.
301
+ - Support for Python 3.13 (#512)
302
+
303
+ ### Fixed
304
+ - Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch.
305
+ - Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537)
306
+ - Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381)
307
+
296
308
  ## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31)
297
309
 
298
310
  ### Fixed
@@ -159,6 +159,8 @@ def from_bytes(
159
159
 
160
160
  results: CharsetMatches = CharsetMatches()
161
161
 
162
+ early_stop_results: CharsetMatches = CharsetMatches()
163
+
162
164
  sig_encoding, sig_payload = identify_sig_or_bom(sequences)
163
165
 
164
166
  if sig_encoding is not None:
@@ -221,16 +223,20 @@ def from_bytes(
221
223
  try:
222
224
  if is_too_large_sequence and is_multi_byte_decoder is False:
223
225
  str(
224
- sequences[: int(50e4)]
225
- if strip_sig_or_bom is False
226
- else sequences[len(sig_payload) : int(50e4)],
226
+ (
227
+ sequences[: int(50e4)]
228
+ if strip_sig_or_bom is False
229
+ else sequences[len(sig_payload) : int(50e4)]
230
+ ),
227
231
  encoding=encoding_iana,
228
232
  )
229
233
  else:
230
234
  decoded_payload = str(
231
- sequences
232
- if strip_sig_or_bom is False
233
- else sequences[len(sig_payload) :],
235
+ (
236
+ sequences
237
+ if strip_sig_or_bom is False
238
+ else sequences[len(sig_payload) :]
239
+ ),
234
240
  encoding=encoding_iana,
235
241
  )
236
242
  except (UnicodeDecodeError, LookupError) as e:
@@ -367,7 +373,13 @@ def from_bytes(
367
373
  and not lazy_str_hard_failure
368
374
  ):
369
375
  fallback_entry = CharsetMatch(
370
- sequences, encoding_iana, threshold, False, [], decoded_payload
376
+ sequences,
377
+ encoding_iana,
378
+ threshold,
379
+ False,
380
+ [],
381
+ decoded_payload,
382
+ preemptive_declaration=specified_encoding,
371
383
  )
372
384
  if encoding_iana == specified_encoding:
373
385
  fallback_specified = fallback_entry
@@ -421,28 +433,58 @@ def from_bytes(
421
433
  ),
422
434
  )
423
435
 
424
- results.append(
425
- CharsetMatch(
426
- sequences,
427
- encoding_iana,
428
- mean_mess_ratio,
429
- bom_or_sig_available,
430
- cd_ratios_merged,
431
- decoded_payload,
432
- )
436
+ current_match = CharsetMatch(
437
+ sequences,
438
+ encoding_iana,
439
+ mean_mess_ratio,
440
+ bom_or_sig_available,
441
+ cd_ratios_merged,
442
+ (
443
+ decoded_payload
444
+ if (
445
+ is_too_large_sequence is False
446
+ or encoding_iana in [specified_encoding, "ascii", "utf_8"]
447
+ )
448
+ else None
449
+ ),
450
+ preemptive_declaration=specified_encoding,
433
451
  )
434
452
 
453
+ results.append(current_match)
454
+
435
455
  if (
436
456
  encoding_iana in [specified_encoding, "ascii", "utf_8"]
437
457
  and mean_mess_ratio < 0.1
438
458
  ):
459
+ # If md says nothing to worry about, then... stop immediately!
460
+ if mean_mess_ratio == 0.0:
461
+ logger.debug(
462
+ "Encoding detection: %s is most likely the one.",
463
+ current_match.encoding,
464
+ )
465
+ if explain:
466
+ logger.removeHandler(explain_handler)
467
+ logger.setLevel(previous_logger_level)
468
+ return CharsetMatches([current_match])
469
+
470
+ early_stop_results.append(current_match)
471
+
472
+ if (
473
+ len(early_stop_results)
474
+ and (specified_encoding is None or specified_encoding in tested)
475
+ and "ascii" in tested
476
+ and "utf_8" in tested
477
+ ):
478
+ probable_result: CharsetMatch = early_stop_results.best() # type: ignore[assignment]
439
479
  logger.debug(
440
- "Encoding detection: %s is most likely the one.", encoding_iana
480
+ "Encoding detection: %s is most likely the one.",
481
+ probable_result.encoding,
441
482
  )
442
483
  if explain:
443
484
  logger.removeHandler(explain_handler)
444
485
  logger.setLevel(previous_logger_level)
445
- return CharsetMatches([results[encoding_iana]])
486
+
487
+ return CharsetMatches([probable_result])
446
488
 
447
489
  if encoding_iana == sig_encoding:
448
490
  logger.debug(
@@ -109,6 +109,14 @@ def cli_detect(argv: Optional[List[str]] = None) -> int:
109
109
  dest="force",
110
110
  help="Replace file without asking if you are sure, use this flag with caution.",
111
111
  )
112
+ parser.add_argument(
113
+ "-i",
114
+ "--no-preemptive",
115
+ action="store_true",
116
+ default=False,
117
+ dest="no_preemptive",
118
+ help="Disable looking at a charset declaration to hint the detector.",
119
+ )
112
120
  parser.add_argument(
113
121
  "-t",
114
122
  "--threshold",
@@ -133,21 +141,35 @@ def cli_detect(argv: Optional[List[str]] = None) -> int:
133
141
  args = parser.parse_args(argv)
134
142
 
135
143
  if args.replace is True and args.normalize is False:
144
+ if args.files:
145
+ for my_file in args.files:
146
+ my_file.close()
136
147
  print("Use --replace in addition of --normalize only.", file=sys.stderr)
137
148
  return 1
138
149
 
139
150
  if args.force is True and args.replace is False:
151
+ if args.files:
152
+ for my_file in args.files:
153
+ my_file.close()
140
154
  print("Use --force in addition of --replace only.", file=sys.stderr)
141
155
  return 1
142
156
 
143
157
  if args.threshold < 0.0 or args.threshold > 1.0:
158
+ if args.files:
159
+ for my_file in args.files:
160
+ my_file.close()
144
161
  print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr)
145
162
  return 1
146
163
 
147
164
  x_ = []
148
165
 
149
166
  for my_file in args.files:
150
- matches = from_fp(my_file, threshold=args.threshold, explain=args.verbose)
167
+ matches = from_fp(
168
+ my_file,
169
+ threshold=args.threshold,
170
+ explain=args.verbose,
171
+ preemptive_behaviour=args.no_preemptive is False,
172
+ )
151
173
 
152
174
  best_guess = matches.best()
153
175
 
@@ -155,9 +177,11 @@ def cli_detect(argv: Optional[List[str]] = None) -> int:
155
177
  print(
156
178
  'Unable to identify originating encoding for "{}". {}'.format(
157
179
  my_file.name,
158
- "Maybe try increasing maximum amount of chaos."
159
- if args.threshold < 1.0
160
- else "",
180
+ (
181
+ "Maybe try increasing maximum amount of chaos."
182
+ if args.threshold < 1.0
183
+ else ""
184
+ ),
161
185
  ),
162
186
  file=sys.stderr,
163
187
  )
@@ -258,8 +282,8 @@ def cli_detect(argv: Optional[List[str]] = None) -> int:
258
282
  try:
259
283
  x_[0].unicode_path = join(dir_path, ".".join(o_))
260
284
 
261
- with open(x_[0].unicode_path, "w", encoding="utf-8") as fp:
262
- fp.write(str(best_guess))
285
+ with open(x_[0].unicode_path, "wb") as fp:
286
+ fp.write(best_guess.output())
263
287
  except IOError as e:
264
288
  print(str(e), file=sys.stderr)
265
289
  if my_file.closed is False:
@@ -544,6 +544,8 @@ COMMON_SAFE_ASCII_CHARACTERS: Set[str] = {
544
544
  "|",
545
545
  '"',
546
546
  "-",
547
+ "(",
548
+ ")",
547
549
  }
548
550
 
549
551
 
@@ -1,13 +1,24 @@
1
- from typing import Any, Dict, Optional, Union
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, Optional
2
4
  from warnings import warn
3
5
 
4
6
  from .api import from_bytes
5
7
  from .constant import CHARDET_CORRESPONDENCE
6
8
 
9
+ # TODO: remove this check when dropping Python 3.7 support
10
+ if TYPE_CHECKING:
11
+ from typing_extensions import TypedDict
12
+
13
+ class ResultDict(TypedDict):
14
+ encoding: Optional[str]
15
+ language: str
16
+ confidence: Optional[float]
17
+
7
18
 
8
19
  def detect(
9
20
  byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any
10
- ) -> Dict[str, Optional[Union[str, float]]]:
21
+ ) -> ResultDict:
11
22
  """
12
23
  chardet legacy method
13
24
  Detect the encoding of the given byte string. It should be mostly backward-compatible.
@@ -236,7 +236,7 @@ class SuspiciousRange(MessDetectorPlugin):
236
236
 
237
237
  @property
238
238
  def ratio(self) -> float:
239
- if self._character_count <= 24:
239
+ if self._character_count <= 13:
240
240
  return 0.0
241
241
 
242
242
  ratio_of_suspicious_range_usage: float = (
@@ -260,6 +260,7 @@ class SuperWeirdWordPlugin(MessDetectorPlugin):
260
260
 
261
261
  self._buffer: str = ""
262
262
  self._buffer_accent_count: int = 0
263
+ self._buffer_glyph_count: int = 0
263
264
 
264
265
  def eligible(self, character: str) -> bool:
265
266
  return True
@@ -279,6 +280,14 @@ class SuperWeirdWordPlugin(MessDetectorPlugin):
279
280
  and is_thai(character) is False
280
281
  ):
281
282
  self._foreign_long_watch = True
283
+ if (
284
+ is_cjk(character)
285
+ or is_hangul(character)
286
+ or is_katakana(character)
287
+ or is_hiragana(character)
288
+ or is_thai(character)
289
+ ):
290
+ self._buffer_glyph_count += 1
282
291
  return
283
292
  if not self._buffer:
284
293
  return
@@ -291,17 +300,20 @@ class SuperWeirdWordPlugin(MessDetectorPlugin):
291
300
  self._character_count += buffer_length
292
301
 
293
302
  if buffer_length >= 4:
294
- if self._buffer_accent_count / buffer_length > 0.34:
303
+ if self._buffer_accent_count / buffer_length >= 0.5:
295
304
  self._is_current_word_bad = True
296
305
  # Word/Buffer ending with an upper case accentuated letter are so rare,
297
306
  # that we will consider them all as suspicious. Same weight as foreign_long suspicious.
298
- if (
307
+ elif (
299
308
  is_accentuated(self._buffer[-1])
300
309
  and self._buffer[-1].isupper()
301
310
  and all(_.isupper() for _ in self._buffer) is False
302
311
  ):
303
312
  self._foreign_long_count += 1
304
313
  self._is_current_word_bad = True
314
+ elif self._buffer_glyph_count == 1:
315
+ self._is_current_word_bad = True
316
+ self._foreign_long_count += 1
305
317
  if buffer_length >= 24 and self._foreign_long_watch:
306
318
  camel_case_dst = [
307
319
  i
@@ -325,6 +337,7 @@ class SuperWeirdWordPlugin(MessDetectorPlugin):
325
337
  self._foreign_long_watch = False
326
338
  self._buffer = ""
327
339
  self._buffer_accent_count = 0
340
+ self._buffer_glyph_count = 0
328
341
  elif (
329
342
  character not in {"<", ">", "-", "=", "~", "|", "_"}
330
343
  and character.isdigit() is False
@@ -1,9 +1,10 @@
1
1
  from encodings.aliases import aliases
2
2
  from hashlib import sha256
3
3
  from json import dumps
4
+ from re import sub
4
5
  from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
5
6
 
6
- from .constant import TOO_BIG_SEQUENCE
7
+ from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE
7
8
  from .utils import iana_name, is_multi_byte_encoding, unicode_range
8
9
 
9
10
 
@@ -16,6 +17,7 @@ class CharsetMatch:
16
17
  has_sig_or_bom: bool,
17
18
  languages: "CoherenceMatches",
18
19
  decoded_payload: Optional[str] = None,
20
+ preemptive_declaration: Optional[str] = None,
19
21
  ):
20
22
  self._payload: bytes = payload
21
23
 
@@ -33,13 +35,13 @@ class CharsetMatch:
33
35
 
34
36
  self._string: Optional[str] = decoded_payload
35
37
 
38
+ self._preemptive_declaration: Optional[str] = preemptive_declaration
39
+
36
40
  def __eq__(self, other: object) -> bool:
37
41
  if not isinstance(other, CharsetMatch):
38
- raise TypeError(
39
- "__eq__ cannot be invoked on {} and {}.".format(
40
- str(other.__class__), str(self.__class__)
41
- )
42
- )
42
+ if isinstance(other, str):
43
+ return iana_name(other) == self.encoding
44
+ return False
43
45
  return self.encoding == other.encoding and self.fingerprint == other.fingerprint
44
46
 
45
47
  def __lt__(self, other: object) -> bool:
@@ -210,7 +212,24 @@ class CharsetMatch:
210
212
  """
211
213
  if self._output_encoding is None or self._output_encoding != encoding:
212
214
  self._output_encoding = encoding
213
- self._output_payload = str(self).encode(encoding, "replace")
215
+ decoded_string = str(self)
216
+ if (
217
+ self._preemptive_declaration is not None
218
+ and self._preemptive_declaration.lower()
219
+ not in ["utf-8", "utf8", "utf_8"]
220
+ ):
221
+ patched_header = sub(
222
+ RE_POSSIBLE_ENCODING_INDICATION,
223
+ lambda m: m.string[m.span()[0] : m.span()[1]].replace(
224
+ m.groups()[0], iana_name(self._output_encoding) # type: ignore[arg-type]
225
+ ),
226
+ decoded_string[:8192],
227
+ 1,
228
+ )
229
+
230
+ decoded_string = patched_header + decoded_string[8192:]
231
+
232
+ self._output_payload = decoded_string.encode(encoding, "replace")
214
233
 
215
234
  return self._output_payload # type: ignore
216
235
 
@@ -266,7 +285,7 @@ class CharsetMatches:
266
285
  )
267
286
  )
268
287
  # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage)
269
- if len(item.raw) <= TOO_BIG_SEQUENCE:
288
+ if len(item.raw) < TOO_BIG_SEQUENCE:
270
289
  for match in self._results:
271
290
  if match.fingerprint == item.fingerprint and match.chaos == item.chaos:
272
291
  match.add_submatch(item)
@@ -2,5 +2,5 @@
2
2
  Expose version
3
3
  """
4
4
 
5
- __version__ = "3.3.2"
5
+ __version__ = "3.4.0"
6
6
  VERSION = __version__.split(".")
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: charset-normalizer
3
- Version: 3.3.2
3
+ Version: 3.4.0
4
4
  Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet.
5
5
  Home-page: https://github.com/Ousret/charset_normalizer
6
6
  Author: Ahmed TAHRI
7
- Author-email: ahmed.tahri@cloudnursery.dev
7
+ Author-email: tahri.ahmed@proton.me
8
8
  License: MIT
9
9
  Project-URL: Bug Reports, https://github.com/Ousret/charset_normalizer/issues
10
10
  Project-URL: Documentation, https://charset-normalizer.readthedocs.io/en/latest
@@ -22,6 +22,7 @@ Classifier: Programming Language :: Python :: 3.9
22
22
  Classifier: Programming Language :: Python :: 3.10
23
23
  Classifier: Programming Language :: Python :: 3.11
24
24
  Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
25
26
  Classifier: Programming Language :: Python :: Implementation :: PyPy
26
27
  Classifier: Topic :: Text Processing :: Linguistic
27
28
  Classifier: Topic :: Utilities
@@ -293,6 +294,17 @@ tools.
293
294
  All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
294
295
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
295
296
 
297
+ ## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08)
298
+
299
+ ### Added
300
+ - Argument `--no-preemptive` in the CLI to prevent the detector to search for hints.
301
+ - Support for Python 3.13 (#512)
302
+
303
+ ### Fixed
304
+ - Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch.
305
+ - Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537)
306
+ - Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381)
307
+
296
308
  ## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31)
297
309
 
298
310
  ### Fixed
@@ -0,0 +1,15 @@
1
+ --find-links https://github.com/mypyc/mypy_mypyc-wheels/releases/expanded_assets/v1.12.0+dev.b2deaaecf1a11e13bc962558992b5f2d5701f295
2
+ flake8==5.0.4
3
+ chardet==5.1.0
4
+ isort==5.11.4
5
+ codecov==2.1.13
6
+ pytest-cov==4.1.0
7
+ build>=0.10.0,<2
8
+ wheel==0.42.0
9
+ black==23.3.0
10
+ mypy==1.11.2; python_version >= '3.8' and python_version < '3.13'
11
+ mypy==1.12.0; python_version >= '3.13'
12
+ mypy==1.4.1; python_version < '3.8'
13
+ Flask==2.2.3
14
+ pytest>=7.4.4,<=8.3.3
15
+ requests==2.31.0
@@ -9,10 +9,7 @@ your level or opinions.
9
9
  Niquests
10
10
  --------
11
11
 
12
- Started as a simple though..
13
-
14
- .. image:: https://i.imgflip.com/7xet0f.jpg
15
- :width: 200
12
+ Started as a simple though.. IE 11 has built-in HTTP/2 support while Requests 2.32 does not!
16
13
 
17
14
  Most of our programs that interact with HTTP server are built with ``requests`` and
18
15
  we aren't likely to switch without a substantial effort.
@@ -6,7 +6,7 @@ long_description_content_type = text/markdown
6
6
  keywords = encoding, charset, charset-detector, detector, normalization, unicode, chardet, detect
7
7
  url = https://github.com/Ousret/charset_normalizer
8
8
  license = MIT
9
- author_email = ahmed.tahri@cloudnursery.dev
9
+ author_email = tahri.ahmed@proton.me
10
10
  author = Ahmed TAHRI
11
11
  project_urls =
12
12
  Bug Reports = https://github.com/Ousret/charset_normalizer/issues
@@ -25,6 +25,7 @@ classifiers =
25
25
  Programming Language :: Python :: 3.10
26
26
  Programming Language :: Python :: 3.11
27
27
  Programming Language :: Python :: 3.12
28
+ Programming Language :: Python :: 3.13
28
29
  Programming Language :: Python :: Implementation :: PyPy
29
30
  Topic :: Text Processing :: Linguistic
30
31
  Topic :: Utilities
@@ -123,3 +123,14 @@ def test_doc_example_short_cp1251():
123
123
  ).best()
124
124
 
125
125
  assert best_guess.encoding == "cp1251"
126
+
127
+
128
+ def test_direct_cmp_charset_match():
129
+ best_guess = from_bytes(
130
+ "😀 Hello World! How affairs are going? 😀".encode("utf_8")
131
+ ).best()
132
+
133
+ assert best_guess == "utf_8"
134
+ assert best_guess == "utf-8"
135
+ assert best_guess != 8
136
+ assert best_guess != None
@@ -0,0 +1,42 @@
1
+ from charset_normalizer import from_bytes
2
+ import pytest
3
+ import platform
4
+
5
+ @pytest.mark.xfail(platform.python_version_tuple()[0] == "3" and platform.python_version_tuple()[1] == "7", reason="Unicode database is too old for this case (Python 3.7)")
6
+ def test_unicode_edge_case():
7
+ payload = b'\xef\xbb\xbf\xf0\x9f\xa9\xb3'
8
+
9
+ best_guess = from_bytes(payload).best()
10
+
11
+ assert best_guess is not None, "Payload should have given something, detection failure"
12
+ assert best_guess.encoding == "utf_8", "UTF-8 payload wrongly detected"
13
+
14
+
15
+ def test_issue_gh520():
16
+ """Verify that minorities does not strip basic latin characters!"""
17
+ payload = b"/includes/webform.compon\xd2\xaants.inc/"
18
+
19
+ best_guess = from_bytes(payload).best()
20
+
21
+ assert best_guess is not None, "Payload should have given something, detection failure"
22
+ assert "Basic Latin" in best_guess.alphabets
23
+
24
+
25
+ def test_issue_gh509():
26
+ """Two common ASCII punctuations should render as-is."""
27
+ payload = b");"
28
+
29
+ best_guess = from_bytes(payload).best()
30
+
31
+ assert best_guess is not None, "Payload should have given something, detection failure"
32
+ assert "ascii" == best_guess.encoding
33
+
34
+
35
+ def test_issue_gh498():
36
+ """This case was mistaken for utf-16-le, this should never happen again."""
37
+ payload = b'\x84\xae\xaa\xe3\xac\xa5\xad\xe2 Microsoft Word.docx'
38
+
39
+ best_guess = from_bytes(payload).best()
40
+
41
+ assert best_guess is not None, "Payload should have given something, detection failure"
42
+ assert "Cyrillic" in best_guess.alphabets
@@ -0,0 +1,66 @@
1
+ import pytest
2
+
3
+ from charset_normalizer.utils import any_specified_encoding
4
+ from charset_normalizer import CharsetMatch
5
+
6
+
7
+ @pytest.mark.parametrize(
8
+ "payload, expected_encoding",
9
+ [
10
+ (b'<?xml version="1.0" encoding="EUC-JP"?>', "euc_jp"),
11
+ (b'<html><head><meta charset="utf-8"></head></html>', "utf_8"),
12
+ (b'<html><head><meta charset="utf-57"></head></html>', None),
13
+ (b'# coding: utf-8', "utf_8"),
14
+ (b'<?xml version="1.0" encoding="UTF-8"?>', 'utf_8'),
15
+ (b'<?xml version="1.0" encoding="US-ASCII"?>', 'ascii'),
16
+ (b'<?xml version="1.0" encoding="JohaB"?>', 'johab'),
17
+ (b'<?xml version="1.0" encoding="ibm037"?>', 'cp037'),
18
+ (b'<html><head><meta charset=WINDOWS-1252></head></html>', "cp1252"),
19
+ (b'<html><head><meta charset="WINDOWS-1256"></head></html>', "cp1256"),
20
+ ]
21
+ )
22
+ def test_detect_most_common_body_encoding(payload, expected_encoding):
23
+ specified_encoding = any_specified_encoding(
24
+ payload
25
+ )
26
+
27
+ assert specified_encoding == expected_encoding, "Unable to determine properly encoding from given body"
28
+
29
+
30
+ @pytest.mark.parametrize(
31
+ "payload, expected_outcome",
32
+ [
33
+ (b'<?xml version="1.0" encoding="EUC-JP"?>', b'<?xml version="1.0" encoding="utf_8"?>'),
34
+ (b'<html><head><meta charset="utf-8"></head></html>', b'<html><head><meta charset="utf-8"></head></html>'),
35
+ (b'<html><head><meta charset="utf-57"></head></html>', b'<html><head><meta charset="utf-57"></head></html>'),
36
+ (b'# coding: utf-8', b'# coding: utf-8'),
37
+ (b'<?xml version="1.0" encoding="UTF-8"?>', b'<?xml version="1.0" encoding="UTF-8"?>'),
38
+ (b'<?xml version="1.0" encoding="US-ASCII"?>', b'<?xml version="1.0" encoding="utf_8"?>'),
39
+ (b'<?xml version="1.0" encoding="JohaB"?>', b'<?xml version="1.0" encoding="utf_8"?>'),
40
+ (b'<html><head><meta charset=WINDOWS-1252></head></html>', b'<html><head><meta charset=utf_8></head></html>'),
41
+ (b'<html><head><meta charset="WINDOWS-1256"></head></html>', b'<html><head><meta charset="utf_8"></head></html>'),
42
+ ]
43
+ )
44
+ def test_preemptive_mark_replacement(payload, expected_outcome):
45
+ """
46
+ When generating (to Unicode converted) bytes, we want to change any potential declarative charset
47
+ to utf-8. This test that.
48
+ """
49
+ specified_encoding = any_specified_encoding(
50
+ payload
51
+ )
52
+
53
+ detected_encoding = specified_encoding if specified_encoding is not None else "utf-8"
54
+
55
+ m = CharsetMatch(
56
+ payload,
57
+ detected_encoding,
58
+ 0.,
59
+ False,
60
+ [],
61
+ preemptive_declaration=specified_encoding,
62
+ )
63
+
64
+ transformed_output = m.output()
65
+
66
+ assert transformed_output == expected_outcome
@@ -1,14 +0,0 @@
1
- flake8==5.0.4
2
- chardet==5.1.0
3
- isort==5.11.4
4
- codecov==2.1.13
5
- pytest-cov==4.1.0
6
- build==0.10.0
7
- wheel==0.41.2
8
-
9
- black==23.3.0
10
- mypy==1.6.1; python_version >= '3.8'
11
- mypy==1.4.1; python_version < '3.8'
12
- Flask==2.2.3
13
- pytest==7.4.3
14
- requests==2.31.0
@@ -1,12 +0,0 @@
1
- from charset_normalizer import from_bytes
2
- import pytest
3
- import platform
4
-
5
- @pytest.mark.xfail(platform.python_version_tuple()[0] == "3" and platform.python_version_tuple()[1] == "7", reason="Unicode database is too old for this case (Python 3.7)")
6
- def test_unicode_edge_case():
7
- payload = b'\xef\xbb\xbf\xf0\x9f\xa9\xb3'
8
-
9
- best_guess = from_bytes(payload).best()
10
-
11
- assert best_guess is not None, "Payload should have given something, detection failure"
12
- assert best_guess.encoding == "utf_8", "UTF-8 payload wrongly detected"
@@ -1,26 +0,0 @@
1
- import pytest
2
-
3
- from charset_normalizer.utils import any_specified_encoding
4
-
5
-
6
- @pytest.mark.parametrize(
7
- "payload, expected_encoding",
8
- [
9
- (b'<?xml version="1.0" encoding="EUC-JP"?>', "euc_jp"),
10
- (b'<html><head><meta charset="utf-8"></head></html>', "utf_8"),
11
- (b'<html><head><meta charset="utf-57"></head></html>', None),
12
- (b'# coding: utf-8', "utf_8"),
13
- (b'<?xml version="1.0" encoding="UTF-8"?>', 'utf_8'),
14
- (b'<?xml version="1.0" encoding="US-ASCII"?>', 'ascii'),
15
- (b'<?xml version="1.0" encoding="JohaB"?>', 'johab'),
16
- (b'<?xml version="1.0" encoding="ibm037"?>', 'cp037'),
17
- (b'<html><head><meta charset=WINDOWS-1252></head></html>', "cp1252"),
18
- (b'<html><head><meta charset="WINDOWS-1256"></head></html>', "cp1256"),
19
- ]
20
- )
21
- def test_detect_most_common_body_encoding(payload, expected_encoding):
22
- specified_encoding = any_specified_encoding(
23
- payload
24
- )
25
-
26
- assert specified_encoding == expected_encoding, "Unable to determine properly encoding from given body"