Skip to content

Commit c5928c6

Browse files
committed
Add chardet package to handle text decoding failures
1 parent e540008 commit c5928c6

2 files changed

Lines changed: 9 additions & 6 deletions

File tree

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ classifiers = [
2727
keywords = ["data format", "HDF5", "neutron scattering", "x-ray scattering"]
2828
requires-python = ">=3.9"
2929
dependencies = [
30+
"chardet",
3031
"colored",
3132
"h5py",
3233
"hdf5plugin",

src/nexusformat/nexus/tree.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@
218218

219219
import h5py as h5
220220
import numpy as np
221+
from typeguard import value
221222

222223
from .. import __version__ as nxversion
223224
from .lock import NXLock, NXLockException
@@ -266,16 +267,17 @@ def text(value):
266267
if isinstance(value, bytes):
267268
try:
268269
_text = value.decode(NX_CONFIG['encoding'])
269-
except UnicodeDecodeError:
270-
if NX_CONFIG['encoding'] == 'utf-8':
271-
_text = value.decode('latin-1')
272-
else:
273-
_text = value.decode('utf-8')
270+
except (UnicodeDecodeError, KeyError, LookupError):
271+
import chardet
272+
detected = chardet.detect(value)
273+
encoding = detected['encoding']
274+
if not encoding:
275+
encoding = 'latin-1'
276+
_text = value.decode(encoding, errors='replace')
274277
else:
275278
_text = str(value)
276279
return _text.replace('\x00', '').rstrip()
277280

278-
279281
def is_text(value):
280282
"""
281283
Return True if the value represents text.

0 commit comments

Comments
 (0)