Character Encoding

Resiliparse encoding utilities API documentation.

class resiliparse.parse.encoding.EncodingDetector

Bases: object

Universal character encoding detector based on uchardet.

uchardet is a C wrapper and a continuation of Mozilla’s Universal Charset Detector library. Call update() multiple times to feed the bytes of one document incrementally. Calling encoding() returns the predicted encoding name and resets the internal state so the detector can process another document.

By default, encoding names are remapped to the Python-compatible WHATWG subset described by map_encoding_to_html5(). Set html5_compatible=False on encoding() to use Python’s canonical codec name without WHATWG remapping.

encoding(html5_compatible=True)

Return a Python-compatible name for the detected encoding and reset the detector.

By default, the detected label is remapped according to the WHATWG encoding specification, which is primarily suitable for web content. Set html5_compatible=False to use Python’s codec registry without this remapping. See map_encoding_to_html5() for the adjusted mapping.

With remapping enabled, unknown encodings fall back to 'utf-8'. Otherwise, detection failure returns None. Retrieving a result always resets the detector, including on failure; subsequent updates start a new document.

Parameters:

html5_compatible – Remap encoding names according to WHATWG (default: True)

Returns:

Detected encoding name, or None if detection fails without remapping

reset()

Manually reset the encoding detector state, discarding all supplied data.

Use this to abandon a document without retrieving a result. encoding() already resets the state automatically.

update(data)

Update charset detection with another block of input bytes.

The detector shortcuts processing when it has enough data to reach certainty, so callers do not need to stop feeding input themselves. Repeated updates belong to the same document until encoding() or reset() is called.

Parameters:

data – The next block of input data

resiliparse.parse.encoding.bytes_to_str(data, encoding='utf-8', errors='ignore', fallback_encodings=('utf-8', 'cp1252'), strip_bom=True)

Helper for decoding a byte string into a unicode string using a given encoding. This encoding should be determined beforehand, e.g., with detect_encoding().

bytes_to_str() tries to decode the byte string with encoding. If that fails, it will fall back to UTF-8 and Windows-1252 (or whichever encodings where given in fallback_encodings). If all fallbacks fail as well, the string will be double-decoded with encoding and invalid characters will be treated according to errors, which has the same options as for bytes.decode() (i.e., "ignore" or "replace"). The double-decoding step ensures that the resulting string is sane and can be re-encoded without errors.

This function also takes care to strip BOMs from the beginning of the string if strip_bom=True.

Exceptions raised by the fallback iterable or a custom codec propagate unchanged.

Parameters:
  • data – Input byte string

  • encoding – Desired encoding

  • errors – Error handling for invalid characters

  • fallback_encodings – List of fallback encodings to try if the primary encoding fails

  • strip_bom – Strip BOM sequences from beginning of the string

Returns:

Decoded string

Raises:
  • LookupError – If an attempted codec or a required error handler is unknown

  • TypeError – If fallback_encodings is not iterable or an attempted label is not a string

  • UnicodeError – If all decoding attempts fail or re-encoding fails under the selected error policy

resiliparse.parse.encoding.detect_encoding(data, max_len=131072, html5_compatible=True, from_html_meta=False)

Detect the encoding of a byte string using uchardet.

This is a convenience wrapper around EncodingDetector that creates a detector for each call.

Input sampling limits processing time and temporary memory usage. If the string is longer than a nonzero max_len, ceil(max_len / 2) bytes from each end are concatenated into one sample. An odd limit therefore samples one extra byte. This is a tradeoff between performance and accuracy. If you need higher accuracy, increase the limit to feed more data into the EncodingDetector (the default should be more than enough in most cases).

The EncodingDetector relies on uchardet as its encoding detection engine. If the input string is an HTML document, you can also use the available information from the HTML meta charset tag instead. With from_html_meta=True, detect_encoding() will try to use the charset meta tag in the HTML string if one is available and ASCII-readable within the first 1024 bytes. If this fails, it will fall back to auto-detection with uchardet.

By default, the detected encoding name is remapped according to the WHATWG encoding specification, which is primarily suitable for web content. To disable this behaviour, set html5_compatible=False. For more information, see: map_encoding_to_html5(). Encodings detected from HTML meta tags are always remapped, no matter the value of html5_compatible, to ensure valid encoding names.

If WHATWG remapping is enabled, UTF-8 is returned as a fallback encoding. Otherwise, the method returns None on failure to detect the encoding.

Parameters:
  • data – Input string for which to detect the encoding

  • max_len – Maximum number of bytes to feed to detector (0 for no limit)

  • html5_compatible – Remap encoding names according to WHATWG

  • from_html_meta – If string is an HTML document, use meta tag info

Returns:

Detected encoding

Raises:

MemoryError – If the encoding detector cannot be allocated

resiliparse.parse.encoding.detect_mime(data, max_unprintable=0.05)

Try to detect common internet MIME types based on the initial magic byte sequence of data.

The check is very basic and only checks the starting bytes as well as the number of unprintable bytes. It does not replace a full-blown MIME type detection engine like Apache Tika at the moment.

Parameters:
  • data – Input bytes

  • max_unprintable – Maximum allowable ratio of unprintable characters for text

Returns:

Detected MIME type

resiliparse.parse.encoding.map_encoding_to_html5(encoding, fallback_utf8=True)

Map an encoding name to a subset of names allowed by the HTML5 standard.

This function will remap the given name according to the mapping definition given in Section 4.2 of the WHATWG encoding specification. The returned value will always be a valid Python encoding name, but the supplied input name does not necessarily have to be.

The WHATWG mapping is designed to boil down the many possible encoding names to a smaller subset of canonical names while taking into account common encoding mislabelling practices. The main purpose of this function is to map encoding names extracted from HTTP headers or websites to their canonical names, but it also makes sense to apply the mapping to an auto-detected encoding name, since it remaps some encodings based on observed practices on the web, such as the mapping from ISO-8859-1 to Windows-1252, which is more likely to be correct, even if both options are possible. EncodingDetector.encoding() already remaps its detected encodings to the WHATWG set by default.

The mapping does not involve Python’s encoding alias names, but instead uses an adjusted WHATWG mapping. Inputs not defined in this mapping are remapped to UTF-8. Hence, the function always produces a valid output, but the mapped encoding is not guaranteed to be compatible with the original encoding. Use bytes_to_str() to avoid decoding errors. You can also set fallback_utf8=False to return None instead if the supplied encoding is unknown.

The adjusted encoding mapping differs from the WHATWG spec in the following details:

  • ISO-8859-8-I name replaced with ISO-8859-8

  • WINDOWS-874 name replaced with ISO-8859-11

  • x-mac-cyrillic is unsupported

  • x-user-defined is unsupported

  • No “replacement” mapping for 7-bit versions of ISO/IEC 2022

Parameters:
  • encoding – Input encoding name

  • fallback_utf8 – Whether to fall back to UTF-8 or return None for unknown encodings

Returns:

Mapped output encoding name