Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/chardet/output_names.py: 57%
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"""Public-API encoding-name remapping.
3Two output transforms applied to detection results before they cross the
4public API:
6* :func:`apply_preferred_superset` -- when the ``prefer_superset`` API option
7 is enabled, replaces detected ISO/subset encoding names with their
8 Windows/CP supersets that modern software actually uses
9 (e.g., ISO-8859-1 -> Windows-1252).
11* :func:`apply_compat_names` -- when the default ``compat_names=True`` mode
12 is enabled, maps internal Python codec names to the names chardet 5.x/6.x
13 returned, preserving backward compatibility for callers that compare
14 encoding strings directly.
16Both transforms operate in-place on a :class:`~chardet.pipeline.DetectionDict`
17and return the same dict for fluent chaining.
18"""
20from __future__ import annotations
22import codecs
24from chardet._utils import decodes_completely, decodes_without_error
25from chardet.enums import EncodingEra
26from chardet.pipeline import DetectionDict
27from chardet.registry import REGISTRY
29# Preferred superset name for each encoding, used by the ``prefer_superset``
30# API option. When enabled, detected encoding names are replaced with the
31# Windows/CP superset that modern software actually uses (browsers, editors,
32# etc. treat these ISO subsets as their Windows counterparts).
33# This is a *selection*, not the codec fact: the registry owns which
34# superset each encoding has (``EncodingInfo.superset``), and this table is
35# the frozen subset of those pairs the option applies. It is public through
36# ``UniversalDetector.LEGACY_MAP``, so adding a pair changes
37# ``prefer_superset=True`` output (ADR-0007). ``iso8859-11`` is an alias of
38# the registry's ``tis-620``, which the pipeline reports instead.
39# Values are lowercase codec names, like the keys: this table only swaps one
40# codec for another. Display casing ("Windows-1252") is a separate step that
41# :data:`_COMPAT_NAMES` applies afterwards, and a display-cased value here
42# would reach it under a name it cannot map and no codec accepts.
43PREFERRED_SUPERSET: dict[str, str] = {
44 "ascii": "cp1252",
45 "euc_kr": "cp949",
46 "iso8859-1": "cp1252",
47 "iso8859-2": "cp1250",
48 "iso8859-5": "cp1251",
49 "iso8859-6": "cp1256",
50 "iso8859-7": "cp1253",
51 "iso8859-8": "cp1255",
52 "iso8859-9": "cp1254",
53 "iso8859-11": "cp874",
54 "iso8859-13": "cp1257",
55 "tis-620": "cp874",
56}
59# Mapping from Python codec names to chardet 5.x/6.x compatible display names.
60# Only entries where codec name differs from the compat output are listed.
61# Encodings where codec name == compat name (e.g., "ascii", "utf-8") and
62# encodings new to v7 have no entry — the codec name passes through unchanged.
63_COMPAT_NAMES: dict[str, str] = {
64 # 5.x compat — these encodings existed in chardet 5.x with different names
65 "big5hkscs": "Big5",
66 "cp855": "IBM855",
67 "cp866": "IBM866",
68 "cp874": "CP874",
69 "cp932": "CP932",
70 "cp949": "CP949",
71 "euc_jis_2004": "EUC-JP",
72 "euc_kr": "EUC-KR",
73 "gb18030": "GB18030",
74 "hz": "HZ-GB-2312",
75 "iso2022_jp_2": "ISO-2022-JP",
76 "iso2022_kr": "ISO-2022-KR",
77 "iso8859-1": "ISO-8859-1",
78 "iso8859-2": "ISO-8859-2",
79 "iso8859-5": "ISO-8859-5",
80 "iso8859-6": "ISO-8859-6",
81 "iso8859-7": "ISO-8859-7",
82 "iso8859-8": "ISO-8859-8",
83 "iso8859-9": "ISO-8859-9",
84 "iso8859-13": "ISO-8859-13",
85 "johab": "Johab",
86 "koi8-r": "KOI8-R",
87 "mac-cyrillic": "MacCyrillic",
88 "mac-roman": "MacRoman",
89 "shift_jis_2004": "SHIFT_JIS",
90 "tis-620": "TIS-620",
91 "utf-16": "UTF-16",
92 "utf-32": "UTF-32",
93 "utf-8-sig": "UTF-8-SIG",
94 "cp1250": "Windows-1250",
95 "cp1251": "Windows-1251",
96 "cp1252": "Windows-1252",
97 "cp1253": "Windows-1253",
98 "cp1254": "Windows-1254",
99 "cp1255": "Windows-1255",
100 "cp1256": "Windows-1256",
101 "cp1257": "Windows-1257",
102 # 6.x compat — new in chardet 6.x with different names
103 "kz1048": "KZ1048",
104 "mac-greek": "MacGreek",
105 "mac-iceland": "MacIceland",
106 "mac-latin2": "MacLatin2",
107 "mac-turkish": "MacTurkish",
108}
111def _remap_encoding(result: DetectionDict, mapping: dict[str, str]) -> DetectionDict:
112 """Replace the encoding name using *mapping*, modifying *result* in-place."""
113 enc = result.get("encoding")
114 if isinstance(enc, str):
115 result["encoding"] = mapping.get(enc, enc)
116 return result
119def apply_preferred_superset(
120 result: DetectionDict,
121 data: bytes | None = None,
122 *,
123 include_encodings: frozenset[str] | None = None,
124 exclude_encodings: frozenset[str] | None = None,
125 encoding_era: EncodingEra = EncodingEra.ALL,
126) -> DetectionDict:
127 """Replace the encoding name with its preferred Windows/CP superset.
129 Modifies the ``"encoding"`` value in *result* in-place and returns *result*
130 for fluent chaining.
132 The Windows code pages leave a few C1 positions undefined that their ISO
133 subsets map (0x81, 0x8D, 0x8F, 0x90, 0x9D under cp1252), so the remap is
134 decode-safe only for data that avoids them. When *data* is given, the
135 remap applies only if the superset decodes it; otherwise the detected
136 name stands, being the one that does.
138 :param result: A detection result dict containing an ``"encoding"`` key.
139 :param data: The bytes *result* was detected from, when known.
140 :param include_encodings: Canonical encoding names (as returned by
141 :func:`~chardet.registry.normalize_encodings`) allowed in the result.
142 The superset is skipped when it is not one of them.
143 :param exclude_encodings: Canonical encoding names forbidden in the
144 result. The superset is skipped when it is one of them.
145 :param encoding_era: The eras the result may name. The superset is
146 skipped when its era is not one of them.
147 :returns: The same *result* dict, modified in-place.
148 """
149 enc = result.get("encoding")
150 if not isinstance(enc, str):
151 return result
152 superset = PREFERRED_SUPERSET.get(enc)
153 if superset is None:
154 return result
155 if include_encodings is not None and superset not in include_encodings:
156 return result
157 if exclude_encodings is not None and superset in exclude_encodings:
158 return result
159 # A rebound table may name a codec the registry does not list.
160 info = REGISTRY.get(superset)
161 if info is not None and not info.era & encoding_era:
162 return result
163 if data is None or decodes_without_error(data, superset):
164 result["encoding"] = superset
165 return result
168# Deprecated alias — kept for external consumers.
169apply_legacy_rename = apply_preferred_superset
172#: Internal names whose display name resolves to a *narrower* Python codec.
173#: ``EUC-JP`` is ``euc_jp``, which lacks the JIS X 0213 rows that
174#: ``euc_jis_2004`` validated; ``SHIFT_JIS``, ``Big5`` and ``ISO-2022-JP``
175#: narrow ``shift_jis_2004``, ``big5hkscs`` and ``iso2022_jp_2`` the same
176#: way. A test pins this set to what :mod:`codecs` reports, so a new
177#: mapping cannot narrow silently.
178NARROWER_DISPLAY_NAMES: frozenset[str] = frozenset(
179 {"big5hkscs", "euc_jis_2004", "iso2022_jp_2", "shift_jis_2004"}
180)
183def display_codec(encoding: str) -> str:
184 """Return the codec that *encoding*'s display name resolves to.
186 ``compat_names=True`` reports ``shift_jis_2004`` as ``SHIFT_JIS``, which
187 :mod:`codecs` resolves to plain ``shift_jis``; that narrower codec is
188 the one a caller decodes with. Names without a display entry resolve
189 to themselves.
191 :param encoding: An internal (canonical registry) encoding name.
192 :returns: The Python codec name behind the name the caller sees.
193 """
194 return codecs.lookup(_COMPAT_NAMES.get(encoding, encoding)).name
197def decodes_under_public_name(data: bytes, encoding: str, *, complete: bool) -> bool:
198 """Return whether *data* decodes under the name the caller will see.
200 The display codec is checked only when it is narrower than *encoding*
201 (:data:`NARROWER_DISPLAY_NAMES`); every other display name is the same
202 codec under another spelling.
204 :param data: The bytes the caller will decode.
205 :param encoding: The internal codec name of the result.
206 :param complete: ``True`` when *data* is the caller's whole input: then
207 *encoding* itself is checked too, and both checks are strict
208 (:func:`~chardet._utils.decodes_completely`), the question the
209 decode-safety flip asks. ``False`` when *encoding* already passed
210 the tolerant validity check: then only the display codec is
211 checked, tolerating a cut sequence at the end as validity does.
212 :returns: ``True`` if the caller's decode under the public name works.
213 """
214 if complete:
215 if not decodes_completely(data, encoding):
216 return False
217 return encoding not in NARROWER_DISPLAY_NAMES or decodes_completely(
218 data, _COMPAT_NAMES[encoding]
219 )
220 return encoding not in NARROWER_DISPLAY_NAMES or decodes_without_error(
221 data, _COMPAT_NAMES[encoding]
222 )
225def apply_compat_names(
226 result: DetectionDict,
227 data: bytes | None = None,
228) -> DetectionDict:
229 """Convert internal codec names to chardet 5.x/6.x compatible names.
231 Modifies the ``"encoding"`` value in *result* in-place and returns *result*
232 for fluent chaining.
234 The internal name is the codec the pipeline validated the data under.
235 For the names in :data:`NARROWER_DISPLAY_NAMES` the display name is a
236 smaller codec, so when *data* is given the rename applies only if the
237 display codec decodes it; otherwise the internal name stands, which
238 Python's codecs accept as is. Without *data* the rename is
239 unconditional, as before.
241 :param result: A detection result dict containing an ``"encoding"`` key.
242 :param data: The bytes *result* was detected from, when known.
243 :returns: The same *result* dict, modified in-place.
244 """
245 enc = result.get("encoding")
246 if (
247 data is not None
248 and isinstance(enc, str)
249 and not decodes_under_public_name(data, enc, complete=False)
250 ):
251 return result
252 return _remap_encoding(result, _COMPAT_NAMES)