question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 14: ordinal not in range(128)

See original GitHub issue

Hi!

I’m getting the error above when running a simple pynetdicom storage SCP.

I’m a bit new to python so it is sure to be a simple thing. Have been googling around for a while now without luck. Any help would really welcome!

from pynetdicom import (
     AE, debug_logger, evt, AllStoragePresentationContexts,
     ALL_TRANSFER_SYNTAXES
 )

debug_logger()

def handle_store(event):
     """Handle EVT_C_STORE events."""
     ds = event.dataset(encoding="utf-8")

     return 0x0000

handlers = [(evt.EVT_C_STORE, handle_store)]

ae = AE(ae_title=b'TEST')

storage_sop_classes = [
     cx.abstract_syntax for cx in AllStoragePresentationContexts
 ]
for uid in storage_sop_classes:
     ae.add_supported_context(uid, ALL_TRANSFER_SYNTAXES)

ae.start_server(('', 11112), block=False, evt_handlers=handlers)

And the error:

E: Unable to decode the received PDU data
E: 'ascii' codec can't decode byte 0xe2 in position 14: ordinal not in range(128)
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/pynetdicom/dul.py", line 301, in _read_pdu_data
    pdu, event = self._decode_pdu(bytestream)
  File "/usr/local/lib/python3.8/dist-packages/pynetdicom/dul.py", line 133, in _decode_pdu
    pdu.decode(bytestream)
  File "/usr/local/lib/python3.8/dist-packages/pynetdicom/pdu.py", line 83, in decode
    self, attr_name, func(bytestream[sl], *args)
  File "/usr/local/lib/python3.8/dist-packages/pynetdicom/pdu.py", line 283, in _wrap_generate_items
    item.decode(item_bytes)
  File "/usr/local/lib/python3.8/dist-packages/pynetdicom/pdu_items.py", line 93, in decode
    setattr(self, attr_name, func(bytestream[sl], *args))
  File "/usr/local/lib/python3.8/dist-packages/pynetdicom/pdu_items.py", line 307, in _wrap_generate_items
    item.decode(item_bytes)
  File "/usr/local/lib/python3.8/dist-packages/pynetdicom/pdu_items.py", line 93, in decode
    setattr(self, attr_name, func(bytestream[sl], *args))
  File "/usr/local/lib/python3.8/dist-packages/pynetdicom/pdu_items.py", line 1386, in abstract_syntax_name
    value = UID(value.decode('ascii'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 14: ordinal not in range(128)
D: Abort Parameters:
D: =========================== OUTGOING A-ABORT PDU ===========================
D: Abort Source: DUL service-user
D: Abort Reason: No reason given
D: ============================= END A-ABORT PDU ==============================

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
scaramallioncommented, Dec 13, 2020

Why have you done ds = event.dataset(encoding="utf-8")? It should be just event.dataset.

Anyway, it seems like whatever you’re associating with is using non-conformant UIDs (they’re supposed to be encoded as ASCII). Could you bind the following to EVT_DATA_RECV and post the output?

from pydicom.utils import pretty_bytes

def debug_data(event):
    data = event.data
    LOGGER.debug(f"{' DEBUG - ENCODED PDU ':=^76}")
    slist = pretty_bytes(
        data, prefix=' ', delimiter=' ', max_size=None, items_per_line=25
    )
    for s in slist:
        LOGGER.debug(s)

    LOGGER.debug(f"{' END ENCODED PDU ':=^76}")


handlers = [(evt.EVT_C_STORE, handle_store), (evt.EVT_DATA_RECV, debug_data)]
0reactions
mijunycommented, Dec 10, 2022

Hi!

I’m not aware if any other solution. For me, this simple and crude node is working with OsiriX:

import logging

from pydicom.uid import UID
from pynetdicom import AE, evt, AllStoragePresentationContexts, debug_logger, pdu
from pynetdicom.pdu_items import AbstractSyntaxSubItem
from pynetdicom.utils import validate_uid

def my_setter(self, value):
    if isinstance(value, UID):
        pass
    elif isinstance(value, str):
        value = UID(value)
    elif isinstance(value, bytes):
        try:
            value = UID(value.decode('ascii'))
        except UnicodeDecodeError:
            value = UID(value.decode('utf-8'))
    elif value is None:
        pass
    else:
        raise TypeError(
            'Abstract Syntax Name must be a pydicom.uid.UID, str or bytes'
        )

    if value is not None and not validate_uid(value):
        LOGGER.error("Abstract Syntax Name is an invalid UID")
        raise ValueError("Abstract Syntax Name is an invalid UID")

    self._abstract_syntax_name = value

AbstractSyntaxSubItem.abstract_syntax_name = AbstractSyntaxSubItem.abstract_syntax_name.setter(my_setter)

pdu.AbstractSyntaxSubItem = AbstractSyntaxSubItem

debug_logger()

# Implement a handler for evt.EVT_C_STORE
def handle_store(event):
    """Handle a C-STORE request event."""
    # Decode the C-STORE request's *Data Set* parameter to a pydicom Dataset
    ds = event.dataset

    # Add the File Meta Information
    ds.file_meta = event.file_meta

    # Save the dataset using the SOP Instance UID as the filename
    ds.save_as(ds.SOPInstanceUID, write_like_original=False)

    # Return a 'Success' status
    return 0x0000

handlers = [(evt.EVT_C_STORE, handle_store)]

# Initialise the Application Entity
ae = AE(ae_title=b'TEST')

# Support presentation contexts for all storage SOP Classes
ae.supported_contexts = AllStoragePresentationContexts

# Start listening for incoming association requests
ae.start_server(('', 11112), evt_handlers=handlers)

Running this in this conda env in macOS:

# Name                    Version                   Build  Channel
bzip2                     1.0.8                h620ffc9_4  
ca-certificates           2022.12.7            h4653dfc_0    conda-forge
certifi                   2022.12.7          pyhd8ed1ab_0    conda-forge
libffi                    3.4.2                hca03da5_6  
ncurses                   6.3                  h1a28f6b_3  
openssl                   1.1.1s               h03a7124_1    conda-forge
pip                       22.3.1          py310hca03da5_0  
pydicom                   2.3.1              pyh1a96a4e_0    conda-forge
pynetdicom                2.0.2              pyhd8ed1ab_0    conda-forge
python                    3.10.8               hc0d8a6c_1  
readline                  8.2                  h1a28f6b_0  
setuptools                65.5.0          py310hca03da5_0  
sqlite                    3.40.0               h7a7dc30_0  
tk                        8.6.12               hb8d0fd4_0  
tzdata                    2022g                h04d1e81_0  
wheel                     0.37.1             pyhd3eb1b0_0  
xz                        5.2.8                h80987f9_0  
zlib                      1.2.13               h5a0b063_0 

Read more comments on GitHub >

github_iconTop Results From Across the Web

'ascii' codec can't decode byte 0xe2 in position 13: ordinal not ...
The file is being read as a bunch of str s, but it should be unicode s. Python tries to implicitly convert, but...
Read more >
'ascii' codec can't decode byte 0xe2 in position 5599 ... - GitHub
UnicodeDecodeError : 'ascii' codec can't decode byte 0xe2 in position 5599: ordinal not in range(128) #87.
Read more >
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in ...
Scanning host fails with error using VUM : Cannot run upgrade script on host | UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in ......
Read more >
'ascii' codec can't decode byte 0xe4 in position 11: ordinal not ...
Turns out the root cause of this issue is that the new pyparted build's python modules return unicode objects instead of (byte) strings...
Read more >
3924 (Caught an exception while rendering: 'ascii' codec can't ...
UnicodeDecodeError at /admin/articulos/articulo/add/ 'ascii' codec can't decode byte 0xc3 in position 8: ordinal not in range(128) Request Method: GET ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found