Repository navigation
fix: decode text in sequence items with the dataset's SpecificCharacterSet - #520
namespaceMarcello wants to merge 5 commits into
Conversation
…erSet
ReadBufferStream starts with TextDecoder("latin1"), and more() creates a new
ReadBufferStream for every sequence item without passing the parent's decoder.
Text inside sequences (SR ContentSequence, SEG segment labels, RTSTRUCT ROI
names) was therefore decoded as windows-1252, which is what "latin1" means for
TextDecoder, even when SpecificCharacterSet is ISO_IR 192. Writing the dataset
back made the damage permanent.
more() now passes its decoder to the new stream. ParsedUnknownValue had the
same problem for UN elements re-read with their dictionary VR, and now passes
the decoder too.
Fixes dcmjs-org#503
Fixes dcmjs-org#508
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWHfLbjyVsKtycUjne5QSs
✅ Deploy Preview for dcmjs2 ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
| it("decodes text in sequence items at every depth", () => { | ||
| const dataset = writeAndRead( | ||
| DicomMetaDictionary.denaturalizeDataset({ | ||
| SpecificCharacterSet: "ISO_IR 192", |
There was a problem hiding this comment.
DICOM allows the specific character set tag to be encoded in a sequence item, which dictates the decoding for that sequence item and datasets under it (overriding the root dataset specific character set). I would suggest creating an additional test for this specific case just to ensure you have the decoding right.
There was a problem hiding this comment.
Yes, I've avoided the Specific Character Set implementations because it's complex, somewhat rare in practice, and highly variable in terms of implementation correctness (i.e. I understand there are at least some incorrect implementations in the wild).
So anything we do here should be accompanied by tests with either real data or synthetically generated data that mirrors real-world uses of this feature.
There was a problem hiding this comment.
I will note we had a problem testing dcmjs trying to process ISO_IR 192 results from a modality worklist server where all of the names were in sequence attributes and they were parsed wrong (and hence my interest and reason for the comment). In any case, at least testing to make sure the "correct" dicom encoding scenarios work would be a good first step.
There was a problem hiding this comment.
@namespaceMarcello can you comment on the nested character set issue @stevewranovsky raised?
There was a problem hiding this comment.
Hi @pieper , I can't check this right now. As this PR has been open for three weeks and feedback was provided only three days ago, I need a little time to catch up on the details and review the issue raised by @stevewranovsky . I will update you soon.
There was a problem hiding this comment.
Thanks @stevewranovsky for raising this, and @pieper for keeping it moving.
The standard says what you describe (PS3.5 7.5.3): a Specific Character Set in an item applies only to that item, and an item without one uses the character set of the data set that contains it. With this PR DicomMessage.readFile follows it. Each item is read from its own sub-stream, which starts with the parent's decoder, and an item's own (0008,0005) switches only that sub-stream, so it reaches the items nested in it and nothing else.
c00d644 adds the test you suggested, shaped like a worklist since that is where you hit it. It is an ISO_IR 192 data set whose first ScheduledProcedureStepSequence item declares ISO_IR 144, with that item's text written as ISO 8859-5 bytes. It checks five values in one comparison: the patient name before the sequence, the first item's physician name and the CodeMeaning in its nested code sequence (Cyrillic), then the second item's physician name and an element after the sequence (UTF-8). Without the fix in this PR, the nested item comes back as ÀÕÝâÓÕÝ instead of Рентген.
On real data, @pieper: the public files I know of with a character set inside an item, pydicom's chrSQEncoding.dcm and chrSQEncoding1.dcm, declare two ISO 2022 Japanese character sets, which dcmjs rejects as multiple character sets. So the test builds its data. If you have a real file with this shape, I can add it.
@stevewranovsky, on your worklist: if those items inherited ISO_IR 192 from the top level, this PR fixes that case. Master reads every item as windows-1252.
The same test, run on AsyncDicomReader, found a bug that predates this PR. That reader reads items on the parent's stream, so a character set declared in an item stays on after the item ends. The next item and the rest of the data set are decoded with it (Dupré^Anaïs comes back as DuprУЉ^AnaУЏs). It's fixed separately in #609, so this PR stays about the sync reader. That also corrects what the description here said: the two readers agreed only on inherited character sets. I've updated the description.
I also merged master in. It brings the Node 24 test fix (readFileAsArrayBuffer in test/testUtils.js), which should clear the test (24) failure here. The new runs are waiting for approval.
Written by Claude Code (AI assistant) on behalf of @namespaceMarcello, who directs this work.
There was a problem hiding this comment.
Thanks @namespaceMarcello - these are looking good. Let's see what @stevewranovsky has to say.
While we are on it, what do you think about Code Extensions? I shied away in the past because I never run into it and it seems a bit complex, but maybe we should handle it now that we can have Claude handle the details.
There was a problem hiding this comment.
Thanks @pieper. Yes, I think Code Extensions are worth doing, in a separate PR so this one stays about sequence items.
Today a multi-valued (0008,0005) such as \ISO 2022 IR 149 makes DicomMessage.readFile throw "Using multiple character sets is not supported". With ignoreErrors, or in AsyncDicomReader, everything is decoded with the first value, so the text after an escape sequence comes out garbled. That is #373.
What I would do:
- on read, split each text value (SH, LO, ST, LT, UC, UT, PN) at the ISO 2022 escape sequences and decode each run with the character set its escape selects, going back to the first value where PS3.5 6.1.2.5 requires it (at
\, and at^and=in PN); - keep the output as it is now: UTF-8 strings, with (0008,0005) rewritten to
ISO_IR 192, so only reading changes; - do it in both
DicomMessageandAsyncDicomReader.
There is real data to test against: the files attached to #373, and the Japanese and Korean examples from PS3.5 Annexes H and I, which pydicom ships as test files (chrH31, chrH32, chrI2, chrJapMulti, chrKoreanMulti).
If that direction works for you, I'll write the plan on #373 and open the PR from there.
Written by Claude Code (AI assistant) on behalf of @namespaceMarcello, who directs this work.
There was a problem hiding this comment.
Yes, having a tested implementation will be great.
There was a problem hiding this comment.
Tests look good to me, thanks for doing the effort to fix this.
Also thanks for investigating the code extensions under #373, this is another one I would have eventually asked about fixing too.
PS3.5 7.5.3: a Specific Character Set in an item applies only to that item and the items nested in it. The new test reads a worklist-shaped data set in ISO_IR 192 whose first scheduled step declares ISO_IR 144, with that item's text in ISO 8859-5 bytes, and checks the five values that tell the cases apart: the item itself and its nested item in Cyrillic, the next item and the element after the sequence still in UTF-8. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sub-stream and worklist tests now read their data four ways: in Explicit and Implicit VR Little Endian, each with the undefined lengths dcmjs writes and with every sequence and item rewritten to a defined length. Both kinds of item reach the same more() call in SequenceOfItems.readBytes. Without the decoder in more() all eight cases fail; reading defined-length items two bytes short fails only the four defined-length cases. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I pushed 08eb339, which only touches the tests. The depth and worklist tests now read their data in Explicit and Implicit VR, each with the undefined lengths dcmjs writes and with every sequence and item rewritten to a defined length, so both kinds of item that reach Written by Claude Code (AI assistant) on behalf of @namespaceMarcello, who directs this work. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…x nested charsets together Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes #503
Fixes #508
Summary
With
SpecificCharacterSet=ISO_IR 192, text at the top level of a dataset reads back correctly, but text inside a sequence item does not."lesione – café 肝"comes back as"lesione â café è". This hits Structured Reports (ContentSequence), SEG segment labels and RTSTRUCT ROI names. Writing the dataset back makes the damage permanent.@hromsdahl (#503) and @rkikinis (#508) both traced this, and @pieper agreed on #503 that it should be fixed. This PR follows the approach suggested in #503: the sub-stream gets the parent stream's decoder. To answer the question in #508: the character set is threaded down through sequence parsing, not resolved per item at naturalize time.
Cause
ReadBufferStreamstarts withnew TextDecoder("latin1").DicomMessage._readswitches the decoder when it readsSpecificCharacterSet, but only on the stream it is reading.SequenceOfItemsreads every item from a new stream made byBufferStream.more(), and that stream started again with the default decoder.In the WHATWG Encoding standard,
"latin1"is a label for windows-1252. That is why #508 sees cp1252 characters (€,“) and #503 sees Latin-1. It is the same bug.Changes
ReadBufferStreamaccepts adecoderoption and falls back tolatin1as before.BufferStream.more()passes its decoder to the new stream. Items nested at any depth inherit it.ParsedUnknownValue.read()had the same problem: aUNelement whose tag has a known VR is re-read from a new stream, so aUN-encodedLOcame back as mojibake too. It now passes the decoder as well._readstill callssetDecoderon the stream it is reading. An item that declares its ownSpecificCharacterSetchanges the decoder for that item and the items inside it, not for its parent or the items after it, as PS3.5 7.5.3 requires. A test covers this now (see below).AsyncDicomReaderreads items in place on the same stream, so it already decoded inherited character sets correctly, and with this change the sync reader gives the same result for them. For a character set declared inside an item the two readers differ:AsyncDicomReaderkeeps it on after the item ends. That bug predates this PR and is fixed separately in #609.Verified
test/data-encoding.test.js, all underISO_IR 192:UN-encodedLO. Onmasterboth tests fail on the value (Received: "lesione â café è"). With the fix they pass.ScheduledProcedureStepSequenceitem declaresISO_IR 144, with that item's text written as ISO 8859-5 bytes (added in review). One comparison checks the patient name before the sequence, the first item's physician name and its nestedCodeMeaning(Cyrillic), the second item's physician name and an element after the sequence (UTF-8). Without the fix the nested value comes back asÀÕÝâÓÕÝinstead ofРентген. If an item could not switch its own decoder, the first item's name would come back as replacement characters. The second-item and after-sequence checks fail onAsyncDicomReaderbefore fix: decode text in sequence items with the right SpecificCharacterSet (sync and async readers) #609.more()call inSequenceOfItems.readBytes.more()fails the depth and worklist tests in all four encodings, and not theUNtest. Not passing it forUNfails only theUNtest. Reading defined-length items two bytes short fails only the four defined-length cases, so the rewritten data does take that path.pnpm run build):0.52.0from npm gives mojibake at depth 1, depth 2 and forUN. This branch gives the original text everywhere, the same asAsyncDicomReader.pnpm run build, eslint andprettier --checkonsrc/andtest/.Written by Claude Code (AI assistant) on behalf of @namespaceMarcello, who directs this work.
🤖 Generated with Claude Code