Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1456 lines (1231 loc) · 52 KB
/
Copy pathmain.py
File metadata and controls
1456 lines (1231 loc) · 52 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
#!/usr/bin/env python3
"""DICOM Anonymizer — main application window."""
from __future__ import annotations
import os
import sys
import tempfile
from pathlib import Path
# Resolve Qt plugin path before any Qt import so macOS can find libqcocoa.dylib.
# This is needed when running from a conda/venv environment.
try:
import PyQt6 as _pyqt6
_qt_plugins = Path(_pyqt6.__file__).parent / "Qt6" / "plugins"
if _qt_plugins.exists():
os.environ.setdefault("QT_PLUGIN_PATH", str(_qt_plugins))
os.environ.setdefault("QT_QPA_PLATFORM_PLUGIN_PATH", str(_qt_plugins / "platforms"))
except Exception:
pass
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QSplitter, QGroupBox, QLabel, QLineEdit, QPushButton, QCheckBox,
QSlider, QComboBox, QScrollArea, QFileDialog, QMessageBox,
QStackedWidget, QRadioButton, QButtonGroup, QFrame, QToolBar,
QSpinBox, QSizePolicy, QDialog, QTableWidget, QTableWidgetItem,
QHeaderView, QDialogButtonBox, QToolButton,
)
from PyQt6.QtCore import Qt, QSettings, QThread, pyqtSignal
from PyQt6.QtGui import QAction, QFont, QGuiApplication, QDoubleValidator
import utils
import exact_client as ec
from viewer import DicomViewer
# ── Stylesheet ────────────────────────────────────────────────────────────────
STYLESHEET = """
QMainWindow { background:#111320; }
QWidget {
background:#111320;
color:#d8ddf0;
font-size:13px;
}
/* ── panels ── */
QWidget#LeftPanel, QWidget#RightContainer {
background:#171929;
border-radius:0px;
}
/* ── group boxes ── */
QGroupBox {
border:1px solid #252a42;
border-radius:10px;
margin-top:16px;
padding:10px 8px 8px 8px;
font-weight:700;
color:#7fa8ff;
font-size:12px;
letter-spacing:0.4px;
}
QGroupBox::title {
subcontrol-origin:margin;
left:12px;
padding:0 6px;
}
/* ── buttons ── */
QPushButton {
background:#2d52c0;
color:#fff;
border:none;
border-radius:8px;
padding:8px 16px;
font-weight:600;
font-size:12px;
}
QPushButton:hover { background:#3b63d4; }
QPushButton:pressed { background:#1f3d98; }
QPushButton:disabled { background:#1e2235; color:#404565; }
QPushButton#accent {
background:#0f7d4b;
color:#fff;
}
QPushButton#accent:hover { background:#139962; }
QPushButton#accent:pressed { background:#0a5c38; }
QPushButton#accent:disabled { background:#1e2235; color:#404565; }
QPushButton#small {
padding:5px 10px;
font-size:11px;
border-radius:6px;
background:#252a42;
}
QPushButton#small:hover { background:#2e3560; }
/* ── inputs ── */
QLineEdit, QSpinBox {
background:#1a1e30;
border:1px solid #252a42;
border-radius:7px;
padding:6px 10px;
color:#d8ddf0;
selection-background-color:#2d52c0;
}
QLineEdit:focus, QSpinBox:focus { border-color:#4a78e8; }
QLineEdit:disabled { color:#404565; }
QComboBox {
background:#1a1e30;
border:1px solid #252a42;
border-radius:7px;
padding:6px 10px;
color:#d8ddf0;
}
QComboBox:focus { border-color:#4a78e8; }
QComboBox::drop-down { border:none; width:26px; }
QComboBox QAbstractItemView {
background:#1a1e30;
selection-background-color:#2d52c0;
border:1px solid #252a42;
}
/* ── sliders ── */
QSlider::groove:horizontal {
height:4px;
background:#252a42;
border-radius:2px;
}
QSlider::handle:horizontal {
width:14px; height:14px;
background:#4a78e8;
border-radius:7px;
margin:-5px 0;
}
QSlider::sub-page:horizontal {
background:#2d52c0;
border-radius:2px;
}
/* ── check / radio ── */
QCheckBox, QRadioButton {
color:#8890b0;
spacing:6px;
font-size:12px;
}
QCheckBox::indicator, QRadioButton::indicator {
width:14px; height:14px;
border:1px solid #252a42;
border-radius:3px;
background:#1a1e30;
}
QRadioButton::indicator { border-radius:7px; }
QCheckBox::indicator:checked, QRadioButton::indicator:checked {
background:#2d52c0;
border-color:#4a78e8;
}
/* ── scroll ── */
QScrollArea { border:none; }
QScrollBar:vertical {
background:#111320;
width:7px;
border-radius:3px;
}
QScrollBar::handle:vertical {
background:#252a42;
border-radius:3px;
min-height:20px;
}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }
/* ── status bar ── */
QStatusBar {
background:#0c0f1c;
color:#5a6080;
font-size:11px;
border-top:1px solid #1e2235;
padding:2px 8px;
}
/* ── toolbar ── */
QToolBar {
background:#0e1120;
border-bottom:1px solid #1e2235;
padding:4px 8px;
spacing:6px;
}
QToolBar QToolButton {
background:#1e2340;
color:#d8ddf0;
border:none;
border-radius:7px;
padding:6px 14px;
font-size:12px;
font-weight:600;
}
QToolBar QToolButton:hover { background:#28304e; }
QToolBar QToolButton:pressed { background:#1a1e35; }
/* ── separators ── */
QFrame#Sep {
background:#1e2235;
max-height:1px;
min-height:1px;
}
/* ── metadata labels ── */
QLabel#MetaKey { color:#44495e; font-size:11px; }
QLabel#MetaVal { color:#c0c6e0; font-size:12px; }
QLabel#SectionHead {
color:#7fa8ff;
font-weight:700;
font-size:11px;
letter-spacing:0.5px;
margin-top:4px;
}
"""
# ── Helper widgets ────────────────────────────────────────────────────────────
def _sep() -> QFrame:
f = QFrame()
f.setObjectName("Sep")
f.setFrameShape(QFrame.Shape.HLine)
return f
def _fmt_num(v, nd: int = 3) -> str:
if v is None:
return ""
try:
return f"{float(v):.{nd}f}"
except (TypeError, ValueError):
return str(v)
def _fmt_vec(v, nd: int = 2) -> str:
if not v:
return ""
try:
return ", ".join(f"{float(x):.{nd}f}" for x in v)
except (TypeError, ValueError):
return str(v)
class _CollapsibleBox(QWidget):
"""A section with a clickable header that shows/hides its content."""
def __init__(self, title: str, expanded: bool = True) -> None:
super().__init__()
self._btn = QToolButton()
self._btn.setText(title)
self._btn.setCheckable(True)
self._btn.setChecked(expanded)
self._btn.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self._btn.setArrowType(
Qt.ArrowType.DownArrow if expanded else Qt.ArrowType.RightArrow
)
self._btn.setCursor(Qt.CursorShape.PointingHandCursor)
self._btn.setStyleSheet(
"QToolButton{border:none;color:#7fa8ff;font-weight:700;font-size:12px;"
"letter-spacing:0.4px;padding:4px 2px;text-align:left;}"
"QToolButton:hover{color:#a9c4ff;}"
)
self._btn.toggled.connect(self._on_toggled)
self._content = QWidget()
self._content.setVisible(expanded)
lay = QVBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
lay.setSpacing(2)
lay.addWidget(self._btn)
lay.addWidget(self._content)
def setContentLayout(self, layout) -> None:
self._content.setLayout(layout)
def _on_toggled(self, checked: bool) -> None:
self._btn.setArrowType(
Qt.ArrowType.DownArrow if checked else Qt.ArrowType.RightArrow
)
self._content.setVisible(checked)
class _InfoRow(QWidget):
"""One metadata key-value row."""
def __init__(self, key: str) -> None:
super().__init__()
h = QHBoxLayout(self)
h.setContentsMargins(0, 1, 0, 1)
h.setSpacing(6)
k = QLabel(key)
k.setObjectName("MetaKey")
k.setFixedWidth(72)
self._v = QLabel("—")
self._v.setObjectName("MetaVal")
self._v.setWordWrap(True)
h.addWidget(k)
h.addWidget(self._v, stretch=1)
def set(self, val: str) -> None:
self._v.setText(str(val).strip() if val else "—")
# ── Left panel (metadata display) ────────────────────────────────────────────
class _LeftPanel(QScrollArea):
# Emitted when the user requests navigation to a typed coordinate.
# (system, a, b, c) where system is "ras" | "voxel" | "xyz"
goto_requested = pyqtSignal(str, float, float, float)
def __init__(self) -> None:
super().__init__()
self.setWidgetResizable(True)
self.setFixedWidth(300)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
container = QWidget()
container.setObjectName("LeftPanel")
self.setWidget(container)
outer = QVBoxLayout(container)
outer.setContentsMargins(10, 10, 10, 10)
outer.setSpacing(10)
# Series info
grp1 = QGroupBox("Series")
v1 = QVBoxLayout()
v1.setSpacing(3)
self.modality = _InfoRow("Modality")
self.study_date = _InfoRow("Date")
self.study_desc = _InfoRow("Study")
self.series_desc = _InfoRow("Series")
self.dimensions = _InfoRow("Size")
for w in [self.modality, self.study_date, self.study_desc,
self.series_desc, self.dimensions]:
v1.addWidget(w)
grp1.setLayout(v1)
outer.addWidget(grp1)
# DICOM geometry (slice spacing / positions)
grpg = QGroupBox("Geometry")
vg = QVBoxLayout()
vg.setSpacing(3)
self.geo_thick = _InfoRow("SliceThk") # (0018,0050)
self.geo_between = _InfoRow("Spacing") # (0018,0088)
self.geo_computed = _InfoRow("Δ/Slice") # |IPP_last-IPP_first|/(N-1)
self.geo_ipp_first = _InfoRow("IPP first") # (0020,0032)
self.geo_ipp_last = _InfoRow("IPP last")
for w in [self.geo_thick, self.geo_between, self.geo_computed,
self.geo_ipp_first, self.geo_ipp_last]:
vg.addWidget(w)
grpg.setLayout(vg)
outer.addWidget(grpg)
# Format-specific info (collapsible; auto-selected by loaded format)
boxf = _CollapsibleBox("Format", expanded=False)
vf = QVBoxLayout()
vf.setContentsMargins(8, 0, 4, 4)
vf.setSpacing(5)
fmt_row = QHBoxLayout()
self.fmt_dicom = QRadioButton("DICOM")
self.fmt_nifti = QRadioButton("NIfTI")
self.fmt_dicom.setChecked(True)
grp_fmt = QButtonGroup(self)
grp_fmt.addButton(self.fmt_dicom)
grp_fmt.addButton(self.fmt_nifti)
fmt_row.addWidget(self.fmt_dicom)
fmt_row.addWidget(self.fmt_nifti)
vf.addLayout(fmt_row)
self.fmt_stack = QStackedWidget()
# DICOM page
dpage = QWidget()
dl = QVBoxLayout(dpage)
dl.setContentsMargins(0, 0, 0, 0)
dl.setSpacing(3)
self.dcm_modality = _InfoRow("Modality")
self.dcm_manuf = _InfoRow("Maker")
self.dcm_voxel = _InfoRow("Voxel mm")
for w in [self.dcm_modality, self.dcm_manuf, self.dcm_voxel]:
dl.addWidget(w)
self.fmt_stack.addWidget(dpage)
# NIfTI page
npage = QWidget()
nl = QVBoxLayout(npage)
nl.setContentsMargins(0, 0, 0, 0)
nl.setSpacing(3)
self.nii_voxel = _InfoRow("Voxel mm")
self.nii_dtype = _InfoRow("Data type")
self.nii_orient = _InfoRow("Orient")
self.nii_dims = _InfoRow("Dims")
for w in [self.nii_voxel, self.nii_dtype, self.nii_orient, self.nii_dims]:
nl.addWidget(w)
self.fmt_stack.addWidget(npage)
vf.addWidget(self.fmt_stack)
boxf.setContentLayout(vf)
outer.addWidget(boxf)
self.fmt_dicom.toggled.connect(
lambda checked: self.fmt_stack.setCurrentIndex(0 if checked else 1)
)
# Patient info (collapsible)
box2 = _CollapsibleBox("Original Patient", expanded=False)
v2 = QVBoxLayout()
v2.setContentsMargins(8, 0, 4, 4)
v2.setSpacing(3)
self.pt_name = _InfoRow("Name")
self.pt_id = _InfoRow("ID")
self.pt_dob = _InfoRow("DOB")
self.pt_sex = _InfoRow("Sex")
self.pt_age = _InfoRow("Age")
for w in [self.pt_name, self.pt_id, self.pt_dob,
self.pt_sex, self.pt_age]:
v2.addWidget(w)
box2.setContentLayout(v2)
outer.addWidget(box2)
# Coordinates (live cursor readout)
grp3 = QGroupBox("Coordinates")
v3 = QVBoxLayout()
v3.setSpacing(3)
hint = QLabel("Hover over a view")
hint.setObjectName("MetaKey")
v3.addWidget(hint)
self.coord_ras = _InfoRow("RAS mm")
self.coord_voxel = _InfoRow("Voxel")
self.coord_value = _InfoRow("Value")
for w in [self.coord_ras, self.coord_voxel, self.coord_value]:
v3.addWidget(w)
# Image-coordinate mm (index × spacing, volume-corner origin) —
# matches the external navigation device readout.
self.coord_x = _InfoRow("x")
self.coord_y = _InfoRow("y")
self.coord_z = _InfoRow("z")
for w in [self.coord_x, self.coord_y, self.coord_z]:
v3.addWidget(w)
grp3.setLayout(v3)
outer.addWidget(grp3)
# Go-to-coordinate input
grp4 = QGroupBox("Gehe zu Koordinate")
v4 = QVBoxLayout()
v4.setSpacing(5)
# Coordinate-system selector at the top
self.goto_system = QComboBox()
self.goto_system.addItems(["RAS mm", "Voxel", "XYZ"])
self.goto_system.currentTextChanged.connect(self._update_goto_hints)
v4.addWidget(self.goto_system)
# Three input fields
fields_row = QHBoxLayout()
fields_row.setSpacing(4)
self.goto_a = QLineEdit()
self.goto_b = QLineEdit()
self.goto_c = QLineEdit()
for e in (self.goto_a, self.goto_b, self.goto_c):
e.setValidator(QDoubleValidator())
e.returnPressed.connect(self._emit_goto)
fields_row.addWidget(e)
v4.addLayout(fields_row)
# Update button
self.goto_btn = QPushButton("Aktualisieren")
self.goto_btn.clicked.connect(self._emit_goto)
v4.addWidget(self.goto_btn)
grp4.setLayout(v4)
outer.addWidget(grp4)
self._update_goto_hints(self.goto_system.currentText())
outer.addStretch()
def update(self, meta: dict) -> None:
self.modality.set(meta.get("modality", ""))
self.study_date.set(meta.get("study_date", ""))
self.study_desc.set(meta.get("study_description", ""))
self.series_desc.set(meta.get("series_description", ""))
sh = meta.get("volume_shape")
self.dimensions.set(
f"{sh[2]} × {sh[1]} × {sh[0]}" if sh else ""
)
self.pt_name.set(meta.get("patient_name", ""))
self.pt_id.set(meta.get("patient_id", ""))
self.pt_dob.set(meta.get("patient_dob", ""))
self.pt_sex.set(meta.get("patient_sex", ""))
self.pt_age.set(meta.get("patient_age", ""))
# Geometry
self.geo_thick.set(_fmt_num(meta.get("slice_thickness")))
self.geo_between.set(_fmt_num(meta.get("spacing_between_slices")))
self.geo_computed.set(_fmt_num(meta.get("computed_slice_spacing")))
self.geo_ipp_first.set(_fmt_vec(meta.get("ipp_first")))
self.geo_ipp_last.set(_fmt_vec(meta.get("ipp_last")))
# Format panel — fill both pages, then auto-select the loaded format
vox = _fmt_vec(meta.get("voxel_spacing"), nd=3)
self.dcm_modality.set(meta.get("modality", ""))
self.dcm_manuf.set(meta.get("manufacturer", ""))
self.dcm_voxel.set(vox)
self.nii_voxel.set(vox)
self.nii_dtype.set(meta.get("nifti_dtype", ""))
self.nii_orient.set(meta.get("nifti_orientation", ""))
self.nii_dims.set(meta.get("nifti_dims", ""))
if meta.get("source_kind") == "nifti":
self.fmt_nifti.setChecked(True)
else:
self.fmt_dicom.setChecked(True)
def update_coords(self, info: dict | None) -> None:
"""Update the live coordinate readout from a viewer hover event."""
if not info:
for w in (self.coord_ras, self.coord_voxel, self.coord_value,
self.coord_x, self.coord_y, self.coord_z):
w.set("")
return
ras = info.get("ras")
if ras is not None:
self.coord_ras.set(f"{ras[0]:.1f}, {ras[1]:.1f}, {ras[2]:.1f}")
else:
self.coord_ras.set("n/a")
vx = info.get("voxel")
if vx is not None:
self.coord_voxel.set(f"{vx[0]}, {vx[1]}, {vx[2]}")
val = info.get("value")
if val is not None:
self.coord_value.set(f"{val:.0f}")
world = info.get("world")
if world is not None:
self.coord_x.set(f"{world[0]:.2f} mm")
self.coord_y.set(f"{world[1]:.2f} mm")
self.coord_z.set(f"{world[2]:.2f} mm")
# ── Go-to-coordinate ───────────────────────────────────────────────────────
_GOTO_HINTS = {
"RAS mm": ("R", "A", "S"),
"Voxel": ("x", "y", "z"),
"XYZ": ("x mm", "y mm", "z mm"),
}
_GOTO_KEYS = {"RAS mm": "ras", "Voxel": "voxel", "XYZ": "xyz"}
def _update_goto_hints(self, system_text: str) -> None:
a, b, c = self._GOTO_HINTS.get(system_text, ("x", "y", "z"))
self.goto_a.setPlaceholderText(a)
self.goto_b.setPlaceholderText(b)
self.goto_c.setPlaceholderText(c)
def _emit_goto(self) -> None:
key = self._GOTO_KEYS.get(self.goto_system.currentText(), "voxel")
try:
a = float(self.goto_a.text().replace(",", "."))
b = float(self.goto_b.text().replace(",", "."))
c = float(self.goto_c.text().replace(",", "."))
except ValueError:
return
self.goto_requested.emit(key, a, b, c)
# ── Right panel (anonymisation + export) ─────────────────────────────────────
class _RightPanel(QScrollArea):
# Signals emitted when the user acts
wl_changed = pyqtSignal(float, float) # (center, width)
export_nifti_req = pyqtSignal()
connect_req = pyqtSignal()
export_exact_req = pyqtSignal()
def __init__(self) -> None:
super().__init__()
self.setWidgetResizable(True)
self.setFixedWidth(268)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
container = QWidget()
container.setObjectName("RightContainer")
self.setWidget(container)
v = QVBoxLayout(container)
v.setContentsMargins(10, 10, 10, 10)
v.setSpacing(10)
v.addWidget(self._build_anon_group())
v.addWidget(self._build_exact_group())
v.addStretch()
# ── Anonymisation group ───────────────────────────────────────────────────
def _build_anon_group(self) -> QGroupBox:
grp = QGroupBox("Anonymisation")
ag = QVBoxLayout()
ag.setSpacing(6)
# Original name display
orig_head = QLabel("ORIGINAL")
orig_head.setObjectName("SectionHead")
ag.addWidget(orig_head)
self.orig_name_lbl = QLabel("—")
self.orig_name_lbl.setWordWrap(True)
self.orig_name_lbl.setStyleSheet("color:#c05060;font-size:12px;padding:2px 0;")
ag.addWidget(self.orig_name_lbl)
ag.addWidget(_sep())
# Pseudonym field
ps_head = QLabel("PSEUDONYM")
ps_head.setObjectName("SectionHead")
ag.addWidget(ps_head)
name_row = QHBoxLayout()
self.pseudo_edit = QLineEdit()
self.pseudo_edit.setPlaceholderText("e.g. SwiftRiver")
self.gen_btn = QPushButton("⟳")
self.gen_btn.setObjectName("small")
self.gen_btn.setFixedWidth(34)
self.gen_btn.setToolTip("Generate random pseudonym")
name_row.addWidget(self.pseudo_edit, stretch=1)
name_row.addWidget(self.gen_btn)
ag.addLayout(name_row)
self.det_check = QCheckBox("Deterministic (hash of patient ID)")
ag.addWidget(self.det_check)
self.copy_btn = QPushButton("Copy Pseudonym")
self.copy_btn.setObjectName("small")
self.copy_btn.setEnabled(False)
ag.addWidget(self.copy_btn)
ag.addWidget(_sep())
# Window / Level
wl_head = QLabel("WINDOW / LEVEL")
wl_head.setObjectName("SectionHead")
ag.addWidget(wl_head)
# WC
wc_row = QHBoxLayout()
wc_row.addWidget(QLabel("Center"))
self.wc_val_lbl = QLabel("0")
self.wc_val_lbl.setAlignment(Qt.AlignmentFlag.AlignRight)
self.wc_val_lbl.setStyleSheet("color:#7fa8ff;font-size:11px;min-width:40px;")
wc_row.addWidget(self.wc_val_lbl)
ag.addLayout(wc_row)
self.wc_slider = QSlider(Qt.Orientation.Horizontal)
self.wc_slider.setRange(-4096, 8192)
self.wc_slider.setValue(300)
ag.addWidget(self.wc_slider)
# WW
ww_row = QHBoxLayout()
ww_row.addWidget(QLabel("Width"))
self.ww_val_lbl = QLabel("2000")
self.ww_val_lbl.setAlignment(Qt.AlignmentFlag.AlignRight)
self.ww_val_lbl.setStyleSheet("color:#7fa8ff;font-size:11px;min-width:40px;")
ww_row.addWidget(self.ww_val_lbl)
ag.addLayout(ww_row)
self.ww_slider = QSlider(Qt.Orientation.Horizontal)
self.ww_slider.setRange(1, 16384)
self.ww_slider.setValue(2000)
ag.addWidget(self.ww_slider)
# Connect sliders
self.wc_slider.valueChanged.connect(
lambda v: (self.wc_val_lbl.setText(str(v)), self._emit_wl())
)
self.ww_slider.valueChanged.connect(
lambda v: (self.ww_val_lbl.setText(str(v)), self._emit_wl())
)
ag.addWidget(_sep())
# Export NIfTI
self.export_nifti_btn = QPushButton("Save anonymised NIfTI …")
self.export_nifti_btn.setObjectName("accent")
self.export_nifti_btn.setEnabled(False)
self.export_nifti_btn.clicked.connect(self.export_nifti_req)
ag.addWidget(self.export_nifti_btn)
grp.setLayout(ag)
return grp
# ── EXACT group ───────────────────────────────────────────────────────────
def _build_exact_group(self) -> QGroupBox:
grp = QGroupBox("EXACT Export")
eg = QVBoxLayout()
eg.setSpacing(6)
eg.addWidget(QLabel("Server URL:"))
self.server_edit = QLineEdit()
self.server_edit.setPlaceholderText("https://exact.yourinstitution.org")
eg.addWidget(self.server_edit)
# Auth mode selector
auth_row = QHBoxLayout()
self.radio_token = QRadioButton("API Token")
self.radio_user = QRadioButton("Username / Password")
self.radio_token.setChecked(True)
grp_btn = QButtonGroup(self)
grp_btn.addButton(self.radio_token)
grp_btn.addButton(self.radio_user)
auth_row.addWidget(self.radio_token)
auth_row.addWidget(self.radio_user)
eg.addLayout(auth_row)
# Stacked widget: page 0 = token, page 1 = user/pass
self.auth_stack = QStackedWidget()
# Page 0 — token
token_page = QWidget()
tp = QVBoxLayout(token_page)
tp.setContentsMargins(0, 0, 0, 0)
tp.setSpacing(4)
tp.addWidget(QLabel("API Token:"))
self.token_edit = QLineEdit()
self.token_edit.setPlaceholderText("Paste your token here")
self.token_edit.setEchoMode(QLineEdit.EchoMode.Password)
tp.addWidget(self.token_edit)
self.save_token_check = QCheckBox("Remember token")
tp.addWidget(self.save_token_check)
self.auth_stack.addWidget(token_page)
# Page 1 — username / password
up_page = QWidget()
up = QVBoxLayout(up_page)
up.setContentsMargins(0, 0, 0, 0)
up.setSpacing(4)
up.addWidget(QLabel("Username:"))
self.username_edit = QLineEdit()
up.addWidget(self.username_edit)
up.addWidget(QLabel("Password:"))
self.password_edit = QLineEdit()
self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
up.addWidget(self.password_edit)
self.auth_stack.addWidget(up_page)
self.radio_token.toggled.connect(
lambda checked: self.auth_stack.setCurrentIndex(0 if checked else 1)
)
eg.addWidget(self.auth_stack)
# Connect button
self.connect_btn = QPushButton("Connect")
self.connect_btn.clicked.connect(self.connect_req)
eg.addWidget(self.connect_btn)
eg.addWidget(_sep())
eg.addWidget(QLabel("Image Set:"))
self.imageset_combo = QComboBox()
self.imageset_combo.setEnabled(False)
self.imageset_combo.setPlaceholderText("— connect first —")
eg.addWidget(self.imageset_combo)
self.export_exact_btn = QPushButton("Upload to EXACT")
self.export_exact_btn.setObjectName("accent")
self.export_exact_btn.setEnabled(False)
self.export_exact_btn.clicked.connect(self.export_exact_req)
eg.addWidget(self.export_exact_btn)
grp.setLayout(eg)
return grp
# ── Helpers ───────────────────────────────────────────────────────────────
def _emit_wl(self) -> None:
self.wl_changed.emit(float(self.wc_slider.value()), float(self.ww_slider.value()))
def set_wl_defaults(self, wc: float, ww: float) -> None:
data_range = ww * 2
self.wc_slider.blockSignals(True)
self.ww_slider.blockSignals(True)
self.wc_slider.setRange(int(wc - data_range), int(wc + data_range))
self.ww_slider.setRange(1, int(data_range * 4) or 16384)
self.wc_slider.setValue(int(wc))
self.ww_slider.setValue(int(ww))
self.wc_val_lbl.setText(str(int(wc)))
self.ww_val_lbl.setText(str(int(ww)))
self.wc_slider.blockSignals(False)
self.ww_slider.blockSignals(False)
def set_loaded(self, patient_name: str, patient_id: str) -> None:
self.orig_name_lbl.setText(patient_name)
self.export_nifti_btn.setEnabled(True)
self.copy_btn.setEnabled(True)
def set_connected(self, image_sets: list[dict]) -> None:
self.imageset_combo.clear()
for s in image_sets:
label = f"{s.get('name', 'Unnamed')} (id {s.get('id', '?')})"
self.imageset_combo.addItem(label, userData=s.get("id"))
self.imageset_combo.setEnabled(True)
self.export_exact_btn.setEnabled(True)
def selected_image_set_id(self) -> int | None:
idx = self.imageset_combo.currentIndex()
if idx < 0:
return None
return self.imageset_combo.itemData(idx)
# ── Worker threads ────────────────────────────────────────────────────────────
class _ScanWorker(QThread):
"""Quickly read DICOM headers to discover which series are present."""
done = pyqtSignal(list) # list of series dicts from utils.scan_dicom_folder
error = pyqtSignal(str)
def __init__(self, path: str) -> None:
super().__init__()
self._path = path
def run(self) -> None:
try:
series = utils.scan_dicom_folder(self._path)
self.done.emit(series)
except Exception as exc:
self.error.emit(str(exc))
class _LoadWorker(QThread):
done = pyqtSignal(object, object, object)
error = pyqtSignal(str)
def __init__(self, path: str, series_uid: str | None = None) -> None:
super().__init__()
self._path = path
self._series_uid = series_uid
def run(self) -> None:
try:
volume, datasets, meta = utils.load_dicom_series(
self._path, self._series_uid
)
self.done.emit(volume, datasets, meta)
except Exception as exc:
self.error.emit('Error in _LoadWorker: ' + str(exc))
class _NiftiLoadWorker(QThread):
done = pyqtSignal(object, object, object)
error = pyqtSignal(str)
def __init__(self, path: str) -> None:
super().__init__()
self._path = path
def run(self) -> None:
try:
volume, datasets, meta = utils.load_nifti(self._path)
self.done.emit(volume, datasets, meta)
except Exception as exc:
self.error.emit('Error loading NIfTI: ' + str(exc))
class _ExportWorker(QThread):
done = pyqtSignal(str)
error = pyqtSignal(str)
def __init__(self, datasets, output_path: str, pseudonym: str,
volume=None, affine=None) -> None:
super().__init__()
self._datasets = datasets
self._output = output_path
self._name = pseudonym
self._volume = volume
self._affine = affine
def run(self) -> None:
try:
if self._datasets:
utils.export_nifti(self._datasets, self._output, self._name)
elif self._volume is not None:
utils.export_nifti_volume(
self._volume, self._affine, self._output, self._name
)
else:
raise ValueError("No data loaded to export.")
self.done.emit(self._output)
except Exception as exc:
self.error.emit('Error in _ExportWorker: ' + str(exc))
class _ConnectWorker(QThread):
done = pyqtSignal(list, str) # (image_sets, token)
error = pyqtSignal(str)
def __init__(self, client: ec.ExactClient, use_token: bool,
token: str, username: str, password: str) -> None:
super().__init__()
self._client = client
self._use_token = use_token
self._token = token
self._username = username
self._password = password
def run(self) -> None:
try:
client = self._client
if self._use_token:
client.set_token(self._token)
else:
client.authenticate(self._username, self._password)
client.verify_connection()
image_sets = client.get_image_sets()
self.done.emit(image_sets, client.token or "")
except Exception as exc:
self.error.emit(str(exc))
class _UploadWorker(QThread):
done = pyqtSignal(dict)
error = pyqtSignal(str)
def __init__(self, client: ec.ExactClient, image_set_id: int,
file_path: str, name: str) -> None:
super().__init__()
self._client = client
self._image_set_id = image_set_id
self._file_path = file_path
self._name = name
def run(self) -> None:
try:
result = self._client.upload_image(
self._image_set_id, self._file_path, self._name
)
self.done.emit(result)
except Exception as exc:
self.error.emit(str(exc))
# ── Series picker dialog ──────────────────────────────────────────────────────
class _SeriesPickerDialog(QDialog):
"""Modal dialog shown when a folder contains more than one DICOM series."""
def __init__(self, series_list: list[dict], parent=None) -> None:
super().__init__(parent)
self.setWindowTitle("Select DICOM Series")
self.setModal(True)
self.resize(660, 280)
self._series = series_list
layout = QVBoxLayout(self)
layout.setSpacing(10)
lbl = QLabel(
f"<b>{len(series_list)} series</b> found in this folder — "
"select one to load:"
)
lbl.setStyleSheet("color:#d8ddf0;font-size:13px;padding-bottom:4px;")
layout.addWidget(lbl)
self._table = QTableWidget(len(series_list), 4)
self._table.setHorizontalHeaderLabels(
["Series Description", "Modality", "Slices", "Image Size"]
)
self._table.horizontalHeader().setSectionResizeMode(
0, QHeaderView.ResizeMode.Stretch
)
self._table.horizontalHeader().setDefaultAlignment(
Qt.AlignmentFlag.AlignLeft
)
self._table.setSelectionBehavior(
QTableWidget.SelectionBehavior.SelectRows
)
self._table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
self._table.setAlternatingRowColors(True)
self._table.setStyleSheet(
"QTableWidget{background:#1a1e30;alternate-background-color:#1e2340;"
"gridline-color:#252a42;color:#d8ddf0;}"
"QTableWidget::item:selected{background:#2d52c0;}"
"QHeaderView::section{background:#1e2340;color:#7fa8ff;"
"font-weight:700;font-size:11px;padding:4px;border:none;"
"border-bottom:1px solid #252a42;}"
)
for row, s in enumerate(series_list):
desc = s.get("description", "") or "(no description)"
self._table.setItem(row, 0, QTableWidgetItem(desc))
self._table.setItem(row, 1, QTableWidgetItem(s.get("modality", "")))
self._table.setItem(row, 2, QTableWidgetItem(str(s.get("n_slices", "?"))))