Debian Codegraph @

js/src/index.js

raw
1 export class Dcm2niix {
2 constructor() {
3 this.worker = null;
4 }
5
6 init() {
7 this.worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
8 return new Promise((resolve, reject) => {
9 // handle worker ready message.
10 // This gets reassigned in the run() method,
11 // but we need to handle the ready message before that.
12 // Maybe there is a less hacky way to do this?
13 this.worker.onmessage = (event) => {
14 if (event.data && event.data.type === 'ready') {
15 resolve(true); // Resolve the promise when the worker is ready
16 }
17 }
18
19 // Handle worker init errors.
20 this.worker.onerror = (error) => {
21 reject(new Error(`Worker failed to load: ${error.message}`));
22 }
23 });
24 }
25
26 conformFileList(fileObjectOrArray) {
27 // prepare files with their relative paths.
28 // annoyingly, safari strips the webkitRelativePath property when sending files to the worker.
29 // fileList is a FileList object, not an array, so we need to convert it to an array.
30 // filesWithRelativePaths is an array of objects with the file and webkitRelativePath properties.
31 // Now we can use the webkitRelativePath property in the worker.
32 // This is important for dcm2niix to work with nested dicom directories in safari.
33 const filesWithRelativePaths = Array.from(fileObjectOrArray).map((file) => ({
34 file,
35 // need to check for both webkitRelativePath and _webkitRelativePath.
36 // _webkitRelativePath is used in case the file was not from a webkitdirectory file input element (e.g. from a drop event).
37 // IMPORTANT: it is up to other developers to ensure that the special _webkitRelativePath property is set correctly when using drop events.
38 webkitRelativePath: file.webkitRelativePath || file._webkitRelativePath || ''
39 }));
40 return filesWithRelativePaths
41 }
42
43 input(fileListObject) {
44 const conformedFileList = this.conformFileList(fileListObject);
45 return new Processor({ worker: this.worker, fileList: conformedFileList });
46 }
47
48 inputFromWebkitDirectory(fileListObject) {
49 const conformedFileList = this.conformFileList(fileListObject);
50 return new Processor({ worker: this.worker, fileList: conformedFileList });
51 }
52
53 inputFromDropItems(dataTransferItemArray) {
54 const conformedFileList = this.conformFileList(dataTransferItemArray);
55 return new Processor({ worker: this.worker, fileList: conformedFileList });
56 }
57 }
58
59 class Processor {
60 constructor({ worker, fileList }) {
61 this.worker = worker;
62 this.fileList = fileList;
63 this.commands = []; // default to verbose output for testing
64 }
65
66 _addCommand(cmd, ...args) {
67 this.commands.push(cmd, ...args.map(String));
68 return this;
69 }
70
71 // --version
72 version() {
73 return this._addCommand('--version');
74 }
75
76 // -1..-9 gz compression level (1=fastest..9=smallest, default 6)
77 compressionLevel(level) {
78 return this._addCommand(`-${level}`);
79 }
80
81 // -a adjacent DICOMs (images from same series always in same folder) for faster conversion (n/y, default n)
82 a(value) {
83 return this._addCommand('-a', value);
84 }
85 // alias for -a
86 adjacent(value) {
87 return this.a(value);
88 }
89
90 // -b BIDS sidecar (y/n/o [o=only: no NIfTI], default y)
91 b(value) {
92 return this._addCommand('-b', value);
93 }
94 // alias for -b
95 bids(value) {
96 return this.b(value);
97 }
98
99 // -ba BIDS anonymize (y/n, default y)
100 ba(value) {
101 return this._addCommand('-ba', value);
102 }
103 // alias for -ba
104 bidsAnonymize(value) {
105 return this.ba(value);
106 }
107
108 // -c comment stored as NIfTI aux_file (up to 24 characters)
109 c(value) {
110 return this._addCommand('-c', value);
111 }
112 // alias for -c
113 comment(value) {
114 return this.c(value);
115 }
116
117 // -d directory search depth (0..9, default 5)
118 // Note: not used in browser/wasm since file list is a flat list
119 d(value) {
120 return this._addCommand('-d', value);
121 }
122 // alias for -d
123 directorySearchDepth(value) {
124 return this.d(value);
125 }
126
127 // export as NRRD (y) or MGH (o) or JSON/JNIfTI (j) or BJNIfTI (b) instead of NIfTI (y/n/o/j/b, default n)
128 e(value) {
129 return this._addCommand('-e', value);
130 }
131 // alias for -e
132 exportFormat(value) {
133 return this.e(value);
134 }
135
136 // -f : filename (%a=antenna (coil) name, %b=basename, %c=comments, %d=description,
137 // %e=echo number, %f=folder name, %g=accession number, %i=ID of patient, %j=seriesInstanceUID,
138 // %k=studyInstanceUID, %m=manufacturer, %n=name of patient, %o=mediaObjectInstanceUID,
139 // %p=protocol, %r=instance number, %s=series number, %t=time, %u=acquisition number,
140 // %v=vendor, %x=study ID; %z=sequence name;
141 //
142 // default '%f_%p_%t_%s')
143 f(value) {
144 return this._addCommand('-f', value);
145 }
146 // alias for -f
147 filenameformat(value) {
148 return this.f(value);
149 }
150
151 // -i : ignore derived, localizer and 2D images (y/n, default n)
152 i(value) {
153 return this._addCommand('-i', value);
154 }
155 // alias for -i
156 ignoreDerived(value) {
157 return this.i(value);
158 }
159
160 // -l : losslessly scale 16-bit integers to use dynamic range (y/n/o [yes=scale, no=no, but uint16->int16, o=original], default o)
161 l(value) {
162 return this._addCommand('-l', value);
163 }
164 // alias for -l
165 losslessScale(value) {
166 return this.l(value);
167 }
168
169 // -m : merge 2D slices from same series regardless of echo, exposure, etc. (n/y or 0/1/2, default 2) [no, yes, auto]
170 m(value) {
171 return this._addCommand('-m', value);
172 }
173 // alias for -m
174 merge2DSlices(value) {
175 return this.m(value);
176 }
177
178 // -n : only convert this series CRC number - can be used up to 16 times (default convert all)
179 n(value) {
180 return this._addCommand('-n', value);
181 }
182 // alias for -n
183 seriesCRC(value) {
184 return this.n(value);
185 }
186
187 // -o : output directory (omit to save to input folder)
188 // o(value){
189 // return this._addCommand('-o', value);
190 // }
191 // alias for -o
192 // outputDirectory(value){
193 // return this.o(value);
194 // }
195
196 // -p : Philips precise float (not display) scaling (y/n, default y)
197 p(value) {
198 return this._addCommand('-p', value);
199 }
200 // alias for -p
201 philipsPreciseFloat(value) {
202 return this.p(value);
203 }
204
205 // -q : only search directory for DICOMs (y/l/n, default y) [y=show number of DICOMs found, l=additionally list DICOMs found, n=no]
206 q(value) {
207 return this._addCommand('-q', value);
208 }
209 // alias for -q
210 searchDirectory(value) {
211 return this.q(value);
212 }
213
214 // -r : rename instead of convert DICOMs (y/n, default n)
215 r(value) {
216 return this._addCommand('-r', value);
217 }
218 // alias for -r
219 renameOnly(value) {
220 return this.r(value);
221 }
222
223 // -s : single file mode, do not convert other images in folder (y/n, default n)
224 s(value) {
225 return this._addCommand('-s', value);
226 }
227 // alias for -s
228 singleFileMode(value) {
229 return this.s(value);
230 }
231
232 // -v : verbose (n/y or 0/1/2, default 0) [no, yes, logorrheic]
233 v(value) {
234 return this._addCommand('-v', value);
235 }
236 // alias for -v
237 verbose(value) {
238 return this.v(value);
239 }
240
241 // -w : write behavior for name conflicts (0,1,2, default 2: 0=skip duplicates, 1=overwrite, 2=add suffix)
242 w(value) {
243 return this._addCommand('-w', value);
244 }
245 // alias for -w
246 writeBehavior(value) {
247 return this.w(value);
248 }
249
250 // -x : crop 3D acquisitions (y/n/i, default n, use 'i'gnore to neither crop nor rotate 3D acquisitions)
251 x(value) {
252 return this._addCommand('-x', value);
253 }
254 // alias for -x
255 crop(value) {
256 return this.x(value);
257 }
258
259 // -z : gz compress images (y/o/i/n/3, default n) [y=pigz, o=optimal pigz, i=internal:miniz, n=no, 3=no,3D]
260 z(value) {
261 return this._addCommand('-z', value);
262 }
263 // alias for -z
264 gzip(value) {
265 return this.z(value);
266 }
267
268 // --big-endian : byte order (y/n/o, default o) [y=big-end, n=little-end, o=optimal/native]
269 bigEndian(value) {
270 return this._addCommand('--big-endian', value);
271 }
272
273 // --ignore_trigger_times : disregard values in 0018,1060 and 0020,9153
274 ignoreTriggerTimes() {
275 return this._addCommand('--ignore_trigger_times');
276 }
277
278 // --terse : omit filename post-fixes (can cause overwrites)
279 terse() {
280 return this._addCommand('--terse');
281 }
282
283 // --xml : Slicer format features
284 xml() {
285 return this._addCommand('--xml');
286 }
287
288 async run() {
289 return new Promise((resolve, reject) => {
290 this.worker.onmessage = (e) => {
291 if (e.data.type === 'error') {
292 reject(new Error(e.data.message));
293 } else {
294 // get the output file and the exit code from niimath wasm
295 const { convertedFiles, exitCode } = e.data;
296 // --version gives exit code 3 in dcm2niix CLI and wasm
297 if (exitCode === 0 || exitCode === 3) {
298 // success
299 resolve(convertedFiles);
300 } else {
301 // error
302 reject(new Error(`dcm2niix processing failed with exit code ${exitCode}`));
303 }
304 }
305 };
306
307 const args = [...this.commands];
308 if (this.worker === null) {
309 reject(new Error('Worker not initialized. Did you await the init() method?'));
310 }
311 // send files and commands to the worker
312 this.worker.postMessage({ fileList: this.fileList, cmd: args });
313 });
314 }
315 }