-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathicore_processor.py
More file actions
1598 lines (1389 loc) · 66.3 KB
/
icore_processor.py
File metadata and controls
1598 lines (1389 loc) · 66.3 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
import logging
import os
import platform
import re
import shutil
import signal
import subprocess
import sys
import time
import pydicom
import string
import tempfile
import xml.etree.ElementTree as ET
import warnings
from contextlib import contextmanager
from datetime import datetime, timedelta
from threading import Thread
import pandas as pd
import requests
import yaml
from lark import Lark
from presidio_analyzer import AnalyzerEngine, PatternRecognizer, Pattern
from presidio_analyzer.nlp_engine import NlpEngineProvider
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig
warnings.filterwarnings('ignore')
os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL', '3')
INPUT_DIR = "input"
OUTPUT_DIR = "output"
APPDATA_DIR = "appdata"
MODULES_DIR = "modules"
CONFIG_PATH = "config.yml"
IMAGEQR_CONFIG = """<Configuration>
<Server
maxThreads="20"
port="50000">
<Log/>
</Server>
<Plugin
class="org.rsna.ctp.stdplugins.AuditLog"
id="AuditLog"
name="AuditLog"
root="{appdata_dir}/temp/roots/AuditLog"/>
<Pipeline name="imagedeid">
<DicomImportService
class="org.rsna.ctp.stdstages.DicomImportService"
name="DicomImportService"
port="50001"
calledAETTag="{application_aet}"
root="{appdata_dir}/temp/roots/DicomImportService"
quarantine="{appdata_dir}/quarantine/DicomImportService"
logConnections="no" />
<DicomFilter
class="org.rsna.ctp.stdstages.DicomFilter"
name="DicomFilter"
root="{appdata_dir}/temp/roots/DicomFilter"
script="scripts/dicom-filter.script"
quarantine="{appdata_dir}/quarantine" />
<DicomAuditLogger
name="DicomAuditLogger"
class="org.rsna.ctp.stdstages.DicomAuditLogger"
root="{appdata_dir}/temp/roots/DicomAuditLogger"
auditLogID="AuditLog"
auditLogTags="AccessionNumber;StudyInstanceUID;PatientName;PatientID;PatientSex;Manufacturer;ManufacturerModelName;StudyDescription;StudyDate;SeriesInstanceUID;SOPClassUID;Modality;SeriesDescription;Rows;Columns;InstitutionName;StudyTime"
cacheID="ObjectCache"
level="study" />
<DirectoryStorageService
class="org.rsna.ctp.stdstages.DirectoryStorageService"
name="DirectoryStorageService"
root="{output_dir}/images"
structure="{{StudyInstanceUID}}/{{SeriesInstanceUID}}"
setStandardExtensions="yes"
acceptDuplicates="no"
returnStoredFile="yes"
quarantine="{appdata_dir}/quarantine/DirectoryStorageService"
whitespaceReplacement="_" />
</Pipeline>
</Configuration>
"""
IMAGEDEID_LOCAL_CONFIG = """<Configuration>
<Server
maxThreads="20"
port="50000">
<Log/>
</Server>
<Plugin
class="org.rsna.ctp.stdplugins.AuditLog"
id="AuditLog"
name="AuditLog"
root="{appdata_dir}/temp/roots/AuditLog"/>
<Plugin
class="org.rsna.ctp.stdplugins.AuditLog"
id="DeidAuditLog"
name="DeidAuditLog"
root="{appdata_dir}/temp/roots/DeidAuditLog"/>
<Pipeline name="imagedeid">
<ArchiveImportService
class="org.rsna.ctp.stdstages.ArchiveImportService"
name="ArchiveImportService"
fsName="DICOM Image Directory"
root="{appdata_dir}/temp/roots/ArchiveImportService"
treeRoot="{input_dir}"
quarantine="{appdata_dir}/quarantine/ArchiveImportService"
acceptFileObjects="no"
acceptXmlObjects="no"
acceptZipObjects="no"
expandTARs="no"/>
<DicomFilter
class="org.rsna.ctp.stdstages.DicomFilter"
name="DicomFilter"
root="{appdata_dir}/temp/roots/DicomFilter"
script="scripts/dicom-filter.script"
quarantine="{appdata_dir}/quarantine/DicomFilter"/>
<DicomAuditLogger
name="DicomAuditLogger"
class="org.rsna.ctp.stdstages.DicomAuditLogger"
root="{appdata_dir}/temp/roots/DicomAuditLogger"
auditLogID="AuditLog"
auditLogTags="AccessionNumber;StudyInstanceUID;PatientName;PatientID;PatientSex;Manufacturer;ManufacturerModelName;StudyDescription;StudyDate;SeriesInstanceUID;SOPClassUID;Modality;SeriesDescription;Rows;Columns;InstitutionName;StudyTime"
cacheID="ObjectCache"
level="study" />
<DicomDecompressor
class="org.rsna.ctp.stdstages.DicomDecompressor"
name="DicomDecompressor"
root="{appdata_dir}/temp/roots/DicomDecompressor"
script="scripts/DicomDecompressor.script"
quarantine="{appdata_dir}/quarantine/DicomDecompressor"/>
<IDMap
class="org.rsna.ctp.stdstages.IDMap"
name="IDMap"
root="{appdata_dir}/temp/roots/IDMap" />
<DicomAnonymizer
class="org.rsna.ctp.stdstages.DicomAnonymizer"
name="DicomAnonymizer"
root="{appdata_dir}/temp/roots/DicomAnonymizer"
script="scripts/DicomAnonymizer.script"
lookupTable="scripts/LookupTable.properties"
quarantine="{appdata_dir}/quarantine/DicomAnonymizer" />
<DicomAuditLogger
name="DicomAuditLogger"
class="org.rsna.ctp.stdstages.DicomAuditLogger"
root="{appdata_dir}/temp/roots/DicomAuditLogger"
auditLogID="DeidAuditLog"
auditLogTags="AccessionNumber;StudyInstanceUID;PatientName;PatientID;PatientSex;Manufacturer;ManufacturerModelName;StudyDescription;StudyDate;SeriesInstanceUID;SOPClassUID;Modality;SeriesDescription;Rows;Columns;InstitutionName;StudyTime"
cacheID="ObjectCache"
level="study" />
<DirectoryStorageService
class="org.rsna.ctp.stdstages.DirectoryStorageService"
name="DirectoryStorageService"
root="{output_dir}/"
structure="{{StudyInstanceUID}}/{{SeriesInstanceUID}}"
setStandardExtensions="yes"
acceptDuplicates="no"
returnStoredFile="yes"
quarantine="{appdata_dir}/quarantine/DirectoryStorageService"
whitespaceReplacement="_" />
</Pipeline>
</Configuration>"""
IMAGEDEID_PACS_CONFIG = """<Configuration>
<Server
maxThreads="20"
port="50000">
<Log/>
</Server>
<Plugin
class="org.rsna.ctp.stdplugins.AuditLog"
id="AuditLog"
name="AuditLog"
root="{appdata_dir}/temp/roots/AuditLog"/>
<Plugin
class="org.rsna.ctp.stdplugins.AuditLog"
id="DeidAuditLog"
name="DeidAuditLog"
root="{appdata_dir}/temp/roots/DeidAuditLog"/>
<Pipeline name="imagedeid">
<DicomImportService
class="org.rsna.ctp.stdstages.DicomImportService"
name="DicomImportService"
port="50001"
calledAETTag="{application_aet}"
root="{appdata_dir}/temp/roots/DicomImportService"
quarantine="{appdata_dir}/quarantine"
logConnections="no" />
<DicomFilter
class="org.rsna.ctp.stdstages.DicomFilter"
name="DicomFilter"
root="{appdata_dir}/temp/roots/DicomFilter"
script="scripts/dicom-filter.script"
quarantine="{appdata_dir}/quarantine" />
<DicomAuditLogger
name="DicomAuditLogger"
class="org.rsna.ctp.stdstages.DicomAuditLogger"
root="{appdata_dir}/temp/roots/DicomAuditLogger"
auditLogID="AuditLog"
auditLogTags="AccessionNumber;StudyInstanceUID;PatientName;PatientID;PatientSex;Manufacturer;ManufacturerModelName;StudyDescription;StudyDate;SeriesInstanceUID;SOPClassUID;Modality;SeriesDescription;Rows;Columns;InstitutionName;StudyTime"
cacheID="ObjectCache"
level="study" />
<DicomDecompressor
class="org.rsna.ctp.stdstages.DicomDecompressor"
name="DicomDecompressor"
root="{appdata_dir}/temp/roots/DicomDecompressor"
script="scripts/DicomDecompressor.script"
quarantine="{appdata_dir}/quarantine"/>
<IDMap
class="org.rsna.ctp.stdstages.IDMap"
name="IDMap"
root="{appdata_dir}/temp/roots/IDMap" />
<DicomAnonymizer
class="org.rsna.ctp.stdstages.DicomAnonymizer"
name="DicomAnonymizer"
root="{appdata_dir}/temp/roots/DicomAnonymizer"
script="scripts/DicomAnonymizer.script"
lookupTable="scripts/LookupTable.properties"
quarantine="{appdata_dir}/quarantine" />
<DicomAuditLogger
name="DicomAuditLogger"
class="org.rsna.ctp.stdstages.DicomAuditLogger"
root="{appdata_dir}/temp/roots/DicomAuditLogger"
auditLogID="DeidAuditLog"
auditLogTags="AccessionNumber;StudyInstanceUID;PatientName;PatientID;PatientSex;Manufacturer;ManufacturerModelName;StudyDescription;StudyDate;SeriesInstanceUID;SOPClassUID;Modality;SeriesDescription;Rows;Columns;InstitutionName;StudyTime"
cacheID="ObjectCache"
level="study" />
<DirectoryStorageService
class="org.rsna.ctp.stdstages.DirectoryStorageService"
name="DirectoryStorageService"
root="{output_dir}"
structure="{{StudyInstanceUID}}/{{SeriesInstanceUID}}"
setStandardExtensions="yes"
acceptDuplicates="no"
returnStoredFile="yes"
quarantine="{appdata_dir}/quarantine"
whitespaceReplacement="_" />
</Pipeline>
</Configuration>
"""
COMMON_DATE_FORMATS = [
'%m/%d/%Y','%Y-%m-%d','%d/%m/%Y','%m-%d-%Y','%Y/%m/%d','%d-%m-%Y',
'%m/%d/%y','%y-%m-%d','%d/%m/%y'
]
def get_dcmtk_binary(binary_name):
if getattr(sys, 'frozen', False):
bundle_dir = os.path.abspath(os.path.dirname(sys.executable))
binary_path = os.path.join(bundle_dir, '_internal', 'dcmtk', 'bin', binary_name)
return binary_path
else:
dcmtk_home = os.environ.get('DCMTK_HOME')
return os.path.join(dcmtk_home, 'bin', binary_name)
def get_dcmtk_dict_path():
if getattr(sys, 'frozen', False):
bundle_dir = os.path.abspath(os.path.dirname(sys.executable))
return os.path.join(bundle_dir, '_internal', 'dcmtk', 'share', 'dcmtk-3.6.9', 'dicom.dic')
else:
dcmtk_home = os.environ.get('DCMTK_HOME')
return os.path.join(dcmtk_home, 'share', 'dcmtk-3.6.9', 'dicom.dic')
def create_analyzer_engine():
if getattr(sys, 'frozen', False):
bundle_dir = os.path.abspath(os.path.dirname(sys.executable))
model_path = os.path.join(bundle_dir, '_internal', 'en_core_web_sm', 'en_core_web_sm-3.7.1')
import spacy
from presidio_analyzer.nlp_engine import SpacyNlpEngine
nlp_engine = SpacyNlpEngine(models=[{"lang_code": "en", "model_name": model_path}])
else:
configuration = {
"nlp_engine_name": "spacy",
"models": [{"lang_code": "en", "model_name": "en_core_web_sm"}],
}
provider = NlpEngineProvider(nlp_configuration=configuration)
nlp_engine = provider.create_engine()
analyzer = AnalyzerEngine(nlp_engine=nlp_engine, supported_languages=["en"])
mrn_recognizer = PatternRecognizer(
supported_entity="MRN",
name="mrn_recognizer",
patterns=[
Pattern(name="mrn_pattern", regex=r"\b(?!0{7,10}\b)\d{7,10}\b", score=0.5),
Pattern(name="mrn_prefix_pattern", regex=r"\b[A-Z]{2,6}-\d{4,10}\b", score=0.7),
],
)
alphanumeric_id_recognizer = PatternRecognizer(
supported_entity="ALPHANUMERIC_ID",
name="alphanumeric_id_recognizer",
patterns=[
Pattern(name="date_id_pattern", regex=r"\b\d{4}-\d{2}-\d{2}\b", score=0.95),
],
)
title_name_recognizer = PatternRecognizer(
supported_entity="PERSON",
name="title_name_recognizer",
patterns=[
Pattern(
name="dr_name_pattern",
regex=r"(?<=Dr\.\s)([A-Z][A-Z]+)\b",
score=0.85
),
Pattern(
name="dr_no_period_pattern",
regex=r"(?<=Dr\s)([A-Z][A-Z]+)\b",
score=0.85
),
],
)
last_name_recognizer = PatternRecognizer(
supported_entity="PERSON",
name="last_name_recognizer",
patterns=[
Pattern(
name="patient_full_name_pattern",
regex=r"(?<=Patient:\s)([A-Z][a-z]+\s+[A-Z]{2,})\b",
score=0.85
),
],
)
ssn_recognizer = PatternRecognizer(
supported_entity="US_SSN",
name="ssn_recognizer",
patterns=[
Pattern(
name="ssn_pattern",
regex=r"\b\d{3}-\d{2}-\d{4}\b",
score=0.95
),
],
)
analyzer.registry.add_recognizer(mrn_recognizer)
analyzer.registry.add_recognizer(alphanumeric_id_recognizer)
analyzer.registry.add_recognizer(title_name_recognizer)
analyzer.registry.add_recognizer(last_name_recognizer)
analyzer.registry.add_recognizer(ssn_recognizer)
return analyzer
def print_and_log(message):
logging.info(message)
print(message)
def error_and_exit(error):
print_and_log(error)
sys.exit(1)
def write(path, data):
with open(path, "w") as f:
f.write(data)
def strip_ctp_cell(value):
return value.strip('=(")') if isinstance(value, str) else value
def ctp_get(url):
request_url = f"http://localhost:50000/{url}"
for attempt in range(3):
try:
return requests.get(request_url, auth=("admin", "password")).text
except Exception:
if attempt < 2:
time.sleep(3)
else:
raise
def ctp_post(url, data):
request_url = f"http://localhost:50000/{url}"
response = requests.post(request_url, auth=("admin", "password"),
data=data, headers={"Referer": f"http://localhost:50000/{url}"})
return response.text
def ctp_get_status(key):
return int(re.search(re.compile(rf"{key}:\s*<\/td><td>(\d+)"), ctp_get("status")).group(1))
def count_files(path, exclude_files):
return sum(len([f for f in files if not f.startswith('.') and f not in exclude_files]) for _, _, files in os.walk(path))
def count_dicom_files(path):
dicom_count = 0
for root, _, files in os.walk(path):
for f in files:
try:
with open(os.path.join(root, f), 'rb') as file:
file.seek(128)
if file.read(4) == b'DICM':
dicom_count += 1
except:
continue
return dicom_count
def run_progress(data):
received = ctp_get_status("Files received") if data["querying_pacs"] else data["dicom_count"]
quarantined = count_files(os.path.join(APPDATA_DIR, "quarantine"), {".", "..", "QuarantineIndex.db", "QuarantineIndex.lg"})
saved = ctp_get_status("Files actually stored")
stable = received == (quarantined + saved)
return saved, quarantined, received, stable
def tick(tick_func, data):
stable_for = 0
while True:
time.sleep(3)
if tick_func is not None:
tick_func(data)
saved, quarantined, received, stable = run_progress(data)
stable_for = stable_for + 1 if stable else 0
if data["complete"] and stable_for > 3:
break
num, denom = (saved + quarantined), received
if int(num) != int(denom):
print_and_log(f"PROGRESS: {num}/{denom} files")
print_and_log("PROGRESS: COMPLETE")
def start_ctp_run(tick_func, tick_data, logf, ctp_dir):
if getattr(sys, 'frozen', False):
bundle_dir = os.path.abspath(os.path.dirname(sys.executable))
if platform.system() == 'Darwin':
java_home = os.path.join(bundle_dir, '_internal', 'jre8', 'Contents', 'Home')
else:
java_home = os.path.join(bundle_dir, '_internal', 'jre8')
else:
java_home = os.environ.get('JAVA_HOME')
java_executable = os.path.join(java_home, "bin", "java")
env = {'JAVA_HOME': java_home}
ctp_process = subprocess.Popen(
[java_executable, "-Djava.awt.headless=true", "-Dapple.awt.UIElement=true", "-Xms2048m", "-Xmx16384m", "-jar", "libraries/CTP.jar"],
cwd=ctp_dir, stdout=logf, stderr=logf, text=True, env=env
)
tick_data = {"complete": False, "querying_pacs": True, "dicom_count": count_dicom_files(INPUT_DIR)} | tick_data
tick_thread = Thread(target=tick, args=(tick_func, tick_data,), daemon=True)
tick_thread.start()
return (ctp_process, tick_thread, tick_data)
def finish_ctp_run(ctp_process, tick_thread, tick_data, temp_ctp_dir):
tick_data["complete"] = True
tick_thread.join()
try:
response = requests.get(
"http://localhost:50000/shutdown",
headers={"servicemanager": "shutdown"},
timeout=5
)
logging.info(f"HTTP shutdown response: {response.status_code}")
try:
ctp_process.wait(timeout=30)
logging.info("CTP process terminated via HTTP shutdown")
return
except subprocess.TimeoutExpired:
logging.warning("HTTP shutdown did not complete in time, falling back to signals")
except Exception as e:
logging.warning(f"HTTP shutdown failed: {e}, falling back to signals")
ctp_process.send_signal(signal.SIGINT)
try:
ctp_process.wait(timeout=30)
logging.info("CTP process terminated gracefully via SIGINT")
except subprocess.TimeoutExpired:
logging.warning("SIGINT did not terminate CTP, sending SIGTERM")
ctp_process.terminate()
try:
ctp_process.wait(timeout=10)
logging.info("CTP process terminated after SIGTERM")
except subprocess.TimeoutExpired:
logging.warning("CTP process did not terminate after SIGTERM, sending SIGKILL")
ctp_process.kill()
ctp_process.wait()
logging.info("CTP process force killed")
finally:
shutil.rmtree(temp_ctp_dir, ignore_errors=True)
@contextmanager
def ctp_workspace(func, data, config_setup_func=None):
temp_roots_dir = os.path.join(APPDATA_DIR, "temp", "roots")
os.makedirs(temp_roots_dir, exist_ok=True)
temp_ctp_dir = setup_ctp_directory()
if config_setup_func:
config_setup_func(temp_ctp_dir)
with open(os.path.join(APPDATA_DIR, "log.txt"), "a") as logf:
try:
process, thread, data = start_ctp_run(func, data, logf, temp_ctp_dir)
time.sleep(3)
yield logf
finally:
finish_ctp_run(process, thread, data, temp_ctp_dir)
shutil.rmtree(temp_roots_dir, ignore_errors=True)
def setup_ctp_directory():
if hasattr(sys, '_MEIPASS'):
source_ctp_dir = os.path.join(sys._MEIPASS, 'ctp')
else:
source_ctp_dir = "ctp"
temp_ctp_dir = tempfile.mkdtemp(prefix='ctp_')
shutil.copytree(source_ctp_dir, temp_ctp_dir, dirs_exist_ok=True)
return temp_ctp_dir
def save_ctp_filters(ctp_filters, ctp_dir):
with open(os.path.join(ctp_dir, "scripts", "dicom-filter.script"), "w") as f:
f.write(ctp_filters if ctp_filters is not None else "true.")
def save_ctp_anonymizer(ctp_anonymizer, ctp_dir):
if ctp_anonymizer is not None:
with open(os.path.join(ctp_dir, "scripts", "DicomAnonymizer.script"), "w") as f:
f.write(ctp_anonymizer)
def save_ctp_lookup_table(ctp_lookup_table, ctp_dir):
if ctp_lookup_table is not None:
with open(os.path.join(ctp_dir, "scripts", "LookupTable.properties"), "w") as f:
f.write(ctp_lookup_table)
else:
with open(os.path.join(ctp_dir, "scripts", "LookupTable.properties"), "w") as f:
f.write("")
def save_config(config, ctp_dir):
with open(os.path.join(ctp_dir, "config.xml"), "w") as f:
f.write(config)
def parse_dicom_tag_dict(output):
tags = {}
expr = rf".*\[(.+)\].+\#.+\,.+ (.+)"
for value, tag in re.findall(expr, output):
tags[tag.strip("\x00").strip()] = value.strip("\x00").strip()
expr = rf".*=(.+).+\#.+\,.+ (.+)"
for value, tag in re.findall(expr, output):
tags[tag.strip("\x00").strip()] = value.strip("\x00").strip()
expr = rf".*FD (.+).+\#.+\,.+ (.+)"
for value, tag in re.findall(expr, output):
tags[tag.strip("\x00").strip()] = value.strip("\x00").strip()
expr = rf".*US (.+).+\#.+\,.+ (.+)"
for value, tag in re.findall(expr, output):
tags[tag.strip("\x00").strip()] = value.strip("\x00").strip()
return tags
def generate_series_date_filter(config):
input_path = os.path.join(INPUT_DIR, "input.xlsx")
if not os.path.exists(input_path):
return None
df = pd.read_excel(input_path)
if not config.get('date_col'):
return None
# Get patient-date pairs
mrn_col = config.get('mrn_col')
date_col = config.get('date_col')
date_window = config.get('date_window', 0)
# Group by patient and get their dates
patient_date_pairs = df[[mrn_col, date_col]].drop_duplicates()
# Create per-patient conditions with their specific date ranges
patient_conditions = []
for _, row in patient_date_pairs.iterrows():
pid = str(row[mrn_col])
target_date = row[date_col]
# Calculate date range for this specific patient
date_start = (target_date - timedelta(days=date_window)).strftime("%Y%m%d")
date_end = (target_date + timedelta(days=date_window)).strftime("%Y%m%d")
# Create date condition for this patient
if date_window == 0:
# If no window, just match the exact date
date_condition = f'StudyDate.equals("{date_start}")'
else:
# If window, match start date OR end date OR anything in between
date_condition = f'(StudyDate.equals("{date_start}") + StudyDate.equals("{date_end}") + (StudyDate.isGreaterThan("{date_start}") * StudyDate.isLessThan("{date_end}")))'
# Combine patient ID with their specific date condition
patient_conditions.append(f'(PatientID.equals("{pid}") * {date_condition})')
# OR all patient conditions together
filter_expr = " + ".join(patient_conditions)
return filter_expr
def get_combined_ctp_filter(config):
generated_filter = generate_series_date_filter(config)
user_filter = config.get("ctp_filters")
if generated_filter and user_filter:
return f'({user_filter}) * ({generated_filter})'
elif generated_filter:
return generated_filter
else:
return user_filter
def cmove_queries(**config):
df = pd.read_excel(os.path.join(INPUT_DIR, "input.xlsx"))
queries = []
accession_numbers = [] # Track all accession numbers
logging.info(f"acc_col: {config.get('acc_col')}, mrn_col: {config.get('mrn_col')}")
logging.info(f"Processing {len(df)} rows from input.xlsx")
if config.get("acc_col") is not None:
mrn_col = config.get("mrn_col")
if mrn_col and mrn_col in df.columns:
acc_mrn = list(df[[config.get("acc_col"), mrn_col]].itertuples(index=False, name=None))
for i, (acc, mrn) in enumerate(acc_mrn, 1):
query = f"-k QueryRetrieveLevel=STUDY -k AccessionNumber=*{str(acc)}* -k PatientID={str(mrn)}"
queries.append(query)
accession_numbers.append(str(acc))
logging.info(f"Row {i}: Accession={acc}, MRN={mrn}")
logging.info(f" Query: {query}")
else:
acc_list = df[config.get("acc_col")].tolist()
for i, acc in enumerate(acc_list, 1):
query = f"-k QueryRetrieveLevel=STUDY -k AccessionNumber=*{str(acc)}*"
queries.append(query)
accession_numbers.append(str(acc))
logging.info(f"Row {i}: Accession={acc}")
logging.info(f" Query: {query}")
else:
mrn_dates = list(df[[config.get("mrn_col"), config.get("date_col")]].itertuples(index=False, name=None))
for i, (mrn, dt) in enumerate(mrn_dates, 1):
dts = datetime.strftime((dt - timedelta(days=config.get("date_window"))), "%Y%m%d")
dte = datetime.strftime((dt + timedelta(days=config.get("date_window"))), "%Y%m%d")
query = f"-k QueryRetrieveLevel=STUDY -k PatientID={str(mrn)} -k StudyDate={dts}-{dte}"
queries.append(query)
logging.info(f"Row {i}: MRN={mrn}, TargetDate={dt.strftime('%Y-%m-%d')}, Window={config.get('date_window')} days")
logging.info(f" Date Range: {dts} to {dte}")
logging.info(f" Query: {query}")
logging.info(f"Total queries generated: {len(queries)}")
return queries, accession_numbers
def cmove_images(logf, **config):
failed_accessions = []
successful_rows = set()
study_uids_rows = {}
queries, accession_numbers = cmove_queries(**config)
for pacs in config.get("pacs"):
study_uids = set()
ip, port, aec = pacs.get("ip"), pacs.get("port"), pacs.get("ae")
aet, aem = config.get("application_aet"), config.get("application_aet")
logging.info(f"Querying PACS: {ip}:{port} (AE: {aec})")
queries, accession_numbers = cmove_queries(**config)
for i, query in enumerate(queries):
logging.info(f"\n{'='*80}")
logging.info(f"FINDSCU Query {i+1}/{len(queries)}")
logging.info(f"{'='*80}")
cmd = [get_dcmtk_binary("findscu"), "-v", "-aet", aet, "-aec", aec, "-S"] + query.split() + ["-k", "StudyInstanceUID", ip, str(port)]
logging.info(f"Command: {' '.join(cmd)}")
env = os.environ.copy()
env['DCMDICTPATH'] = get_dcmtk_dict_path()
process = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
# Log full debug output
logging.info("FINDSCU STDOUT:")
logging.info(process.stdout)
logging.info("FINDSCU STDERR:")
logging.info(process.stderr)
output = process.stderr
studies_found_this_query = 0
for entry in output.split("Find Response:")[1:]:
tags = parse_dicom_tag_dict(entry)
study_uid = tags.get("StudyInstanceUID")
if study_uid and len(study_uid) > 0:
study_uids.add(study_uid)
study_uids_rows[study_uid] = i
studies_found_this_query += 1
study_date = tags.get("StudyDate", "N/A")
logging.info(f" Found StudyInstanceUID: {study_uid}, StudyDate: {study_date}")
if studies_found_this_query == 0:
logging.info(f" No studies found for this query")
else:
logging.info(f" Total studies found for this query: {studies_found_this_query}")
logging.info(f"Processed {i+1}/{len(queries)} query rows")
logging.info(f"\n{'='*80}")
logging.info(f"FINDSCU SUMMARY: Found {len(study_uids)} unique studies total from PACS {ip}:{port}")
logging.info(f"{'='*80}\n")
retry_count = 0
current_moves = list(study_uids)
while current_moves and retry_count < 3:
if retry_count > 0:
logging.info(f"Retry attempt {retry_count} for {len(current_moves)} failed moves")
time.sleep(5)
failed_moves = []
for i, study_uid in enumerate(current_moves):
logging.info(f"\n{'='*80}")
logging.info(f"MOVESCU {i+1}/{len(current_moves)} (Retry {retry_count})")
logging.info(f"{'='*80}")
cmd = [get_dcmtk_binary("movescu"), "-v", "-aet", aet, "-aem", aem, "-aec", aec, "-S", "-k", "QueryRetrieveLevel=STUDY", "-k", f"StudyInstanceUID={study_uid}", ip, str(port)]
logging.info(f"Command: {' '.join(cmd)}")
logging.info(f"StudyInstanceUID: {study_uid}")
env = os.environ.copy()
env['DCMDICTPATH'] = get_dcmtk_dict_path()
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env)
stdout, stderr = process.communicate()
process.wait()
# Log full debug output
logging.info("MOVESCU STDOUT:")
logging.info(stdout)
logging.info("MOVESCU STDERR:")
logging.info(stderr)
success = "Received Final Move Response (Success)" in (stdout + stderr)
if success:
successful_rows.add(study_uids_rows[study_uid])
logging.info(f"✓ SUCCESS: Study {study_uid} moved successfully")
else:
failed_moves.append(study_uid)
logging.info(f"✗ FAILED: Study {study_uid} failed to move")
logging.info(f"Progress: {i+1}/{len(current_moves)} studies processed in this batch")
current_moves = failed_moves
retry_count += 1
failed_accessions = []
for i in range(len(queries)):
if i not in successful_rows:
failed_accessions.append(i)
return failed_accessions
def save_metadata_csv():
metadata_csv = ctp_get("AuditLog?export&csv&suppress")
with open(os.path.join(APPDATA_DIR, "metadata.csv"), "w") as f:
f.write(metadata_csv)
def save_deid_metadata_csv():
deid_metadata_csv = ctp_get("DeidAuditLog?export&csv&suppress")
with open(os.path.join(APPDATA_DIR, "deid_metadata.csv"), "w") as f:
f.write(deid_metadata_csv)
def save_failed_accessions(failed_accessions):
metadata_path = os.path.join(APPDATA_DIR, "metadata.csv")
with open(metadata_path, "a") as f:
for acc in failed_accessions:
line = f"{time.strftime('%Y-%m-%d %H:%M:%S')},{acc},Failed to retrieve\n"
f.write(line)
def save_quarantined_files_log():
"""Save detailed log of quarantined files to appdata"""
log_path = os.path.join(APPDATA_DIR, "quarantined_files_log.csv")
quarantine_dirs = {
"ArchiveImportService": os.path.join(APPDATA_DIR, "quarantine", "ArchiveImportService"),
"DicomFilter": os.path.join(APPDATA_DIR, "quarantine", "DicomFilter"),
"DicomDecompressor": os.path.join(APPDATA_DIR, "quarantine", "DicomDecompressor"),
"DicomAnonymizer": os.path.join(APPDATA_DIR, "quarantine", "DicomAnonymizer"),
"DirectoryStorageService": os.path.join(APPDATA_DIR, "quarantine", "DirectoryStorageService")
}
with open(log_path, "w") as f:
f.write("Stage,Filename,Path\n")
for stage, quarantine_path in quarantine_dirs.items():
if os.path.exists(quarantine_path):
for root, dirs, filenames in os.walk(quarantine_path):
for filename in filenames:
if not filename.startswith('.') and filename not in ['QuarantineIndex.db', 'QuarantineIndex.lg']:
file_path = os.path.join(root, filename)
f.write(f"{stage},{filename},{file_path}\n")
logging.info(f"Quarantined files log saved to {log_path}")
def save_linker_csv():
linker_csv = ctp_post("idmap", {"p": 0, "s": 4, "keytype": "trialAN", "keys": "", "format": "csv"})
with open(os.path.join(APPDATA_DIR, "linker.csv"), "w") as f:
f.write(linker_csv)
def scrub(data, whitelist, blacklist):
try:
analyzer = create_analyzer_engine()
anonymizer = AnonymizerEngine()
medical_terms_deny_list = {
'cardiomediastinal', 'ventricles', 'medullaris', 'conus', 'calvarium',
'paraspinal', 'mediastinum', 'pleura', 'parenchyma', 'foramina',
'mucosal', 'multiplanar', 'heterogeneously', 'schmorl',
'md', 'pneumonia', 'pneumothorax', 'effusion', 'opacity',
'consolidation', 'calcification', 'abnormality', 'silhouette',
'technique', 'ap', 'lateral', 'ct', 'mri', 'radiograph', 'examination',
'copd', 'emg', 'npi', 'acr', 'lmp', 'afi',
'hu', 'ed', 'npo', 'iv', 'or', 'er', 'icu', 'po', 'im', 'sc',
'degrees', 'cm', 'mm', 'ml'
}
medical_person_deny_list = {
'ventricles', 'mucosal', 'multiplanar', 'schmorl', 'medullaris', 'conus',
'standard', 'g2p1', 'referring',
'son', 'daughter', 'wife', 'husband', 'mother', 'father', 'parent',
'pine', 'cedar', 'oak', 'maple',
'diverticulosis', 'diverticulitis'
}
if whitelist:
medical_terms_deny_list.update(whitelist)
medical_person_deny_list.update(whitelist)
for item in blacklist:
blacklist_recognizer = PatternRecognizer(
supported_entity="CUSTOM_BLACKLIST",
name=f"blacklist_{hash(item)}",
patterns=[Pattern(name=f"blacklist_pattern_{hash(item)}", regex=re.escape(item), score=0.95)],
)
analyzer.registry.add_recognizer(blacklist_recognizer)
entities_to_detect = [
"PERSON", "DATE_TIME", "MRN", "ALPHANUMERIC_ID", "PHONE_NUMBER",
"EMAIL_ADDRESS", "LOCATION", "US_SSN", "MEDICAL_LICENSE",
"US_DRIVER_LICENSE", "US_PASSPORT", "CREDIT_CARD", "US_ITIN",
"NRP", "IBAN_CODE", "CUSTOM_BLACKLIST"
]
alphanumeric_date_pattern = re.compile(r'\b\d{4}-\d{2}-\d{2}\b')
age_pattern = re.compile(r'\b\d{1,3}[-\s]year[-\s]old\b', re.IGNORECASE)
duration_pattern = re.compile(r'\b\d{1,3}\s+(weeks?|months?|days?|hours?|minutes?|seconds?|mins?|secs?)\b', re.IGNORECASE)
time_pattern = re.compile(r'\b\d{1,2}:\d{2}(\s*[AP]M)?\b', re.IGNORECASE)
gestational_age_pattern = re.compile(r'\b\d{1,2}\s*weeks?\s*\d*\s*days?\b', re.IGNORECASE)
time_reference_pattern = re.compile(r'\b(midnight|noon|morning|evening|afternoon)\b', re.IGNORECASE)
complex_age_pattern = re.compile(r'\b\d{1,3}\s+years?,\s*\d{1,2}\s+(months?|days?)\s+old\b', re.IGNORECASE)
operators = {
"PERSON": OperatorConfig("replace", {"new_value": "[PERSONALNAME]"}),
"DATE_TIME": OperatorConfig("replace", {"new_value": "[DATE]"}),
"MRN": OperatorConfig("replace", {"new_value": "[MRN]"}),
"ALPHANUMERIC_ID": OperatorConfig("replace", {"new_value": "[ALPHANUMERICID]"}),
"PHONE_NUMBER": OperatorConfig("replace", {"new_value": "[PHONE]"}),
"EMAIL_ADDRESS": OperatorConfig("replace", {"new_value": "[EMAIL]"}),
"LOCATION": OperatorConfig("replace", {"new_value": "[LOCATION]"}),
"US_SSN": OperatorConfig("replace", {"new_value": "[SSN]"}),
"MEDICAL_LICENSE": OperatorConfig("replace", {"new_value": "[MEDICALID]"}),
"US_DRIVER_LICENSE": OperatorConfig("replace", {"new_value": "[DRIVERSLICENSE]"}),
"US_PASSPORT": OperatorConfig("replace", {"new_value": "[PASSPORT]"}),
"CREDIT_CARD": OperatorConfig("replace", {"new_value": "[CREDITCARD]"}),
"US_ITIN": OperatorConfig("replace", {"new_value": "[ITIN]"}),
"NRP": OperatorConfig("replace", {"new_value": "[NRP]"}),
"IBAN_CODE": OperatorConfig("replace", {"new_value": "[IBAN]"}),
"CUSTOM_BLACKLIST": OperatorConfig("replace", {"new_value": "[REDACTED]"}),
}
results = []
for i, text_item in enumerate(data):
text = str(text_item) if text_item is not None else "Empty"
text = ''.join(c for c in text if c in string.printable)
results_analysis = analyzer.analyze(
text=text,
entities=entities_to_detect,
language='en',
score_threshold=0.5
)
filtered_results = []
for result in results_analysis:
detected_text = text[result.start:result.end]
detected_lower = detected_text.lower()
if result.entity_type == "LOCATION":
if detected_lower in medical_terms_deny_list:
continue
if result.entity_type == "PERSON":
if detected_lower in medical_person_deny_list:
continue
if result.entity_type == "DATE_TIME":
if alphanumeric_date_pattern.match(detected_text):
continue
if age_pattern.search(detected_text):
continue
if complex_age_pattern.search(detected_text):
continue
if duration_pattern.search(detected_text):
continue
if time_pattern.match(detected_text):
continue
if gestational_age_pattern.match(detected_text):
continue
if time_reference_pattern.search(detected_text):
continue
filtered_results.append(result)
filtered_results = sorted(filtered_results, key=lambda x: x.start)
anonymized_result = anonymizer.anonymize(
text=text,
analyzer_results=filtered_results,
operators=operators
)
results.append(anonymized_result.text)
print_and_log(f"PROGRESS: {i+1}/{len(data)} rows de-identified")
return results
except Exception as e:
error_msg = f"Error in scrub function: {str(e)}"
logging.error(error_msg)
raise Exception(error_msg)
def date_shift_text(original_list, deided_list, date_shift_by):
shifted_list = []
for i, (original, deided) in enumerate(zip(original_list, deided_list)):
dates = []
for d_line, o_line in zip(deided.split('\n'), original.split('\n')):
pos = 0
while '[DATE]' in d_line[pos:]:
pos = d_line.find('[DATE]', pos)
context = o_line[max(0,pos-30):min(len(o_line),pos+35)]
for word in context.split():
for fmt in COMMON_DATE_FORMATS:
try:
datetime.strptime(word, fmt)
dates.append(word)
break
except ValueError:
continue
else:
continue
break
pos += 1
result = deided
for date in dates:
shifted = datetime.strptime(date, '%m/%d/%Y') + timedelta(days=date_shift_by)
result = result.replace('[DATE]', shifted.strftime('%m/%d/%Y'), 1)
shifted_list.append(result)
print_and_log(f"PROGRESS: {i+1}/{len(original_list)} rows date shifted")
return shifted_list
def format_ctp_filter(filter_expr):
"""Format CTP filter expression for better readability"""
if not filter_expr:
return ""
# Replace * with AND and + with OR
formatted = filter_expr.replace(" * ", " AND ")
formatted = formatted.replace(" + ", " OR ")
# Split on OR that's between major patient conditions (not inside parens)
# Find OR that separates PatientID conditions
import re
# Split by ") OR (" pattern which separates patient conditions
parts = re.split(r'\) OR \((?=PatientID)', formatted)
if len(parts) > 1:
# Reconstruct with newlines between patient conditions
result = []
for i, part in enumerate(parts):
if i == 0:
result.append(part + ")")
elif i == len(parts) - 1:
result.append("\nOR (" + part)
else:
result.append("\nOR (" + part + ")")
return ''.join(result)
else:
# No split needed, just return with operators replaced
return formatted
def imageqr_func(_):
save_metadata_csv()
def imageqr_main(**config):
def setup_config(temp_ctp_dir):
# Log filter generation details
logging.info("\n" + "="*80)
logging.info("CTP FILTER GENERATION")
logging.info("="*80)
generated_filter = generate_series_date_filter(config)
user_filter = config.get("ctp_filters")
combined_filter = get_combined_ctp_filter(config)
if generated_filter:
logging.info("Generated Series/Date Filter:")