| 1 |
===================== |
| 2 |
Register new Charset |
| 3 |
===================== |
| 4 |
|
| 5 |
Add a new encoding to the detector |
| 6 |
---------------------------------- |
| 7 |
|
| 8 |
Charset-Normalizer don't have to know about your encoding to be able to detect it. |
| 9 |
This library is rather agnostic of encodings and tries its best to be generic. |
| 10 |
|
| 11 |
If Python knows about your encoding, we will be able to attempt detecting it. |
| 12 |
|
| 13 |
How it works |
| 14 |
~~~~~~~~~~~~ |
| 15 |
|
| 16 |
Charset-Normalizer iterates through every encoding registered in Python's ``encodings.aliases`` registry. |
| 17 |
If your custom encoding is registered there, it will be tried automatically alongside the built-in ones. |
| 18 |
|
| 19 |
Python provides a codec registration mechanism via ``codecs.register()`` that lets you plug in any |
| 20 |
encoding table. Once registered, both Python's ``str.encode()``/``bytes.decode()`` **and** Charset-Normalizer |
| 21 |
will recognize it. |
| 22 |
|
| 23 |
Registering a custom encoding |
| 24 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 25 |
|
| 26 |
Here is a complete example that registers a fictitious single-byte encoding called ``x-my-encoding``. |
| 27 |
|
| 28 |
**Step 1 -- Define the codec** |
| 29 |
|
| 30 |
A codec needs at minimum an ``IncrementalDecoder``, an ``IncrementalEncoder``, and a ``codec_info`` search |
| 31 |
function. For a simple byte-to-character mapping, you only need a decoding table (256 entries). :: |
| 32 |
|
| 33 |
import codecs |
| 34 |
|
| 35 |
# Decoding table: maps each byte (0x00-0xFF) to a Unicode character. |
| 36 |
# Start from latin-1 as a base and override specific positions. |
| 37 |
DECODING_TABLE = list(bytes(range(256)).decode("latin-1")) |
| 38 |
|
| 39 |
# Example: remap bytes 0x80-0x83 to specific characters |
| 40 |
DECODING_TABLE[0x80] = "\u0410" # А (Cyrillic) |
| 41 |
DECODING_TABLE[0x81] = "\u0411" # Б |
| 42 |
DECODING_TABLE[0x82] = "\u0412" # В |
| 43 |
DECODING_TABLE[0x83] = "\u0413" # Г |
| 44 |
|
| 45 |
DECODING_TABLE = "".join(DECODING_TABLE) |
| 46 |
|
| 47 |
# Build the encoding map (reverse lookup: character -> byte) |
| 48 |
ENCODING_MAP = codecs.charmap_build(DECODING_TABLE) |
| 49 |
|
| 50 |
**Step 2 -- Create the codec classes** :: |
| 51 |
|
| 52 |
class MyCodec(codecs.Codec): |
| 53 |
def encode(self, input, errors="strict"): |
| 54 |
return codecs.charmap_encode(input, errors, ENCODING_MAP) |
| 55 |
|
| 56 |
def decode(self, input, errors="strict"): |
| 57 |
return codecs.charmap_decode(input, errors, DECODING_TABLE) |
| 58 |
|
| 59 |
|
| 60 |
class MyIncrementalEncoder(codecs.IncrementalEncoder): |
| 61 |
def encode(self, input, final=False): |
| 62 |
return codecs.charmap_encode(input, self.errors, ENCODING_MAP)[0] |
| 63 |
|
| 64 |
|
| 65 |
class MyIncrementalDecoder(codecs.IncrementalDecoder): |
| 66 |
def decode(self, input, final=False): |
| 67 |
return codecs.charmap_decode(input, self.errors, DECODING_TABLE)[0] |
| 68 |
|
| 69 |
|
| 70 |
class MyStreamReader(MyCodec, codecs.StreamReader): |
| 71 |
pass |
| 72 |
|
| 73 |
|
| 74 |
class MyStreamWriter(MyCodec, codecs.StreamWriter): |
| 75 |
pass |
| 76 |
|
| 77 |
**Step 3 -- Create a helper that returns the CodecInfo** :: |
| 78 |
|
| 79 |
def _get_codec_info(): |
| 80 |
return codecs.CodecInfo( |
| 81 |
name="x_my_encoding", |
| 82 |
encode=MyCodec().encode, |
| 83 |
decode=MyCodec().decode, |
| 84 |
incrementalencoder=MyIncrementalEncoder, |
| 85 |
incrementaldecoder=MyIncrementalDecoder, |
| 86 |
streamreader=MyStreamReader, |
| 87 |
streamwriter=MyStreamWriter, |
| 88 |
) |
| 89 |
|
| 90 |
**Step 4 -- Register the codec with Python** :: |
| 91 |
|
| 92 |
codecs.register( |
| 93 |
lambda name: _get_codec_info() |
| 94 |
if name in ("x-my-encoding", "x_my_encoding") |
| 95 |
else None |
| 96 |
) |
| 97 |
|
| 98 |
**Step 5 -- Make it discoverable by Charset-Normalizer** |
| 99 |
|
| 100 |
Charset-Normalizer uses ``importlib.import_module("encodings.<name>")`` internally to |
| 101 |
inspect the ``IncrementalDecoder`` of each encoding. A codec registered only via |
| 102 |
``codecs.register()`` won't have a corresponding module. You need to create one:: |
| 103 |
|
| 104 |
import sys |
| 105 |
import types |
| 106 |
from encodings.aliases import aliases |
| 107 |
|
| 108 |
# Expose the codec as a module so the import-based lookup works. |
| 109 |
mod = types.ModuleType("encodings.x_my_encoding") |
| 110 |
mod.IncrementalDecoder = MyIncrementalDecoder |
| 111 |
mod.IncrementalEncoder = MyIncrementalEncoder |
| 112 |
mod.getregentry = _get_codec_info |
| 113 |
sys.modules["encodings.x_my_encoding"] = mod |
| 114 |
|
| 115 |
# Register the alias so it appears in the candidate list. |
| 116 |
aliases["x_my_encoding"] = "x_my_encoding" |
| 117 |
|
| 118 |
.. warning:: |
| 119 |
|
| 120 |
Both the module registration and the alias **must happen before** importing |
| 121 |
``charset_normalizer``. The candidate list is built once at import time from |
| 122 |
``encodings.aliases``. |
| 123 |
|
| 124 |
**Step 6 -- Verify** :: |
| 125 |
|
| 126 |
from charset_normalizer import from_bytes |
| 127 |
|
| 128 |
sample = ( |
| 129 |
b"Hello world, this is a test of custom encoding " |
| 130 |
b"with mapped bytes: \x80\x81\x82\x83 mixed in here." |
| 131 |
) |
| 132 |
|
| 133 |
results = from_bytes(sample, cp_isolation=["x_my_encoding"]) |
| 134 |
best = results.best() |
| 135 |
print(best.encoding) # x_my_encoding |
| 136 |
print(str(best)) # Hello world, ... АБВГ mixed in here. |
| 137 |
|
| 138 |
Important notes |
| 139 |
~~~~~~~~~~~~~~~ |
| 140 |
|
| 141 |
- The codec **must** provide an ``IncrementalDecoder``. Charset-Normalizer uses incremental |
| 142 |
decoding internally and will skip encodings that don't provide one. |
| 143 |
- For single-byte encodings, ``codecs.charmap_decode`` / ``codecs.charmap_encode`` handle everything. |
| 144 |
For multi-byte encodings, you will need a more involved decoder implementation. |
| 145 |
- You do **not** need to modify any Charset-Normalizer source code. The library dynamically |
| 146 |
discovers encodings from the ``encodings.aliases`` registry at runtime. |
| 147 |
|
| 148 |
Using ``cp_isolation`` to target your encoding |
| 149 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 150 |
|
| 151 |
If you only want to test your custom encoding (useful during development), use the |
| 152 |
``cp_isolation`` parameter:: |
| 153 |
|
| 154 |
results = from_bytes(sample, cp_isolation=["x_my_encoding"]) |
| 155 |
|
| 156 |
This restricts detection to only the specified encoding(s), making the output deterministic |
| 157 |
and the execution faster. |