-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathfile.py
More file actions
3340 lines (2977 loc) · 117 KB
/
file.py
File metadata and controls
3340 lines (2977 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Client to access DICOM Part10 files through a layer of abstraction."""
import collections
import io
import logging
import math
import os
import re
import sqlite3
import sys
import time
import traceback
from collections import OrderedDict
from enum import Enum
from pathlib import Path
from typing import (
Any,
Dict,
Iterator,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Union,
)
import numpy as np
from PIL import Image
from PIL.ImageCms import ImageCmsProfile, createProfile
from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.encaps import encapsulate, get_frame_offsets
from pydicom.errors import InvalidDicomError
from pydicom.filebase import DicomFileLike
from pydicom.datadict import dictionary_VR, keyword_for_tag, tag_for_keyword
from pydicom.filereader import (
data_element_offset_to_value,
dcmread,
read_file_meta_info,
read_partial,
)
from pydicom.filewriter import dcmwrite
from pydicom.pixel_data_handlers.numpy_handler import unpack_bits
from pydicom.tag import (
BaseTag,
ItemTag,
SequenceDelimiterTag,
Tag,
TupleTag,
)
from pydicom.uid import UID
from pydicom.valuerep import DA, DT, TM
logger = logging.getLogger(__name__)
_FLOAT_PIXEL_DATA_TAGS = {0x7FE00008, 0x7FE00009, }
_UINT_PIXEL_DATA_TAGS = {0x7FE00010, }
_PIXEL_DATA_TAGS = _FLOAT_PIXEL_DATA_TAGS.union(_UINT_PIXEL_DATA_TAGS)
_JPEG_SOI_MARKER = b'\xFF\xD8' # also JPEG-LS
_JPEG_EOI_MARKER = b'\xFF\xD9' # also JPEG-LS
_JPEG2000_SOC_MARKER = b'\xFF\x4F'
_JPEG2000_EOC_MARKER = b'\xFF\xD9'
_START_MARKERS = {_JPEG_SOI_MARKER, _JPEG2000_SOC_MARKER}
_END_MARKERS = {_JPEG_EOI_MARKER, _JPEG2000_EOC_MARKER}
def _get_bot(fp: DicomFileLike, number_of_frames: int) -> List[int]:
"""Read or build the Basic Offset Table (BOT).
Parameters
----------
fp: pydicom.filebase.DicomFileLike
Pointer for DICOM PS3.10 file stream positioned at the first byte of
the Pixel Data element
number_of_frames: int
Number of frames contained in the Pixel Data element
Returns
-------
List[int]
Offset of each Frame item in bytes from the first byte of the Pixel
Data element following the BOT item
Note
----
Moves the pointer to the first byte of the open file following the BOT item
(the first byte of the first Frame item).
"""
logger.debug('read Basic Offset Table')
basic_offset_table = _read_bot(fp)
first_frame_offset = fp.tell()
tag = TupleTag(fp.read_tag())
if int(tag) != ItemTag:
raise ValueError('Reading of Basic Offset Table failed')
fp.seek(first_frame_offset, 0)
# Basic Offset Table item must be present, but it may be empty
if len(basic_offset_table) == 0:
logger.debug('Basic Offset Table item is empty')
if len(basic_offset_table) != number_of_frames:
logger.debug('build Basic Offset Table item')
basic_offset_table = _build_bot(
fp,
number_of_frames=number_of_frames
)
return basic_offset_table
def _read_bot(fp: DicomFileLike) -> List[int]:
"""Read the Basic Offset Table (BOT) of an encapsulated Pixel Data element.
Parameters
----------
fp: pydicom.filebase.DicomFileLike
Pointer for DICOM PS3.10 file stream positioned at the first byte of
the Pixel Data element
Returns
-------
List[int]
Offset of each Frame item in bytes from the first byte of the Pixel
Data element following the BOT item
Note
----
Moves the pointer to the first byte of the open file following the BOT item
(the first byte of the first Frame item).
Raises
------
IOError
When file pointer is not positioned at first byte of Pixel Data element
"""
tag = TupleTag(fp.read_tag())
if int(tag) not in _PIXEL_DATA_TAGS:
raise IOError(
'Expected file pointer at first byte of Pixel Data element.'
)
# Skip Pixel Data element header (tag, VR, length)
pixel_data_element_value_offset = data_element_offset_to_value(
fp.is_implicit_VR, 'OB'
)
fp.seek(pixel_data_element_value_offset - 4, 1)
is_empty, offsets = get_frame_offsets(fp)
return offsets
def _build_bot(fp: DicomFileLike, number_of_frames: int) -> List[int]:
"""Build a Basic Offset Table (BOT) for an encapsulated Pixel Data element.
Parameters
----------
fp: pydicom.filebase.DicomFileLike
Pointer for DICOM PS3.10 file stream positioned at the first byte of
the Pixel Data element following the empty Basic Offset Table (BOT)
number_of_frames: int
Total number of frames in the dataset
Returns
-------
List[int]
Offset of each Frame item in bytes from the first byte of the Pixel
Data element following the BOT item
Note
----
Moves the pointer back to the first byte of the Pixel Data element
following the BOT item (the first byte of the first Frame item).
Raises
------
IOError
When file pointer is not positioned at first byte of first Frame item
after Basic Offset Table item or when parsing of Frame item headers
fails
ValueError
When the number of offsets doesn't match the specified number of frames
"""
initial_position = fp.tell()
offset_values = []
current_offset = 0
i = 0
while True:
frame_position = fp.tell()
tag = TupleTag(fp.read_tag())
if int(tag) == SequenceDelimiterTag:
break
if int(tag) != ItemTag:
fp.seek(initial_position, 0)
raise IOError(
'Building Basic Offset Table (BOT) failed. Expected tag of '
f'Frame item #{i} at position {frame_position}.'
)
length = fp.read_UL()
if length % 2:
fp.seek(initial_position, 0)
raise IOError(
'Building Basic Offset Table (BOT) failed. '
f'Length of Frame item #{i} is not a multiple of 2.'
)
elif length == 0:
fp.seek(initial_position, 0)
raise IOError(
'Building Basic Offset Table (BOT) failed. '
f'Length of Frame item #{i} is zero.'
)
first_two_bytes = fp.read(2)
if not fp.is_little_endian:
first_two_bytes = first_two_bytes[::-1]
# In case of fragmentation, we only want to get the offsets to the
# first fragment of a given frame. We can identify those based on the
# JPEG and JPEG 2000 markers that should be found at the beginning and
# end of the compressed byte stream.
if first_two_bytes in _START_MARKERS:
current_offset = frame_position - initial_position
offset_values.append(current_offset)
i += 1
fp.seek(length - 2, 1) # minus the first two bytes
if len(offset_values) != number_of_frames:
raise ValueError(
'Number of frame items does not match specified Number of Frames.'
)
else:
basic_offset_table = offset_values
fp.seek(initial_position, 0)
return basic_offset_table
class _ImageFileReader:
"""Class for reading DICOM files that represent Image Information Entities.
The class provides methods for efficient access to individual Frame items
contained in the Pixel Data element of a Data Set stored in a Part10 file
on disk without loading the entire element into memory.
"""
def __init__(self, fp: Union[str, Path, DicomFileLike]):
"""
Parameters
----------
fp: Union[str, pathlib.Path, pydicom.filebase.DicomfileLike]
DICOM Part10 file containing a dataset of an image SOP Instance
"""
self._filepointer: Union[DicomFileLike, None]
self._filepath: Union[Path, None]
if isinstance(fp, DicomFileLike):
is_little_endian, is_implicit_VR = self._check_file_format(fp)
try:
if fp.is_little_endian != is_little_endian:
raise ValueError(
'Transfer syntax of file object has incorrect value '
'for attribute "is_little_endian".'
)
except AttributeError:
raise AttributeError(
'Transfer syntax of file object does not have '
'attribute "is_little_endian".'
)
try:
if fp.is_implicit_VR != is_implicit_VR:
raise ValueError(
'Transfer syntax of file object has incorrect value '
'for attribute "is_implicit_VR".'
)
except AttributeError:
raise AttributeError(
'Transfer syntax of file object does not have '
'attribute "is_implicit_VR".'
)
self._filepointer = fp
self._filepath = None
elif isinstance(fp, (str, Path)):
self._filepath = Path(fp)
self._filepointer = None
else:
raise TypeError(
'Argument "filename" must either an open DICOM file object or '
'the path to a DICOM file stored on disk.'
)
# Those attributes will be set by the "open()"
self._metadata: Dataset = Dataset()
self._is_open = False
self._as_float = False
self._bytes_per_frame_uncompressed: int = -1
self._basic_offset_table: List[int] = []
self._first_frame_offset: int = -1
self._pixel_data_offset: int = -1
self._pixels_per_frame: int = -1
def _check_file_format(self, fp: DicomFileLike) -> Tuple[bool, bool]:
"""Check whether file object represents a DICOM Part 10 file.
Parameters
----------
fp: pydicom.filebase.DicomFileLike
DICOM file object
Returns
-------
is_little_endian: bool
Whether the data set is encoded in little endian transfer syntax
is_implicit_VR: bool
Whether value representations of data elements in the data set
are implicit
Raises
------
InvalidDicomError
If the file object does not represent a DICOM Part 10 file
"""
def is_main_tag(tag: BaseTag, VR: Optional[str], length: int) -> bool:
return tag >= 0x00040000
pos = fp.tell()
ds = read_partial(fp, stop_when=is_main_tag) # type: ignore
fp.seek(pos)
transfer_syntax_uid = UID(ds.file_meta.TransferSyntaxUID)
return (
transfer_syntax_uid.is_little_endian,
transfer_syntax_uid.is_implicit_VR,
)
def __enter__(self) -> '_ImageFileReader':
self.open()
return self
def __exit__(self, except_type, except_value, except_trace) -> None:
self._fp.close()
if except_value:
sys.stdout.write(
'Error while accessing file "{}":\n{}'.format(
self._filepath, str(except_value)
)
)
for tb in traceback.format_tb(except_trace):
sys.stdout.write(tb)
raise
@property
def _fp(self) -> DicomFileLike:
if self._filepointer is None:
raise IOError('File has not been opened for reading.')
return self._filepointer
def open(self) -> None:
"""Open file for reading.
Raises
------
FileNotFoundError
When file cannot be found
OSError
When file cannot be opened
IOError
When DICOM metadata cannot be read from file
ValueError
When DICOM dataset contained in file does not represent an image
Note
----
Reads the metadata of the DICOM Data Set contained in the file and
builds a Basic Offset Table to speed up subsequent frame-level access.
"""
# This methods sets several attributes on the object, which cannot
# (or should not) be set in the constructor. Other methods assert that
# this method has been called first by checking the value of the
# "_is_open" attribute.
if self._is_open:
return
if self._filepointer is None:
# This should not happen is just for mypy to be happy
if self._filepath is None:
raise ValueError(f'File not found: "{self._filepath}".')
logger.debug('read File Meta Information')
try:
file_meta = read_file_meta_info(self._filepath)
except FileNotFoundError:
raise ValueError('No file path was set.')
except InvalidDicomError:
raise InvalidDicomError(
f'File is not a valid DICOM file: "{self._filepath}".'
)
except Exception:
raise IOError(f'Could not read file: "{self._filepath}".')
transfer_syntax_uid = UID(file_meta.TransferSyntaxUID)
if transfer_syntax_uid is None:
raise IOError(
'File is not a valid DICOM file: "{self._filepath}".'
'It lacks File Meta Information.'
)
self._transfer_syntax_uid: UID = transfer_syntax_uid
is_little_endian = transfer_syntax_uid.is_little_endian
is_implicit_VR = transfer_syntax_uid.is_implicit_VR
self._filepointer = DicomFileLike(open(self._filepath, 'rb'))
self._filepointer.is_little_endian = is_little_endian
self._filepointer.is_implicit_VR = is_implicit_VR
logger.debug('read metadata elements')
try:
tmp = dcmread(self._fp, stop_before_pixels=True)
except Exception as error:
raise IOError(
f'DICOM metadata cannot be read from file: "{error}"'
)
# Construct a new Dataset that is fully decoupled from the file,
# i.e., that does not contain any File Meta Information
del tmp.file_meta
self._metadata = Dataset(tmp)
self._pixels_per_frame = int(np.product([
self._metadata.Rows,
self._metadata.Columns,
self._metadata.SamplesPerPixel
]))
self._pixel_data_offset = self._fp.tell()
# Determine whether dataset contains a Pixel Data element
try:
tag = TupleTag(self._fp.read_tag())
except EOFError:
raise ValueError(
'Dataset does not represent an image information entity.'
)
if int(tag) not in _PIXEL_DATA_TAGS:
raise ValueError(
'Dataset does not represent an image information entity.'
)
self._as_float = False
if int(tag) in _FLOAT_PIXEL_DATA_TAGS:
self._as_float = True
# Reset the file pointer to the beginning of the Pixel Data element
self._fp.seek(self._pixel_data_offset, 0)
logger.debug('build Basic Offset Table')
try:
number_of_frames = int(self._metadata.NumberOfFrames)
except AttributeError:
number_of_frames = 1
if self._transfer_syntax_uid.is_encapsulated:
try:
self._basic_offset_table = _get_bot(
self._fp,
number_of_frames=number_of_frames
)
except Exception as error:
raise IOError(
f'Failed to build Basic Offset Table: "{error}"'
)
self._first_frame_offset = self._fp.tell()
else:
if self._fp.is_implicit_VR:
header_offset = 4 + 4 # tag and length
else:
header_offset = 4 + 2 + 2 + 4 # tag, VR, reserved, and length
self._first_frame_offset = self._pixel_data_offset + header_offset
n_pixels = self._pixels_per_frame
bits_allocated = self._metadata.BitsAllocated
if bits_allocated == 1:
# Determine the nearest whole number of bytes needed to contain
# 1-bit pixel data. e.g. 10 x 10 1-bit pixels is 100 bits,
# which are packed into 12.5 -> 13 bytes
self._bytes_per_frame_uncompressed = (
n_pixels // 8 + (n_pixels % 8 > 0)
)
self._basic_offset_table = [
int(math.floor(i * n_pixels / 8))
for i in range(number_of_frames)
]
else:
self._bytes_per_frame_uncompressed = (
n_pixels * bits_allocated // 8
)
self._basic_offset_table = [
i * self._bytes_per_frame_uncompressed
for i in range(number_of_frames)
]
if len(self._basic_offset_table) != number_of_frames:
raise ValueError(
'Length of Basic Offset Table does not match '
'Number of Frames.'
)
self._is_open = True
def _assert_is_open(self) -> None:
if not self._is_open:
raise IOError('DICOM image file has not been opened for reading.')
@property
def transfer_syntax_uid(self) -> UID:
"""pydicom.uid.UID: Transfer Syntax UID"""
self._assert_is_open()
return self._transfer_syntax_uid
@property
def metadata(self) -> Dataset:
"""pydicom.dataset.Dataset: Metadata"""
self._assert_is_open()
return self._metadata
def close(self) -> None:
"""Close file."""
if self._fp is not None:
self._fp.close()
self._is_open = False
def read_frame(self, index: int) -> bytes:
"""Read the pixel data of an individual frame item.
Parameters
----------
index: int
Zero-based frame index
Returns
-------
bytes
Pixel data of a given frame item encoded in the transfer syntax.
Raises
------
IOError
When frame could not be read
"""
self._assert_is_open()
if index > self.number_of_frames:
raise ValueError(
f'Frame index {index} exceeds number of frames in image: '
f'{self.number_of_frames}.'
)
logger.debug(f'read frame #{index}')
frame_offset = self._basic_offset_table[index]
self._fp.seek(self._first_frame_offset + frame_offset, 0)
if self._transfer_syntax_uid.is_encapsulated:
try:
stop_at = self._basic_offset_table[index + 1] - frame_offset
except IndexError:
# For the last frame, there is no next offset available.
stop_at = -1
n = 0
# A frame may consist of multiple items (fragments).
fragments = []
while True:
tag = TupleTag(self._fp.read_tag())
if n == stop_at or int(tag) == SequenceDelimiterTag:
break
if int(tag) != ItemTag:
raise ValueError(f'Failed to read frame #{index}.')
length = self._fp.read_UL()
fragments.append(self._fp.read(length))
n += 4 + 4 + length
frame_data = b''.join(fragments)
else:
frame_data = self._fp.read(self._bytes_per_frame_uncompressed)
if len(frame_data) == 0:
raise IOError(f'Failed to read frame #{index}.')
return frame_data
def decode_frame(self, index: int, value: bytes):
"""Decode the pixel data of an individual frame item.
Parameters
----------
index: int
Zero-based frame index
value: bytes
Value of a Frame item
Returns
-------
numpy.ndarray
Array of decoded pixels of the frame with shape (Rows x Columns)
in case of a monochrome image or (Rows x Columns x SamplesPerPixel)
in case of a color image.
"""
self._assert_is_open()
logger.debug(f'decode frame #{index}')
metadata = self.metadata
if metadata.BitsAllocated == 1:
unpacked_frame = unpack_bits(value)
rows, columns = metadata.Rows, self.metadata.Columns
n_pixels = self._pixels_per_frame
pixel_offset = int(((index * n_pixels / 8) % 1) * 8)
pixel_array = unpacked_frame[pixel_offset:pixel_offset + n_pixels]
return pixel_array.reshape(rows, columns) # type: ignore
else:
# This hack creates a small dataset containing a Pixel Data element
# with only a single frame item, which can then be decoded using the
# existing pydicom API.
ds = Dataset()
ds.file_meta = FileMetaDataset()
ds.file_meta.TransferSyntaxUID = self._transfer_syntax_uid
ds.Rows = metadata.Rows
ds.Columns = metadata.Columns
ds.SamplesPerPixel = metadata.SamplesPerPixel
ds.PhotometricInterpretation = metadata.PhotometricInterpretation
ds.PixelRepresentation = metadata.PixelRepresentation
ds.PlanarConfiguration = metadata.get('PlanarConfiguration', None)
ds.BitsAllocated = metadata.BitsAllocated
ds.BitsStored = metadata.BitsStored
ds.HighBit = metadata.HighBit
if self._transfer_syntax_uid.is_encapsulated:
ds.PixelData = encapsulate(frames=[value])
else:
ds.PixelData = value
return ds.pixel_array
def read_and_decode_frame(self, index: int):
"""Read and decode the pixel data of an individual frame item.
Parameters
----------
index: int
Zero-based frame index
Returns
-------
numpy.ndarray
Array of decoded pixels of the frame with shape (Rows x Columns)
in case of a monochrome image or (Rows x Columns x SamplesPerPixel)
in case of a color image.
Raises
------
IOError
When frame could not be read
"""
frame = self.read_frame(index)
return self.decode_frame(index, frame)
@property
def number_of_frames(self) -> int:
"""int: Number of frames"""
self._assert_is_open()
try:
return int(self.metadata.NumberOfFrames)
except AttributeError:
return 1
class _QueryResourceType(Enum):
"""DICOMweb Query resource types."""
STUDIES = 'studies'
SERIES = 'series'
INSTANCES = 'instances'
def _build_acceptable_media_type_lut(
media_types: Tuple[Union[str, Tuple[str, str]], ...],
supported_media_type_lut: Mapping[str, Iterable[str]]
) -> Mapping[str, Iterable[str]]:
# If no acceptable transfer syntax has been specified, then we just return
# the instance in whatever transfer syntax is has been stored. This
# behavior should be compliant with the standard (Part 18 Section 8.7.3.4):
# If the Transfer Syntax is not specified in a message, then the Default
# Transfer Syntax shall be used, unless the origin server has only access
# to the pixel data in lossy compressed form or the pixel data in a
# lossless compressed form that is of such length that it cannot be encoded
# in the Explicit VR Little Endian Transfer Syntax.
acceptable_media_type_lut = collections.defaultdict(set)
for m in media_types:
if isinstance(m, tuple):
media_type = str(m[0])
if media_type not in supported_media_type_lut:
raise ValueError(
f'Media type "{media_type}" is not a valid for '
'retrieval of instance frames.'
)
if len(m) > 1:
ts_uid = str(m[1])
if ts_uid not in supported_media_type_lut[media_type]:
raise ValueError(
f'Transfer syntax "{ts_uid}" is not a valid for '
'retrieval of instance frames with media type '
f'"{media_type}".'
)
acceptable_media_type_lut[media_type].add(ts_uid)
else:
acceptable_media_type_lut[media_type].update(
supported_media_type_lut[media_type]
)
elif isinstance(m, str):
media_type = str(m)
if media_type not in supported_media_type_lut:
raise ValueError(
f'Media type "{media_type}" is not a valid for '
'retrieval of instance frames.'
)
acceptable_media_type_lut[media_type].update(
supported_media_type_lut[media_type]
)
else:
raise ValueError('Argument "media_types" is malformatted.')
return acceptable_media_type_lut
class DICOMfileClient:
"""Client for managing DICOM Part10 files in a DICOMweb-like manner.
Facilitates serverless access to data stored locally on a file system as
DICOM Part10 files.
Note
----
The class exposes the same :class:`dicomweb_client.api.DICOMClient`
interface as the :class:`dicomweb_client.api.DICOMwebClient` class.
While method parameters and return values have the same types, but the
types of exceptions may differ.
Note
----
The class internally uses an in-memory database, which is persisted on disk
to facilitate faster subsequent data access. However, the implementation
details of the database and the structure of any database files stored on
the file system may change at any time and should not be relied on.
Note
----
This is **not** an implementation of the DICOM File Service and does not
depend on the presence of ``DICOMDIR`` files.
"""
def __init__(
self,
base_dir: Union[Path, str],
update_db: bool = False,
recreate_db: bool = False,
in_memory: bool = False
):
"""Instantiate client.
Parameters
----------
base_dir: Union[pathlib.Path, str]
Path to base directory containing DICOM files
update_db: bool, optional
Whether the database should be updated (default: ``False``). If
``True``, the client will search `base_dir` recursively for new
DICOM Part10 files and create database entries for each file.
The client will further delete any database entries for files that
no longer exist on the file system.
recreate_db: bool, optional
Whether the database should be recreated (default: ``False``). If
``True``, the client will search `base_dir` recursively for DICOM
Part10 files and create database entries for each file.
in_memory: bool, optional
Whether the database should only be stored in memory (default:
``False``).
"""
self.base_dir = Path(base_dir).resolve()
if in_memory:
filename = ':memory:'
else:
filename = '.dicom-file-client.db'
self._db_filepath = self.base_dir.joinpath(filename)
if not self._db_filepath.exists():
update_db = True
self._db_connection_handle: Union[sqlite3.Connection, None] = None
self._db_cursor_handle: Union[sqlite3.Cursor, None] = None
if recreate_db:
self._drop_db()
update_db = True
self._create_db()
self._attributes = {
_QueryResourceType.STUDIES: self._get_attributes(
_QueryResourceType.STUDIES
),
_QueryResourceType.SERIES: self._get_attributes(
_QueryResourceType.SERIES
),
_QueryResourceType.INSTANCES: self._get_attributes(
_QueryResourceType.INSTANCES
),
}
if update_db:
logger.info('updating database...')
start = time.time()
self._update_db()
end = time.time()
elapsed = round(end - start)
logger.info(f'updated database in {elapsed} seconds')
self._reader_cache: OrderedDict[Path, _ImageFileReader] = OrderedDict()
self._max_reader_cache_size = 50
def __getstate__(self) -> dict:
"""Customize state for serialization via pickle module.
Returns
-------
dict
Contents of the instance that should be serialized
"""
contents = self.__dict__
# The database connection and the cached image file readers should
# (and cannot) be serialized. Therefore, we reset the state of the
# instance before serialization.
# This is critical for applications that rely on Python multiprocessing
# such as PyTorch or TensorFlow.
try:
if self._db_cursor_handle is not None:
self._db_cursor_handle.execute('PRAGMA optimize')
self._db_cursor_handle.close()
if self._db_connection_handle is not None:
self._db_connection_handle.commit()
self._db_connection_handle.close()
for image_file_reader in self._reader_cache.values():
image_file_reader.close()
finally:
contents['_db_connection_handle'] = None
contents['_db_cursor_handle'] = None
contents['_reader_cache'] = OrderedDict()
return contents
@property
def _connection(self) -> sqlite3.Connection:
"""sqlite3.Connection: database connection"""
if self._db_connection_handle is None:
self._db_connection_handle = sqlite3.connect(str(self._db_filepath))
self._db_connection_handle.row_factory = sqlite3.Row
return self._db_connection_handle
@property
def _cursor(self) -> sqlite3.Cursor:
if self._db_cursor_handle is None:
self._db_cursor_handle = self._connection.cursor()
return self._db_cursor_handle
def _create_db(self):
"""Creating database tables and indices."""
with self._connection as connection:
cursor = connection.cursor()
cursor.execute('PRAGMA journal_mode = WAL')
cursor.execute('PRAGMA synchronous = off')
cursor.execute('PRAGMA temp_store = memory')
cursor.execute('PRAGMA mmap_size = 30000000000')
cursor.execute('''
CREATE TABLE IF NOT EXISTS studies (
StudyInstanceUID TEXT NOT NULL,
StudyID TEXT,
StudyDate TEXT,
StudyTime TEXT,
PatientName TEXT,
PatientID TEXT,
PatientSex TEXT,
PatientBirthDate TEXT,
ReferringPhysicianName TEXT,
PRIMARY KEY (StudyInstanceUID)
)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS study_index_patient_id
ON studies (PatientID)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS study_index_study_id
ON studies (StudyID)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS series (
StudyInstanceUID TEXT NOT NULL,
SeriesInstanceUID TEXT NOT NULL,
Modality VARCHAR(2),
AccessionNumber TEXT,
SeriesNumber INTEGER,
PRIMARY KEY (StudyInstanceUID, SeriesInstanceUID)
FOREIGN KEY (StudyInstanceUID)
REFERENCES studies(StudyInstanceUID)
)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS series_index_modality
ON series (
Modality
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS instances (
StudyInstanceUID TEXT NOT NULL,
SeriesInstanceUID TEXT NOT NULL,
SOPInstanceUID TEXT NOT NULL,
SOPClassUID TEXT NOT NULL,
InstanceNumber INTEGER,
Rows INTEGER,
Columns INTEGER,
BitsAllocated INTEGER,
NumberOfFrames INTEGER,
TransferSyntaxUID TEXT NOT NULL,
_file_path TEXT,
PRIMARY KEY (
StudyInstanceUID,
SeriesInstanceUID,
SOPInstanceUID
)
FOREIGN KEY (SeriesInstanceUID)
REFERENCES series(SeriesInstanceUID)
FOREIGN KEY (StudyInstanceUID)
REFERENCES studies(StudyInstanceUID)
)
''')
cursor.execute(
'CREATE INDEX IF NOT EXISTS instances_index_sop_class_uid '
'ON instances (SOPClassUID)'
)
cursor.close()
def _drop_db(self):
"""Drop database tables and indices."""
with self._connection as connection:
cursor = connection.cursor()
cursor.execute('DROP TABLE IF EXISTS instances')
cursor.execute('DROP TABLE IF EXISTS series')
cursor.execute('DROP TABLE IF EXISTS studies')
cursor.close()
def _update_db(self):
"""Update database."""
all_attributes = (
self._attributes[_QueryResourceType.STUDIES] +
self._attributes[_QueryResourceType.SERIES] +
self._attributes[_QueryResourceType.INSTANCES]
)
tags = [
tag_for_keyword(attr)
for attr in all_attributes
]
def is_stop_tag(tag: BaseTag, VR: Optional[str], length: int) -> bool:
return tag > max(tags)
indexed_file_paths = set(self._get_indexed_file_paths())
found_file_paths = set()
studies = {}
series = {}
instances = {}
n = 100
for i, file_path in enumerate(self.base_dir.glob('**/*')):
if not file_path.is_file() or file_path.name == 'DICOMDIR':
continue
rel_file_path = file_path.relative_to(self.base_dir)
found_file_paths.add(rel_file_path)
if file_path in indexed_file_paths:
logger.debug(f'skip indexed file {file_path}')
continue
logger.debug(f'index file {file_path}')
with open(file_path, 'rb') as fp:
try:
ds = read_partial(
fp,
stop_when=is_stop_tag,
specific_tags=tags
)