-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfull_anonymizer.py
More file actions
3295 lines (2836 loc) · 130 KB
/
Copy pathfull_anonymizer.py
File metadata and controls
3295 lines (2836 loc) · 130 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
"""
匿名化ツール (Full Anonymizer)
機能:
- フォルダ D&D → フォルダ名/ファイル名/テキスト内容/DICOMタグ を一括匿名化
- Feistel暗号化モード / 対応表作成モード
- 全設定を SEED.conf に一元管理 (exe化対応)
暗号方式:
Feistel cipher (PBKDF2-SHA256 鍵導出 + HMAC-SHA256 ラウンド関数, 16 rounds)
※ ID桁数=7, 接頭辞=K の場合、ID-Anonymizer.ps1 と完全互換
暗号化SEED値・設定:
同じフォルダ内の SEED.conf に暗号化SEED値と設定が保存されます。
SEED値を変更すると、全く異なる匿名化結果になります。
"""
import os
import sys
import json
import math
import hmac
import hashlib
import struct
import shutil
import re
import secrets
import string
import csv
import zipfile
import queue
import threading
import tkinter as tk
from tkinter import filedialog, messagebox
from pathlib import Path
from datetime import datetime
import xml.etree.ElementTree as ET
try:
import customtkinter as ctk
except ImportError:
print("customtkinter が必要です: pip install customtkinter")
sys.exit(1)
try:
import windnd
HAS_WINDND = True
except ImportError:
HAS_WINDND = False
try:
import pydicom
HAS_PYDICOM = True
except ImportError:
HAS_PYDICOM = False
try:
import openpyxl
HAS_OPENPYXL = True
except ImportError:
HAS_OPENPYXL = False
# ============================================================
# 暗号化SEED値 読み込み / 生成 / 保存
# ============================================================
# exe化対応: frozen時は exe の場所、通常時は .py の場所
if getattr(sys, 'frozen', False):
_APP_DIR = Path(os.path.dirname(sys.executable))
else:
_APP_DIR = Path(os.path.dirname(os.path.abspath(__file__)))
_SEED_FILE = _APP_DIR / "SEED.conf"
_PW_GEN_LENGTH = 20 # 自動生成SEED値の長さ (英大小+数字+記号 → ~131 bit)
def _load_password_file() -> tuple:
"""SEED.conf から暗号化SEED値・メモ・設定を読み込む。
Returns: (password, memo, settings_dict)
"""
if not _SEED_FILE.exists():
return "", "", {}
try:
text = _SEED_FILE.read_text(encoding="utf-8")
except Exception:
return "", "", {}
lines = text.split("\n")
password = lines[0].strip() if lines else ""
memo_parts = []
settings = {}
current_section = None
for line in lines[1:]:
stripped = line.strip()
if stripped.startswith("# メモ:"):
memo_parts.append(stripped[len("# メモ:"):].strip())
elif stripped.startswith("[") and stripped.endswith("]"):
current_section = stripped[1:-1]
settings[current_section] = {}
elif current_section and "=" in stripped and not stripped.startswith("#"):
key, _, value = stripped.partition("=")
settings[current_section][key.strip()] = value.strip()
return password, "\n".join(memo_parts), settings
def _generate_password(length: int = _PW_GEN_LENGTH) -> str:
"""暗号学的に安全なランダムSEED値を生成"""
alphabet = string.ascii_letters + string.digits + "!@#$%&*+-=?"
while True:
pw = "".join(secrets.choice(alphabet) for _ in range(length))
# 全文字種が含まれることを保証
if (re.search(r"[a-z]", pw) and re.search(r"[A-Z]", pw)
and re.search(r"[0-9]", pw) and re.search(r"[^a-zA-Z0-9]", pw)):
return pw
def _save_password_file(password: str, memo: str = "", settings: dict = None) -> Path:
"""SEED.conf に暗号化SEED値 + メタデータ + 全設定を保存"""
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
lines = [password, ""]
lines.append(f"# 作成日時: {ts}")
if memo.strip():
for line in memo.strip().splitlines():
lines.append(f"# メモ: {line}")
lines.append("")
lines.append("# --- 1行目が暗号化SEED値です ---")
lines.append("# SEED値を変更すると過去の匿名化結果とは異なる結果になります")
lines.append("# このファイルは匿名化データと一緒に配布しないでください")
if settings:
for section, kvs in settings.items():
lines.append("")
lines.append(f"[{section}]")
for k, v in kvs.items():
lines.append(f"{k} = {v}")
lines.append("")
_SEED_FILE.write_text("\n".join(lines), encoding="utf-8")
return _SEED_FILE
SEED, _LOADED_MEMO, _LOADED_SETTINGS = _load_password_file()
# SEED値強度の最低ライン (ビット)
# PBKDF2 100k回 × 高性能GPU 100万回/秒 × 100年 ≒ 2^71.5
# 余裕をもって 72 bit 以上を要求
MIN_ENTROPY_BITS = 72
# 攻撃想定: PBKDF2-100k を GPU 並列で毎秒 100 万回試行
ATTACK_RATE = 1_000_000
def _estimate_entropy(password: str) -> float:
"""使用文字種からエントロピー (bit) を推定"""
if not password:
return 0.0
pool = 0
if re.search(r"[a-z]", password):
pool += 26
if re.search(r"[A-Z]", password):
pool += 26
if re.search(r"[0-9]", password):
pool += 10
if re.search(r"[^a-zA-Z0-9]", password):
pool += 33
if pool == 0:
pool = 1
return len(password) * math.log2(pool)
def _crack_time_display(entropy: float) -> str:
"""推定解読時間を人間向け文字列で返す"""
if entropy <= 0:
return "即座"
seconds = (2 ** entropy) / ATTACK_RATE
years = seconds / (365.25 * 86400)
if years < 1:
return f"約 {seconds / 3600:.0f} 時間"
if years < 1000:
return f"約 {years:.0f} 年"
exp = int(math.log10(years))
return f"約 10^{exp} 年"
def _password_guidance() -> str:
"""必要文字数のガイダンス文字列を返す"""
examples = []
for label, pool in [("英小文字のみ", 26), ("英大小+数字", 62), ("英大小+数字+記号", 95)]:
need = math.ceil(MIN_ENTROPY_BITS / math.log2(pool))
examples.append(f" {label}: {need}文字以上")
return "\n".join(examples)
# ============================================================
# ============================================================
# Feistel cipher コア (ID-Anonymizer.ps1 と同一アルゴリズム)
# ============================================================
FEISTEL_ROUNDS = 16
def get_cipher_params(id_digits: int) -> tuple:
"""(half_mod, output_digits) を返す"""
if id_digits <= 6:
return 1000, 6 # block = 1,000,000 (5〜6桁をカバー)
else:
return 10000, 8 # block = 100,000,000 (7〜8桁をカバー)
def derive_key(seed: str) -> bytes:
"""PBKDF2-SHA256 でシードから 256bit キーを導出"""
salt = b"ID-Anonymizer-SFRT-v1-Salt"
return hashlib.pbkdf2_hmac(
"sha256", seed.encode("utf-8"), salt, 100000, dklen=32
)
def _feistel_f(half: int, round_num: int, key: bytes, half_mod: int) -> int:
data = f"{round_num}|{half}".encode("utf-8")
h = hmac.new(key, data, hashlib.sha256).digest()
return struct.unpack_from("<I", h)[0] % half_mod
def protect_id(plain_id: str, key: bytes, id_digits: int = 7, prefix: str = "K") -> str:
"""N桁 ID → prefix+M桁 匿名化 ID"""
half_mod, out_digits = get_cipher_params(id_digits)
max_val = half_mod * half_mod - 1
num = int(plain_id)
if num < 0 or num > max_val:
raise ValueError(f"ID は 0〜{max_val} の範囲")
left, right = divmod(num, half_mod)
for r in range(FEISTEL_ROUNDS):
f = _feistel_f(right, r, key, half_mod)
left, right = right, (left + f) % half_mod
return f"{prefix}{left * half_mod + right:0{out_digits}d}"
def unprotect_id(cipher_id: str, key: bytes, id_digits: int = 7, prefix: str = "K") -> str:
"""prefix+M桁 匿名化 ID → N桁 ID"""
half_mod, out_digits = get_cipher_params(id_digits)
max_val = half_mod * half_mod - 1
stripped = cipher_id.strip()
if prefix and stripped.startswith(prefix):
stripped = stripped[len(prefix):]
elif prefix and stripped.lower().startswith(prefix.lower()):
stripped = stripped[len(prefix):]
num = int(stripped)
if num < 0 or num > max_val:
raise ValueError("不正な匿名化ID")
left, right = divmod(num, half_mod)
for r in range(FEISTEL_ROUNDS - 1, -1, -1):
f = _feistel_f(left, r, key, half_mod)
left, right = (right - f) % half_mod, left
return f"{left * half_mod + right:0{id_digits}d}"
# ============================================================
# 定数
# ============================================================
DEFAULT_DICOM_TAGS = {
"PatientName": ("患者名", "{id}"),
"PatientID": ("患者ID", "{id}"),
"PatientBirthDate": ("生年月日", ""),
"PatientSex": ("患者性別", ""),
"StudyDate": ("検査日", ""),
"SeriesDate": ("シリーズ日", ""),
"AcquisitionDate": ("収集日", ""),
"ContentDate": ("コンテンツ日", ""),
"AccessionNumber": ("アクセッション番号", ""),
"InstitutionName": ("施設名", ""),
"Manufacturer": ("製造元", ""),
"ReferringPhysicianName": ("紹介医", ""),
"OperatorsName": ("操作者名", ""),
"StudyDescription": ("検査説明", ""),
"SeriesDescription": ("シリーズ説明", ""),
}
TEXT_EXTS = {".csv", ".txt", ".tsv", ".log", ".ini", ".yaml", ".yml", ".toml", ".bin"}
RICH_EXTS = {".json", ".xml"}
XLSX_EXT = ".xlsx"
OOXML_EXTS = {".docx", ".pptx"}
MAPPING_CSV = "_対応表.csv"
# 親DIR直下ファイル: 名前列検出キーワード (正規化後: 小文字, 区切り除去)
_NAME_KW_STRONG = ('患者名', 'patientname', '被験者名', '対象者名',
'氏名', '名前', '姓名')
_NAME_KW_MEDIUM = ('lastname', 'firstname', 'familyname', 'givenname',
'カナ', 'フリガナ', 'ふりがな', 'ローマ字', 'romaji', 'kana')
_NAME_KW_EXACT = frozenset({'姓', '名', 'name', 'last', 'first'})
# ID列: ヘッダ不要、値ベースで既知IDとの一致率 + 日付除外 で判定
_DATE_YYYYMMDD = re.compile(
r'^(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])$')
_DATE_SERIAL_MAX = 73000 # Excel日付シリアル上限 (~2100年)
OUT_APP = "app"
OUT_ORIG = "orig"
OUT_CUSTOM = "custom"
# カラーパレット
CLR_ACCENT = ("#3B82F6", "#60A5FA") # アクセントカラー
CLR_SUCCESS = ("#22C55E", "#4ADE80") # 成功
CLR_PROCESSING = ("#F59E0B", "#FBBF24") # 処理中
# ゾーンカラー
CLR_LEFT_BG = ("#EDF2FB", "#1A2540") # 左ゾーン背景 (淡い青)
CLR_LEFT_BORDER = ("#B8CCE5", "#3A4F6F") # 左ゾーン枠
CLR_RIGHT_BG = ("#F2EDF8", "#251A40") # 右ゾーン背景 (淡い紫)
CLR_RIGHT_BORDER = ("#C5B8E5", "#4F3A6F") # 右ゾーン枠
CLR_ZONE_SELECTED_BG = ("#DBEAFE", "#1E3A5F") # 選択時の青背景
CLR_DONE_BG = ("#DCFCE7", "#14532D") # 完了時の緑背景
CLR_ARROW_DISABLED = ("#D1D5DB", "#374151") # 矢印無効色
CLR_CENTER_BG = ("#F8F9FB", "#1E2030") # 中央ゾーン背景
ICON_LOCK_OPEN = "\U0001F513" # 🔓
ICON_LOCK_CLOSED = "\U0001F512" # 🔒
ICON_ARROW_RIGHT = "\u27A1" # ➡
ICON_ARROW_LEFT = "\u2B05" # ⬅
# ============================================================
# 暗号化SEED値 作成ダイアログ
# ============================================================
class PasswordDialog(ctk.CTkToplevel):
def __init__(self, parent, on_saved=None):
super().__init__(parent)
self.title("暗号化SEED値 新規作成")
self.geometry("520x400")
self.transient(parent)
self.grab_set()
self.on_saved = on_saved
self.after(100, self.lift)
# 説明
ctk.CTkLabel(
self,
text="暗号化SEED値を自動生成します。\n"
"生成されたSEED値は SEED.conf に保存されます。",
font=("", 12), justify="left"
).pack(anchor="w", padx=20, pady=(15, 5))
# 警告
ctk.CTkLabel(
self,
text="* SEED値を変更すると、過去の匿名化結果とは異なる結果になります\n"
"* SEED.conf を匿名化データと一緒に配布しないでください",
font=("", 11), text_color="orange", justify="left"
).pack(anchor="w", padx=20, pady=(0, 10))
# SEED値表示
pw_frame = ctk.CTkFrame(self, fg_color="transparent")
pw_frame.pack(fill="x", padx=20)
ctk.CTkLabel(pw_frame, text="暗号化SEED値:", font=("", 12)).pack(anchor="w")
pw_row = ctk.CTkFrame(pw_frame, fg_color="transparent")
pw_row.pack(fill="x", pady=(2, 0))
self.pw_var = tk.StringVar(value=_generate_password())
self.pw_entry = ctk.CTkEntry(
pw_row, textvariable=self.pw_var, width=340,
font=("Consolas", 13)
)
self.pw_entry.pack(side="left")
ctk.CTkButton(
pw_row, text="再生成", width=70,
fg_color="gray", hover_color="#555",
command=self._regenerate
).pack(side="left", padx=(8, 0))
# 強度表示
self.strength_label = ctk.CTkLabel(
self, text="", font=("", 11), anchor="w"
)
self.strength_label.pack(fill="x", padx=20, pady=(4, 8))
self._update_strength()
self.pw_var.trace_add("write", lambda *_: self._update_strength())
# メモ
memo_frame = ctk.CTkFrame(self, fg_color="transparent")
memo_frame.pack(fill="x", padx=20)
ctk.CTkLabel(memo_frame, text="メモ (任意):", font=("", 12)).pack(anchor="w")
self.memo_box = ctk.CTkTextbox(memo_frame, height=80, font=("", 11))
self.memo_box.pack(fill="x", pady=(2, 0))
# ボタン
btn_row = ctk.CTkFrame(self, fg_color="transparent")
btn_row.pack(fill="x", padx=20, pady=15)
ctk.CTkButton(
btn_row, text="保存して適用", width=140,
command=self._save
).pack(side="left")
ctk.CTkButton(
btn_row, text="キャンセル", width=100,
fg_color="gray", hover_color="#555",
command=self.destroy
).pack(side="right")
def _regenerate(self):
self.pw_var.set(_generate_password())
def _update_strength(self):
pw = self.pw_var.get()
ent = _estimate_entropy(pw)
crack = _crack_time_display(ent)
if ent >= MIN_ENTROPY_BITS:
self.strength_label.configure(
text=f"強度: {ent:.0f} bit / 推定解読時間: {crack}",
text_color="green"
)
else:
self.strength_label.configure(
text=f"強度: {ent:.0f} bit / 推定解読時間: {crack} (不足)",
text_color="red"
)
def _save(self):
pw = self.pw_var.get().strip()
if not pw:
messagebox.showerror("エラー", "SEED値が空です", parent=self)
return
ent = _estimate_entropy(pw)
if ent < MIN_ENTROPY_BITS:
if not messagebox.askyesno(
"強度不足",
f"SEED値の強度が {ent:.0f} bit で基準 ({MIN_ENTROPY_BITS} bit) を下回っています。\n"
"このまま保存しますか?",
parent=self
):
return
memo = self.memo_box.get("1.0", "end").strip()
# 親ウィンドウから現在の設定を収集して一緒に保存
settings = None
if hasattr(self.master, "_collect_settings"):
settings = self.master._collect_settings()
_save_password_file(pw, memo, settings)
global SEED
SEED = pw
if self.on_saved:
self.on_saved(pw)
messagebox.showinfo(
"保存完了",
f"SEED.conf に保存しました。\n\n"
f"場所: {_SEED_FILE}\n"
f"強度: {ent:.0f} bit / 推定解読時間: {_crack_time_display(ent)}",
parent=self
)
self.destroy()
# ============================================================
# DICOM 詳細設定ダイアログ
# ============================================================
class DicomSettingsDialog(ctk.CTkToplevel):
def __init__(self, parent, tag_vars, tag_entries):
super().__init__(parent)
self.title("DICOM 匿名化 詳細設定")
self.geometry("580x540")
self.transient(parent)
self.grab_set()
self.after(100, self.lift)
ctk.CTkLabel(
self, text="{id} は匿名化 ID に自動置換されます",
font=("", 11), text_color="gray"
).pack(anchor="w", padx=15, pady=(10, 5))
scroll = ctk.CTkScrollableFrame(self, height=420)
scroll.pack(fill="both", expand=True, padx=10, pady=5)
for tag_name, (display, _) in DEFAULT_DICOM_TAGS.items():
row = ctk.CTkFrame(scroll, fg_color="transparent")
row.pack(fill="x", pady=2)
ctk.CTkCheckBox(
row, text=f"{display} ({tag_name})",
variable=tag_vars[tag_name], width=320,
onvalue=True, offvalue=False
).pack(side="left")
ctk.CTkEntry(
row, textvariable=tag_entries[tag_name], width=150
).pack(side="right", padx=5)
ctk.CTkButton(self, text="閉じる", width=100,
command=self.destroy).pack(pady=10)
# ============================================================
# シナリオB用: 新規ID割当方法ダイアログ
# ============================================================
class NewIdAssignDialog(ctk.CTkToplevel):
"""既存対応表がある場合に新規IDの割当方法を選択するダイアログ"""
def __init__(self, parent, existing_count, new_count, next_preview, current_template):
super().__init__(parent)
self.title("新規IDの割当方法")
self.geometry("440x300")
self.transient(parent)
self.grab_set()
self.result = None # "continue" / "change" / None(cancel)
self.new_template = None
self.after(100, self.lift)
ctk.CTkLabel(
self, text=f"既存対応表: {existing_count} 件\n新規ID: {new_count} 件",
font=("", 13), justify="left"
).pack(anchor="w", padx=20, pady=(15, 10))
self._choice = tk.StringVar(value="continue")
ctk.CTkRadioButton(
self, text=f"同じパターンで続行 (次: {next_preview}〜)",
variable=self._choice, value="continue",
command=self._on_choice
).pack(anchor="w", padx=20, pady=(5, 2))
ctk.CTkRadioButton(
self, text="ヘッダーテキストを変更",
variable=self._choice, value="change",
command=self._on_choice
).pack(anchor="w", padx=20, pady=(2, 2))
self._tmpl_var = tk.StringVar(value=current_template)
self._tmpl_entry = ctk.CTkEntry(
self, textvariable=self._tmpl_var, width=300,
placeholder_text="新しいテンプレート例: KMS_{0001}_aaa"
)
self._tmpl_entry.pack(anchor="w", padx=40, pady=(2, 10))
self._tmpl_entry.configure(state="disabled")
btn_row = ctk.CTkFrame(self, fg_color="transparent")
btn_row.pack(fill="x", padx=20, pady=15)
ctk.CTkButton(
btn_row, text="OK", width=120, command=self._ok
).pack(side="left")
ctk.CTkButton(
btn_row, text="キャンセル", width=100,
fg_color="gray", hover_color="#555", command=self._cancel
).pack(side="right")
self.protocol("WM_DELETE_WINDOW", self._cancel)
def _on_choice(self):
if self._choice.get() == "change":
self._tmpl_entry.configure(state="normal")
else:
self._tmpl_entry.configure(state="disabled")
def _ok(self):
if self._choice.get() == "change":
self.result = "change"
self.new_template = self._tmpl_var.get().strip()
if not self.new_template:
messagebox.showerror("エラー", "テンプレートを入力してください", parent=self)
return
else:
self.result = "continue"
self.grab_release()
self.destroy()
def _cancel(self):
self.result = None
self.grab_release()
self.destroy()
# ============================================================
# メインアプリケーション
# ============================================================
class AnonymizerApp(ctk.CTk):
def __init__(self):
super().__init__()
ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")
self.title("匿名化ツール")
self.geometry("480x290")
self.resizable(True, True)
if not SEED:
self.after(200, lambda: messagebox.showwarning(
"暗号化SEED値 未設定",
"SEED.conf が見つからないか空です。\n"
"アプリと同じフォルダに SEED.conf を作成し、\n"
"暗号化SEED値を記入してください。\n\n"
"【必要な文字数の目安】\n" + _password_guidance()
))
elif _estimate_entropy(SEED) < MIN_ENTROPY_BITS:
ent = _estimate_entropy(SEED)
crack = _crack_time_display(ent)
self.after(200, lambda: messagebox.showwarning(
"暗号化SEED値が短すぎます",
f"現在のSEED値の強度: {ent:.0f} bit\n"
f"推定解読時間: {crack}\n"
f"(必要強度: {MIN_ENTROPY_BITS} bit 以上 = 100年以上)\n\n"
"【必要な文字数の目安】\n" + _password_guidance() + "\n\n"
"SEED.conf のSEED値を変更してください。"
))
self.key = derive_key(SEED)
self.processing = False
self.last_output_dir = None
# 双方向ドロップゾーン状態
self._ui_state = "idle"
self._left_path = None # 左に選択されたフォルダ
self._right_path = None # 右に選択されたフォルダ
self._left_output_dir = None # 復元結果の出力先
self._right_output_dir = None # 匿名化結果の出力先
self._single_id_filter = None # 単独IDフォルダ名 (例: "1234567_CT")
# スレッドセーフなコールバックキュー
self._callback_queue = queue.Queue()
# DICOM タグ設定
self.tag_vars = {}
self.tag_entries = {}
for tag_name, (_, default) in DEFAULT_DICOM_TAGS.items():
self.tag_vars[tag_name] = tk.BooleanVar(value=True)
self.tag_entries[tag_name] = tk.StringVar(value=default)
self._build_ui()
self._setup_dnd()
self._poll_callback_queue() # キューポーリング開始
# SEED.conf から設定を復元
if _LOADED_SETTINGS:
self._apply_settings(_LOADED_SETTINGS)
# --------------------------------------------------------
# 設定の収集 / 適用 / 保存
# --------------------------------------------------------
def _collect_settings(self) -> dict:
"""現在のGUI設定を辞書に収集"""
settings = {
"anonymization": {
"id_digits": self.id_digits.get(),
"anon_mode": self.anon_mode.get(),
"prefix": self.prefix.get(),
"simple_text": self.simple_text.get(),
"dicom_replace_text": self.dicom_replace_text.get(),
},
"options": {
"opt_rename": str(self.opt_rename.get()).lower(),
"opt_text": str(self.opt_text.get()).lower(),
"opt_dicom": str(self.opt_dicom.get()).lower(),
},
"output": {
"output_mode": self.output_mode.get(),
"custom_dir": self.custom_dir.get(),
},
"dicom_tags": {},
}
for tag_name in DEFAULT_DICOM_TAGS:
enabled = str(self.tag_vars[tag_name].get()).lower()
value = self.tag_entries[tag_name].get()
settings["dicom_tags"][tag_name] = f"{enabled}|{value}"
return settings
def _apply_settings(self, settings: dict):
"""辞書からGUI設定を復元"""
anon = settings.get("anonymization", {})
if "id_digits" in anon and anon["id_digits"] in ("5", "6", "7", "8"):
self.id_digits.set(anon["id_digits"])
if "anon_mode" in anon and anon["anon_mode"] in ("feistel", "simple", "dicom_only"):
self.anon_mode.set(anon["anon_mode"])
if "prefix" in anon:
self.prefix.set(anon["prefix"])
if "simple_text" in anon:
self.simple_text.set(anon["simple_text"])
if "dicom_replace_text" in anon:
self.dicom_replace_text.set(anon["dicom_replace_text"])
opts = settings.get("options", {})
if "opt_rename" in opts:
self.opt_rename.set(opts["opt_rename"] == "true")
if "opt_text" in opts:
self.opt_text.set(opts["opt_text"] == "true")
if "opt_dicom" in opts:
self.opt_dicom.set(opts["opt_dicom"] == "true")
out = settings.get("output", {})
if "output_mode" in out and out["output_mode"] in (OUT_APP, OUT_ORIG, OUT_CUSTOM):
self.output_mode.set(out["output_mode"])
if "custom_dir" in out:
self.custom_dir.set(out["custom_dir"])
dtags = settings.get("dicom_tags", {})
for tag_name, value in dtags.items():
if tag_name in self.tag_vars:
parts = value.split("|", 1)
self.tag_vars[tag_name].set(parts[0] == "true")
if len(parts) > 1:
self.tag_entries[tag_name].set(parts[1])
self._on_mode_change()
def _save_current_settings(self):
"""現在のGUI設定をSEED.confに保存(SEED値は変更しない)"""
if not _SEED_FILE.exists():
return
pw, memo, _ = _load_password_file()
_save_password_file(pw, memo, self._collect_settings())
# --------------------------------------------------------
# UI 構築
# --------------------------------------------------------
def _build_ui(self):
# === ヘッダー ===
header = ctk.CTkFrame(self, fg_color="transparent")
header.pack(fill="x", padx=20, pady=(12, 0))
ctk.CTkLabel(
header, text="匿名化ツール",
font=("", 22, "bold")
).pack(side="left")
# 詳細設定トグル
self._compact = True
self.toggle_btn = ctk.CTkButton(
header, text="▽ 詳細設定", width=90, height=28,
fg_color="transparent", border_width=1,
text_color=CLR_ACCENT, border_color=CLR_ACCENT,
hover_color=("#E0EAFF", "#1E293B"),
command=self._toggle_compact,
font=("", 11),
)
self.toggle_btn.pack(side="right")
if SEED and _SEED_FILE.exists():
# SEED.conf が存在 → 押し込まれた(使用済み)見た目で無効化
self.pw_btn = ctk.CTkButton(
header, text="SEED値 設定済", width=120,
fg_color=("#D1D5DB", "#374151"),
text_color=("#9CA3AF", "#6B7280"),
border_width=0,
hover_color=("#D1D5DB", "#374151"),
state="disabled",
)
else:
# SEED.conf が無い → 飛び出した(未設定)目立つ見た目
self.pw_btn = ctk.CTkButton(
header, text="SEED値 作成", width=120,
fg_color=CLR_ACCENT,
text_color="white",
border_width=2, border_color=CLR_ACCENT,
hover_color=("#2563EB", "#3B82F6"),
command=self._open_password_dialog,
)
self.pw_btn.pack(side="right", padx=(0, 8))
# === Full view wrapper (詳細設定、初期非表示) ===
self._full_frame = ctk.CTkFrame(self, fg_color="transparent")
# === ドロップゾーン (3パネル: 左 | 中央矢印 | 右) ===
drop_container = ctk.CTkFrame(
self._full_frame, height=170, fg_color="transparent",
)
drop_container.pack(fill="x", padx=20, pady=(12, 8))
drop_container.pack_propagate(False)
# --- 左ゾーン (元データ) ---
self.left_zone = ctk.CTkFrame(
drop_container, corner_radius=16,
border_width=2, border_color=CLR_LEFT_BORDER,
fg_color=CLR_LEFT_BG,
)
self.left_zone.pack(side="left", fill="both", expand=True)
left_inner = ctk.CTkFrame(self.left_zone, fg_color="transparent")
left_inner.place(relx=0.5, rely=0.5, anchor="center")
self.left_icon = ctk.CTkLabel(
left_inner, text=ICON_LOCK_OPEN,
font=("Segoe UI Emoji", 36)
)
self.left_icon.pack()
self.left_text = ctk.CTkLabel(
left_inner, text="元データ",
font=("", 13, "bold")
)
self.left_text.pack(pady=(2, 0))
self.left_sub = ctk.CTkLabel(
left_inner, text="クリックして選択",
font=("", 10), text_color="gray"
)
self.left_sub.pack()
for w in [self.left_zone, left_inner, self.left_icon,
self.left_text, self.left_sub]:
w.bind("<Button-1>", lambda e: self._on_left_click())
# --- 中央ゾーン (矢印) ---
self.center_zone = ctk.CTkFrame(
drop_container, width=120, fg_color=CLR_CENTER_BG,
corner_radius=12,
)
self.center_zone.pack(side="left", fill="y", padx=4)
self.center_zone.pack_propagate(False)
center_inner = ctk.CTkFrame(self.center_zone, fg_color="transparent")
center_inner.place(relx=0.5, rely=0.5, anchor="center")
self.arrow_right_btn = ctk.CTkButton(
center_inner, text=ICON_ARROW_RIGHT, width=60, height=40,
font=("", 22), corner_radius=10,
fg_color=CLR_ARROW_DISABLED,
text_color=("gray", "gray"),
hover=False, state="disabled",
command=self._on_arrow_right,
)
self.arrow_right_btn.pack(pady=(0, 8))
self.arrow_left_btn = ctk.CTkButton(
center_inner, text=ICON_ARROW_LEFT, width=60, height=40,
font=("", 22), corner_radius=10,
fg_color=CLR_ARROW_DISABLED,
text_color=("gray", "gray"),
hover=False, state="disabled",
command=self._on_arrow_left,
)
self.arrow_left_btn.pack(pady=(8, 0))
# --- 右ゾーン (匿名化データ) ---
self.right_zone = ctk.CTkFrame(
drop_container, corner_radius=16,
border_width=2, border_color=CLR_RIGHT_BORDER,
fg_color=CLR_RIGHT_BG,
)
self.right_zone.pack(side="left", fill="both", expand=True)
right_inner = ctk.CTkFrame(self.right_zone, fg_color="transparent")
right_inner.place(relx=0.5, rely=0.5, anchor="center")
self.right_icon = ctk.CTkLabel(
right_inner, text=ICON_LOCK_CLOSED,
font=("Segoe UI Emoji", 36)
)
self.right_icon.pack()
self.right_text = ctk.CTkLabel(
right_inner, text="匿名化データ",
font=("", 13, "bold")
)
self.right_text.pack(pady=(2, 0))
self.right_sub = ctk.CTkLabel(
right_inner, text="クリックして選択",
font=("", 10), text_color="gray"
)
self.right_sub.pack()
for w in [self.right_zone, right_inner, self.right_icon,
self.right_text, self.right_sub]:
w.bind("<Button-1>", lambda e: self._on_right_click())
# === 出力先設定 ===
out_section = ctk.CTkFrame(self._full_frame, fg_color="transparent")
out_section.pack(fill="x", padx=20, pady=(0, 4))
ctk.CTkLabel(out_section, text="出力先",
font=("", 14, "bold")).pack(anchor="w")
self.output_mode = tk.StringVar(value=OUT_ORIG)
radio_row = ctk.CTkFrame(out_section, fg_color="transparent")
radio_row.pack(fill="x")
ctk.CTkRadioButton(
radio_row, text="アプリと同じ場所",
variable=self.output_mode, value=OUT_APP
).pack(side="left", padx=(0, 12))
ctk.CTkRadioButton(
radio_row, text="元フォルダと同じ場所",
variable=self.output_mode, value=OUT_ORIG
).pack(side="left", padx=12)
ctk.CTkRadioButton(
radio_row, text="指定した場所",
variable=self.output_mode, value=OUT_CUSTOM
).pack(side="left", padx=12)
custom_row = ctk.CTkFrame(out_section, fg_color="transparent")
custom_row.pack(fill="x", pady=(4, 0))
self.custom_dir = tk.StringVar()
ctk.CTkEntry(
custom_row, textvariable=self.custom_dir, width=300,
placeholder_text="出力先フォルダを選択..."
).pack(side="left")
ctk.CTkButton(
custom_row, text="参照", width=60,
fg_color="gray", hover_color="#555",
command=self._browse_output
).pack(side="left", padx=6)
self.open_btn = ctk.CTkButton(
custom_row, text="出力フォルダを開く", width=140,
state="disabled", command=self._open_output
)
self.open_btn.pack(side="right")
# === 匿名化設定 ===
anon_section = ctk.CTkFrame(self._full_frame, fg_color="transparent")
anon_section.pack(fill="x", padx=20, pady=(4, 4))
ctk.CTkLabel(anon_section, text="匿名化設定",
font=("", 14, "bold")).pack(anchor="w")
# ID桁数
digits_row = ctk.CTkFrame(anon_section, fg_color="transparent")
digits_row.pack(fill="x", pady=2)
ctk.CTkLabel(digits_row, text="ID桁数:", font=("", 12)).pack(side="left")
self.id_digits = tk.StringVar(value="7")
self.digits_seg = ctk.CTkSegmentedButton(
digits_row, values=["5", "6", "7", "8"],
variable=self.id_digits, width=200
)
self.digits_seg.pack(side="left", padx=(8, 0))
# モード選択
mode_row = ctk.CTkFrame(anon_section, fg_color="transparent")
mode_row.pack(fill="x", pady=2)
ctk.CTkLabel(mode_row, text="モード:", font=("", 12)).pack(side="left")
self.anon_mode = tk.StringVar(value="feistel")
ctk.CTkRadioButton(
mode_row, text="Feistel暗号化",
variable=self.anon_mode, value="feistel",
command=self._on_mode_change
).pack(side="left", padx=(8, 12))
ctk.CTkRadioButton(
mode_row, text="対応表作成",
variable=self.anon_mode, value="simple",
command=self._on_mode_change
).pack(side="left", padx=12)
ctk.CTkRadioButton(
mode_row, text="DICOMタグのみ",
variable=self.anon_mode, value="dicom_only",
command=self._on_mode_change
).pack(side="left", padx=12)
# 接頭辞 (Feistelモード用)
self._prefix_row = ctk.CTkFrame(anon_section, fg_color="transparent")
self._prefix_row.pack(fill="x", pady=2)
ctk.CTkLabel(self._prefix_row, text="接頭辞:", font=("", 12)).pack(side="left")
self.prefix = tk.StringVar(value="K")
self.prefix_entry = ctk.CTkEntry(
self._prefix_row, textvariable=self.prefix, width=120
)
self.prefix_entry.pack(side="left", padx=(8, 0))
# 対応表ルール (対応表モード用)
self._simple_row = ctk.CTkFrame(anon_section, fg_color="transparent")
ctk.CTkLabel(self._simple_row, text="対応表ルール:", font=("", 12)).pack(side="left")
self.simple_text = tk.StringVar(value="tokumeika")
self.simple_entry = ctk.CTkEntry(
self._simple_row, textvariable=self.simple_text, width=200,
placeholder_text="例: KMS_{0001}_aaa"
)
self.simple_entry.pack(side="left", padx=(8, 0))
ctk.CTkLabel(
self._simple_row,
text="{0013}で0013,0014,0015...",
font=("", 11), text_color="gray",
).pack(side="left", padx=(8, 0))
# 置換テキスト (DICOMタグのみモード用)
self._dicom_text_row = ctk.CTkFrame(anon_section, fg_color="transparent")
ctk.CTkLabel(self._dicom_text_row, text="置換テキスト:", font=("", 12)).pack(side="left")
self.dicom_replace_text = tk.StringVar(value="anonymous")
ctk.CTkEntry(
self._dicom_text_row, textvariable=self.dicom_replace_text, width=200,
placeholder_text="例: anonymous"
).pack(side="left", padx=(8, 0))
# === 処理オプション ===
opt_section = ctk.CTkFrame(self._full_frame, fg_color="transparent")
opt_section.pack(fill="x", padx=20, pady=(4, 4))
ctk.CTkLabel(opt_section, text="処理オプション",
font=("", 14, "bold")).pack(anchor="w")
opts = ctk.CTkFrame(opt_section, fg_color="transparent")
opts.pack(fill="x")
self.opt_rename = tk.BooleanVar(value=True)
ctk.CTkCheckBox(
opts, text="フォルダ名・ファイル名の ID 置換",
variable=self.opt_rename, onvalue=True, offvalue=False