Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/chardet/__init__.py: 36%
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
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
1######################## BEGIN LICENSE BLOCK ########################
2# This library is free software; you can redistribute it and/or
3# modify it under the terms of the GNU Lesser General Public
4# License as published by the Free Software Foundation; either
5# version 2.1 of the License, or (at your option) any later version.
6#
7# This library is distributed in the hope that it will be useful,
8# but WITHOUT ANY WARRANTY; without even the implied warranty of
9# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10# Lesser General Public License for more details.
11#
12# You should have received a copy of the GNU Lesser General Public
13# License along with this library; if not, see
14# <https://www.gnu.org/licenses/>.
15######################### END LICENSE BLOCK #########################
17from typing import List, Union
19from .charsetgroupprober import CharSetGroupProber
20from .charsetprober import CharSetProber
21from .enums import InputState
22from .resultdict import ResultDict
23from .universaldetector import UniversalDetector
24from .version import VERSION, __version__
26__all__ = ["UniversalDetector", "detect", "detect_all", "__version__", "VERSION"]
29def detect(
30 byte_str: Union[bytes, bytearray], should_rename_legacy: bool = False
31) -> ResultDict:
32 """
33 Detect the encoding of the given byte string.
35 :param byte_str: The byte sequence to examine.
36 :type byte_str: ``bytes`` or ``bytearray``
37 :param should_rename_legacy: Should we rename legacy encodings
38 to their more modern equivalents?
39 :type should_rename_legacy: ``bool``
40 """
41 if not isinstance(byte_str, bytearray):
42 if not isinstance(byte_str, bytes):
43 raise TypeError(
44 f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
45 )
46 byte_str = bytearray(byte_str)
47 detector = UniversalDetector(should_rename_legacy=should_rename_legacy)
48 detector.feed(byte_str)
49 return detector.close()
52def detect_all(
53 byte_str: Union[bytes, bytearray],
54 ignore_threshold: bool = False,
55 should_rename_legacy: bool = False,
56) -> List[ResultDict]:
57 """
58 Detect all the possible encodings of the given byte string.
60 :param byte_str: The byte sequence to examine.
61 :type byte_str: ``bytes`` or ``bytearray``
62 :param ignore_threshold: Include encodings that are below
63 ``UniversalDetector.MINIMUM_THRESHOLD``
64 in results.
65 :type ignore_threshold: ``bool``
66 :param should_rename_legacy: Should we rename legacy encodings
67 to their more modern equivalents?
68 :type should_rename_legacy: ``bool``
69 """
70 if not isinstance(byte_str, bytearray):
71 if not isinstance(byte_str, bytes):
72 raise TypeError(
73 f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
74 )
75 byte_str = bytearray(byte_str)
77 detector = UniversalDetector(should_rename_legacy=should_rename_legacy)
78 detector.feed(byte_str)
79 detector.close()
81 if detector.input_state == InputState.HIGH_BYTE:
82 results: List[ResultDict] = []
83 probers: List[CharSetProber] = []
84 for prober in detector.charset_probers:
85 if isinstance(prober, CharSetGroupProber):
86 probers.extend(p for p in prober.probers)
87 else:
88 probers.append(prober)
89 for prober in probers:
90 if ignore_threshold or prober.get_confidence() > detector.MINIMUM_THRESHOLD:
91 charset_name = prober.charset_name or ""
92 lower_charset_name = charset_name.lower()
93 # Use Windows encoding name instead of ISO-8859 if we saw any
94 # extra Windows-specific bytes
95 if lower_charset_name.startswith("iso-8859") and detector.has_win_bytes:
96 charset_name = detector.ISO_WIN_MAP.get(
97 lower_charset_name, charset_name
98 )
99 # Rename legacy encodings with superset encodings if asked
100 if should_rename_legacy:
101 charset_name = detector.LEGACY_MAP.get(
102 charset_name.lower(), charset_name
103 )
104 results.append({
105 "encoding": charset_name,
106 "confidence": prober.get_confidence(),
107 "language": prober.language,
108 })
109 if len(results) > 0:
110 return sorted(results, key=lambda result: -result["confidence"])
112 return [detector.result]