-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgui.py
More file actions
1434 lines (1223 loc) · 71.9 KB
/
Copy pathgui.py
File metadata and controls
1434 lines (1223 loc) · 71.9 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
"""
gui.py — Tkinter 기반 GUI 메인 파일: TRPGTranslatorApp 클래스와 진입점을 정의한다.
기능별 로직은 Mixin으로 분리되어 있다:
translation_mixin.py — 번역 / 용어집 추출 메서드
image_mixin.py — PDF 이미지 추출 / 이미지 글자 제거 메서드
ccfolia_mixin.py — 코코포리아 룸 이미지 교체 메서드
dialogs.py — 각종 모달 다이얼로그 클래스
"""
import tkinter as tk
import tkinter.font as tkfont
from tkinter import filedialog, messagebox, scrolledtext, ttk, simpledialog
import webbrowser
import threading
import os
import sys
import queue
import re
import math
import shutil
import config
from config import save_settings, load_settings
from translator import configure_genai
from translation_mixin import TranslationMixin
from image_mixin import ImageMixin
from ccfolia_mixin import CcfoliaMixin
# 설정 탭에서 여는 외부 문서
URL_API_KEYS = "https://aistudio.google.com/u/1/api-keys?hl=ko"
URL_PRICING = "https://ai.google.dev/gemini-api/docs/pricing?hl=ko"
# 버튼 색: (평소, 마우스 올렸을 때). 역할별로 색을 고정해 화면 전체가 같은 규칙을 따르게 한다.
# primary 주 동작 / action 보조 실행 / accent 설정·편집 / save 저장 / danger 삭제
# link 외부 링크 / quiet 눈에 덜 띄어야 하는 것
BUTTON_KINDS = {
"primary": ("#2E7D32", "#388E3C"),
"action": ("#455A64", "#55707E"),
"accent": ("#5C6BC0", "#6E78CC"),
"save": ("#EF6C00", "#F57C00"),
"danger": ("#C62828", "#D64545"),
"link": ("#1A73E8", "#3B86EC"),
"quiet": ("#E4E8EB", "#D3D9DE"),
}
# 창 크기. 저장값이 있어도 화면을 넘으면 이 범위로 줄인다 (_apply_window_geometry).
# 세로 940은 '1차 번역 탭이 요구하는 높이(약 740) + 로그 최소 높이'에서 나온 값이다.
# 이보다 낮으면 탭 아래쪽(미리보기 버튼·진행 표시줄)이 잘린다.
DEFAULT_WINDOW_W, DEFAULT_WINDOW_H = 900, 940
MIN_WINDOW_W, MIN_WINDOW_H = 780, 560
# 첫 실행에서 로그 영역에 최소한 남겨줄 높이
MIN_LOG_H = 150
# Pre-compiled regex patterns (kept for backward compatibility / potential local use)
_RE_COLOR_TAG_SPLIT = re.compile(r'(<c=#[0-9a-fA-F]{6}>.*?</c>|<b>.*?</b>)', re.DOTALL)
_RE_COLOR_TAG_STRIP = re.compile(r'<c=#[0-9a-fA-F]{6}>|</c>|<b>|</b>')
_RE_INVALID_FILENAME = re.compile(r'[\\/*?:"<>|]')
# '900x850+120+60' 형태의 Tk geometry 문자열 (위치는 없을 수도 있다)
_RE_GEOMETRY = re.compile(r'^(\d+)x(\d+)(?:\+(-?\d+)\+(-?\d+))?$')
class TRPGTranslatorApp(TranslationMixin, ImageMixin, CcfoliaMixin):
"""TRPG 번역 도구의 메인 애플리케이션 클래스. 각 Mixin에서 기능별 메서드를 상속한다."""
def __init__(self, root):
self.root = root
self.root.title("Japanese TRPG/Murder Mystery Translator v0.8")
# Set Window Icon
try:
# Helper for PyInstaller bundled paths
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# Use image.png for high-res window icon
icon_path = resource_path("image.png")
if os.path.exists(icon_path):
# Using PhotoImage allows PNG usage
icon_img = tk.PhotoImage(file=icon_path)
self.root.iconphoto(False, icon_img)
else:
# Fallback to CWD
local_path = os.path.join(os.getcwd(), "image.png")
if os.path.exists(local_path):
icon_img = tk.PhotoImage(file=local_path)
self.root.iconphoto(False, icon_img)
except Exception as e:
print(f"Failed to load icon: {e}")
# Settings
self.settings = load_settings()
self.api_key_var = tk.StringVar(value=self.settings["api_key"])
self.model_name_var = tk.StringVar(value=self.settings["model_name"])
# 창 크기·위치는 지난번 것을 쓰되 반드시 지금 화면에 맞게 보정한다
self._apply_window_geometry()
# Translation Vars
self.text_dir = tk.StringVar(value=self.settings.get("last_text_dir", ""))
self.image_dir = tk.StringVar(value=self.settings.get("last_image_dir", ""))
self.output_dir = tk.StringVar(value=self.settings.get("last_output_dir", ""))
self.trans_glossary_file = tk.StringVar(value=self.settings.get("last_trans_glossary", ""))
self.refine_enabled = tk.BooleanVar(value=False)
self.docx_output_enabled = tk.BooleanVar(value=False)
self.docx_font_name = tk.StringVar(value=self.settings.get("docx_font_name", "바탕"))
self.docx_remove_headers = tk.BooleanVar(value=False)
self.auto_apply_glossary = tk.BooleanVar(value=True)
# 서식 유지 토글 — 켠 서식만 태그로 실어 나른다. 끄면 입력·출력 토큰이 줄어든다.
self.fmt_bold = tk.BooleanVar(value=self.settings.get("fmt_bold", True))
self.fmt_color = tk.BooleanVar(value=self.settings.get("fmt_color", True))
self.fmt_heading = tk.BooleanVar(value=self.settings.get("fmt_heading", True))
# 원문·번역을 페이지 단위로 나란히 놓은 원문대조 HTML을 함께 만들지
self.bilingual_enabled = tk.BooleanVar(value=self.settings.get("bilingual_enabled", True))
# 용어집 파일이 지정되지 않았을 때 번역 직전에 자동 추출할지 (API 1회 추가)
self.auto_extract_glossary = tk.BooleanVar(value=self.settings.get("auto_extract_glossary", True))
self.resume_enabled = tk.BooleanVar(value=False)
self.auto_open_output = tk.BooleanVar(value=self.settings.get("auto_open_output", False))
self.save_log_enabled = tk.BooleanVar(value=self.settings.get("save_log_enabled", True))
# PDF 이미지 선택 다이얼로그의 최소 크기 필터 (px). 이 값 미만은 목록에서 숨긴다.
self.min_image_size = tk.IntVar(value=self.settings.get("min_image_size", 100))
# PDF 판독 순서 / 이미지 폴백
self.column_mode = tk.StringVar(value=self.settings.get("column_mode", "자동 (컬럼 인식)"))
self.remove_margins = tk.BooleanVar(value=self.settings.get("remove_margins", True))
self.image_fallback_enabled = tk.BooleanVar(value=self.settings.get("image_fallback_enabled", False))
# 블록 안의 줄을 화면 순서로 정렬 (표 한 행이 여러 줄로 잡힐 때 값 순서가 뒤섞이는 것 보정)
self.sort_lines = tk.BooleanVar(value=self.settings.get("sort_lines", True))
# 원문 줄 간격을 보고 문단 경계에 빈 줄을 넣을지 (file_handler.PARA_* 참조)
self.paragraph_breaks = tk.BooleanVar(value=self.settings.get("paragraph_breaks", True))
# 표가 있는 페이지를 이미지 모드 후보로 올릴지
self.detect_tables = tk.BooleanVar(value=self.settings.get("detect_tables", True))
# 번역 결과의 마크다운 표를 DOCX에서 진짜 Word 표로 만들지
self.docx_tables = tk.BooleanVar(value=self.settings.get("docx_tables", True))
# 1M 토큰당 단가(USD). 0이면 요금 추정 없이 토큰 수만 로그에 표시한다.
self.price_input_per_1m = tk.StringVar(value=str(self.settings.get("price_input_per_1m", "0")))
self.price_output_per_1m = tk.StringVar(value=str(self.settings.get("price_output_per_1m", "0")))
# Ccfolia Vars
self.ccfolia_src_dir = tk.StringVar(value=self.settings.get("ccfolia_src_dir", ""))
self.ccfolia_trans_dir = tk.StringVar(value=self.settings.get("ccfolia_trans_dir", ""))
self.ccfolia_output_dir = tk.StringVar(value=self.settings.get("ccfolia_output_dir", ""))
self.ccfolia_match_mode = tk.StringVar(value=self.settings.get("ccfolia_match_mode", "manual"))
self.ccfolia_make_zip = tk.BooleanVar(value=self.settings.get("ccfolia_make_zip", True))
self.ccfolia_api_match = tk.BooleanVar(value=self.settings.get("ccfolia_api_match", False))
self.ccfolia_api_match_model = tk.StringVar(value=self.settings.get("ccfolia_api_match_model", config.DEFAULT_MODEL))
self.ccfolia_translate_memo = tk.BooleanVar(value=self.settings.get("ccfolia_translate_memo", False))
self.ccfolia_glossary_file = tk.StringVar(value=self.settings.get("ccfolia_glossary_file", ""))
# Image Cleaner Vars (v0.5)
self.ic_api_key = tk.StringVar(value=self.settings.get("image_cleaner_api_key", ""))
# 기본값은 config 한 곳에서만 온다 — 문자열을 여기 다시 박으면 config와 어긋난다
# (모델 ID가 settings.json과 config.py에서 갈라졌던 것이 이 때문이었다).
self.ic_model_name = tk.StringVar(value=self.settings.get("image_cleaner_model_name", config.DEFAULT_IMAGE_CLEANER_MODEL))
self.ic_input_dir = tk.StringVar(value=self.settings.get("last_ic_input_dir", ""))
self.ic_output_dir = tk.StringVar(value=self.settings.get("last_ic_output_dir", ""))
self.ic_prompt = tk.StringVar(value=self.settings.get("image_cleaner_prompt", "캐릭터나 그림은 유지하고 글자만 자연스럽게 지워줘"))
self.ic_alpha_enabled = tk.BooleanVar(value=self.settings.get("image_cleaner_alpha_enabled", True))
# UI Element placeholders
self.open_glossary_btn = None
self.auto_apply_check = None
self.last_extracted_glossary = ""
self.msg_queue = queue.Queue()
# Determine UI Font
available_families = tkfont.families()
# Robust search for NanumBarunGothic
found_font = None
for f in available_families:
if "NanumBarunGothic" in f:
found_font = f
break
if found_font:
self.ui_font_family = found_font
else:
# Fallback to hardcoded if not found in list (might still work)
self.ui_font_family = "NanumBarunGothic"
self.create_widgets()
# 경계선 위치는 위젯이 실제로 배치된 뒤에만 먹는다 → 화면이 그려진 다음에 적용
self.root.after_idle(self._restore_sash)
# 창을 닫을 때 크기·경계선 위치를 남긴다 (메인 창의 첫 종료 핸들러다)
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
# Start checking queue
self._queue_job = self.root.after(100, self.process_queue)
def _apply_window_geometry(self):
"""저장된 창 크기·위치를 지금 화면에 맞게 보정해서 적용한다.
모니터마다 해상도와 배율이 달라 저장값을 그대로 쓰면 창이 화면을 넘어가거나
보이지 않는 자리에 뜬다. 화면보다 크면 줄이고, 화면 밖이면 가운데로 되돌린다.
"""
screen_w = self.root.winfo_screenwidth()
screen_h = self.root.winfo_screenheight()
width, height = DEFAULT_WINDOW_W, DEFAULT_WINDOW_H
pos_x = pos_y = None
matched = _RE_GEOMETRY.match(self.settings.get("window_geometry", "") or "")
if matched:
width, height = int(matched.group(1)), int(matched.group(2))
if matched.group(3) is not None:
pos_x, pos_y = int(matched.group(3)), int(matched.group(4))
# 화면을 넘지 않게. 아래는 작업 표시줄 몫으로 조금 더 뺀다.
width = max(MIN_WINDOW_W, min(width, screen_w - 40))
height = max(MIN_WINDOW_H, min(height, screen_h - 80))
# 위치 확인은 '전체 바탕화면'(여러 모니터를 합친 범위) 기준으로 한다.
# 주 모니터 크기로 판단하면 보조 모니터에 둔 창을 매번 끌고 온다.
left, top, virtual_w, virtual_h = self._virtual_screen(screen_w, screen_h)
on_screen = (pos_x is not None
and left - 20 <= pos_x <= left + virtual_w - 100
and top - 20 <= pos_y <= top + virtual_h - 100)
if not on_screen:
pos_x = max(0, (screen_w - width) // 2)
pos_y = max(0, (screen_h - height) // 3)
self.root.geometry(f"{width}x{height}+{pos_x}+{pos_y}")
# 이보다 작아지면 옵션 글자가 잘린다
self.root.minsize(MIN_WINDOW_W, MIN_WINDOW_H)
def _virtual_screen(self, screen_w, screen_h):
"""여러 모니터를 합친 바탕화면 범위 (left, top, width, height)."""
if sys.platform == "win32":
try:
import ctypes
metric = ctypes.windll.user32.GetSystemMetrics
# 76~79: 가상 화면의 좌상단 좌표와 크기
return metric(76), metric(77), metric(78), metric(79)
except Exception:
pass
return 0, 0, screen_w, screen_h
def _restore_sash(self, attempts=20):
"""로그 영역 경계선 위치를 정한다. 저장값이 있으면 그것을, 없으면 탭에 맞춰서.
분할 위젯에 실제 높이가 잡히기 전에 sashpos를 부르면 조용히 무시된다.
(창이 그려지기 전에는 높이가 1이다.) 크기가 잡힐 때까지 잠깐 기다린다.
"""
total = self.paned.winfo_height()
if total <= 1:
if attempts > 0:
self.root.after(50, lambda: self._restore_sash(attempts - 1))
return
pos = self.settings.get("log_sash", 0)
if not pos:
# 첫 실행: 비율(3:1)로 나누면 1차 번역 탭 아래쪽이 잘린다.
# 탭이 요구하는 높이를 먼저 주고, 남는 만큼을 로그에 준다.
need = self.notebook.winfo_reqheight()
pos = min(need, max(total - MIN_LOG_H, total // 2))
try:
self.paned.sashpos(0, int(pos))
except Exception:
# 창보다 큰 값 등은 Tk가 알아서 잘라낸다 — 실패해도 기본 배치면 된다
pass
def _on_close(self):
"""창 크기와 로그 경계선 위치를 저장하고 종료한다."""
try:
state = {"window_geometry": self.root.geometry()}
try:
state["log_sash"] = self.paned.sashpos(0)
except Exception:
pass
# save_settings가 아니라 update_settings를 쓴다 — 저장 버튼을 누르지 않은
# API 키·모델명 입력값까지 파일에 박히면 안 된다.
config.update_settings(**state)
except Exception:
pass
# 예약된 큐 확인을 취소한다 — destroy 뒤에 돌면 Tcl 오류가 찍힌다
try:
if getattr(self, "_queue_job", None):
self.root.after_cancel(self._queue_job)
except Exception:
pass
self.root.destroy()
def _button(self, parent, text, command, kind="action", size=10, bold=True, **kwargs):
"""색·모서리·마우스 반응이 일정한 버튼을 만든다.
버튼마다 색과 굵기를 따로 주면 화면이 제각각으로 보인다. 역할(kind)만 고르면
나머지는 여기서 정해진다.
"""
base, hover = BUTTON_KINDS.get(kind, BUTTON_KINDS["action"])
fg = "#37474F" if kind == "quiet" else "white"
btn = tk.Button(parent, text=text, command=command,
bg=base, fg=fg,
activebackground=hover, activeforeground=fg,
font=(self.ui_font_family, size, "bold" if bold else "normal"),
relief="flat", bd=0, highlightthickness=0,
cursor="hand2", **kwargs)
# 비활성 상태에서는 색을 바꾸지 않는다 (작업 중이라는 표시가 지워지면 안 된다)
def on_enter(_event, b=btn, c=hover):
if str(b["state"]) != "disabled":
b.configure(bg=c)
def on_leave(_event, b=btn, c=base):
if str(b["state"]) != "disabled":
b.configure(bg=c)
btn.bind("<Enter>", on_enter)
btn.bind("<Leave>", on_leave)
return btn
def create_widgets(self):
# ── 창 구성 ──────────────────────────────────────────────────────────
# 푸터를 먼저 pack한다. 늘어나는 위젯(PanedWindow)을 먼저 깔면 아래쪽
# 고정 위젯이 제자리에 못 간다.
footer_font_family = "Arial"
available_fonts = set(tkfont.families(self.root))
for f in ["NanumBarunGothic", "NanumBarunGothic Regular", "나눔바른고딕", "NanumBarunGothicBold"]:
if f in available_fonts:
footer_font_family = f
break
tk.Label(self.root, text="제작자 : 포하", fg="gray",
font=(footer_font_family, 9)).pack(side="bottom", anchor="e", padx=10, pady=5)
# 탭과 로그를 세로 분할에 넣어 경계선을 끌어 높이를 조절할 수 있게 한다.
# 예전에는 둘 다 expand=True로 남은 공간을 나눠 가져서, 탭 내용이 길어지면
# 로그가 밀려 몇 줄만 보였다.
self.paned = ttk.PanedWindow(self.root, orient="vertical")
self.paned.pack(fill="both", expand=True, padx=10, pady=5)
# 1. Notebook for Tabs
self.notebook = ttk.Notebook(self.paned)
self.paned.add(self.notebook, weight=3)
# --- Tab 1: 설정 (Settings) ---
self.tab_settings = tk.Frame(self.notebook)
self.notebook.add(self.tab_settings, text="설정 (Settings)")
# API & Model Settings
sett_frame = tk.LabelFrame(self.tab_settings, text="API 및 모델 설정")
sett_frame.pack(fill="x", padx=10, pady=10)
tk.Label(sett_frame, text="Gemini API Key:", width=15, anchor="w").grid(row=0, column=0, padx=5, pady=5)
key_row = tk.Frame(sett_frame)
key_row.grid(row=0, column=1, sticky="w", padx=5, pady=5)
tk.Entry(key_row, textvariable=self.api_key_var, show="*", width=42).pack(side="left")
self._button(key_row, "키 발급 ↗", lambda: self._open_url(URL_API_KEYS),
kind="link", size=9).pack(side="left", padx=(6, 0), ipadx=6, ipady=2)
tk.Label(sett_frame, text="Model Name:", width=15, anchor="w").grid(row=1, column=0, padx=5, pady=5)
# sticky="w"가 없으면 grid가 칸 안에서 가운데로 밀어 넣어 위아래 입력칸과 왼쪽이 안 맞는다
# (요금 단가 행이 열을 넓혀 놓기 때문에 그 차이만큼 오른쪽으로 밀린다).
tk.Entry(sett_frame, textvariable=self.model_name_var, width=42).grid(
row=1, column=1, sticky="w", padx=5, pady=5)
# 요금 단가 — 입력해두면 번역 완료 시 로그에 예상 요금이 함께 찍힌다.
price_row = tk.Frame(sett_frame)
price_row.grid(row=2, column=1, sticky="w", padx=5, pady=5)
tk.Label(price_row, text="입력 $").pack(side="left")
tk.Entry(price_row, textvariable=self.price_input_per_1m, width=8).pack(side="left", padx=(0, 10))
tk.Label(price_row, text="출력 $").pack(side="left")
tk.Entry(price_row, textvariable=self.price_output_per_1m, width=8).pack(side="left", padx=(0, 10))
tk.Label(price_row, text="(1M 토큰당 · 사용 중인 모델의 공식 단가를 입력하세요. 0이면 토큰만 표시)",
fg="gray", font=(self.ui_font_family, 8)).pack(side="left")
tk.Label(sett_frame, text="요금 단가:", width=15, anchor="w").grid(row=2, column=0, padx=5, pady=5)
# '설정 저장'과 '사용 설명서'는 같은 세로선에 놓는다 — 오른쪽 끝을 맞추고
# 두 버튼의 폭을 같게(width=10) 주면 왼쪽 끝도 저절로 맞는다.
save_row = tk.Frame(sett_frame)
save_row.grid(row=3, column=1, columnspan=2, sticky="e", padx=(5, 10), pady=10)
# 연결 테스트는 count_tokens만 부르므로 생성 토큰을 쓰지 않는다 (사실상 무료).
self.test_conn_btn = self._button(save_row, "연결 테스트", self.test_api_connection,
kind="action", size=9)
self.test_conn_btn.pack(side="left", padx=(0, 8), ipadx=10, ipady=4)
self._button(save_row, "설정 저장", self.save_app_settings,
kind="save", size=9, width=10).pack(side="left", ipady=4)
# User Manual Button
self._button(sett_frame, "사용 설명서", self.open_manual,
kind="action", size=9, width=10).grid(
row=0, column=2, rowspan=2, padx=(5, 10), pady=5, sticky="ne", ipady=6)
# Prompt Settings Button
self._button(sett_frame, "프롬프트 설정", self.open_prompt_editor,
kind="accent", size=9).grid(row=3, column=0, sticky="w",
padx=5, pady=10, ipadx=10, ipady=4)
# ── 자주 쓰는 모델 ───────────────────────────────────────────────────
# 모델명과 단가를 코드에 박지 않는다 — 새 모델이 나오면 바로 낡는다.
# 쓰는 모델만 등록해두고 고르면 모델명과 단가가 한 번에 적용된다.
models_lf = tk.LabelFrame(self.tab_settings, text="자주 쓰는 모델 (Model Presets)")
models_lf.pack(fill="x", padx=10, pady=5)
model_row = tk.Frame(models_lf)
model_row.pack(fill="x", padx=5, pady=6)
tk.Label(model_row, text="모델:", width=8, anchor="w").pack(side="left")
self.model_combo = ttk.Combobox(model_row, width=28, state="readonly")
self.model_combo.pack(side="left", padx=5)
self.model_combo.bind("<<ComboboxSelected>>", self._apply_model_entry)
self._button(model_row, "현재 값으로 저장", self._save_model_entry,
kind="save", size=9, width=13).pack(side="left", padx=3, ipady=3)
self._button(model_row, "삭제", self._delete_model_entry,
kind="danger", size=9, width=5).pack(side="left", padx=3, ipady=3)
self._button(model_row, "공식 단가 ↗", lambda: self._open_url(URL_PRICING),
kind="link", size=9).pack(side="left", padx=(10, 0), ipadx=6, ipady=3)
self.model_hint = tk.Label(models_lf, text="", fg="#777",
font=(self.ui_font_family, 8), anchor="w", justify="left")
self.model_hint.pack(fill="x", padx=10, pady=(0, 6))
self._refresh_model_combo()
# Presets
presets_lf = tk.LabelFrame(self.tab_settings, text="설정 프리셋 (Presets)")
presets_lf.pack(fill="x", padx=10, pady=5)
preset_row = tk.Frame(presets_lf)
preset_row.pack(fill="x", padx=5, pady=6)
tk.Label(preset_row, text="프리셋:", width=8, anchor="w").pack(side="left")
self.preset_combo = ttk.Combobox(preset_row, width=24, state="readonly")
self.preset_combo.pack(side="left", padx=5)
self._refresh_preset_combo()
self._button(preset_row, "불러오기", self._load_preset,
kind="action", size=9, width=8).pack(side="left", padx=3, ipady=3)
self._button(preset_row, "현재 설정 저장", self._save_preset,
kind="save", size=9, width=13).pack(side="left", padx=3, ipady=3)
self._button(preset_row, "삭제", self._delete_preset,
kind="danger", size=9, width=5).pack(side="left", padx=3, ipady=3)
# ── 설정 파일 위치 ───────────────────────────────────────────────────
# 백업·초기화·문제 해결에 쓴다. 경로 상수가 전부 상대 경로라 abspath로 푼다
# (exe로 돌리면 실행 파일이 있는 폴더가 된다).
files_lf = tk.LabelFrame(self.tab_settings, text="설정 파일 위치 (Data Files)")
files_lf.pack(fill="x", padx=10, pady=5)
files_row = tk.Frame(files_lf)
files_row.pack(fill="x", padx=5, pady=6)
self._button(files_row, "폴더 열기", self._open_config_folder,
kind="action", size=9, width=9).pack(side="left", padx=3, ipady=3)
tk.Label(files_row,
text=f"{config.SETTINGS_FILE} — API 키·경로·옵션 "
f"{config.PROMPTS_FILE} · {config.RULES_FILE} — 번역 규칙 (있을 때만)",
fg="#555", font=(self.ui_font_family, 8)).pack(side="left", padx=(8, 0))
# 경로는 길어서 한 줄에 안 들어간다. wraplength로 접어 표시해야 창을 넘지 않는다.
tk.Label(files_lf,
text=os.path.abspath(os.path.dirname(config.SETTINGS_FILE) or "."),
fg="#888", font=(self.ui_font_family, 8),
anchor="w", justify="left", wraplength=820).pack(
fill="x", padx=10, pady=(0, 8))
# --- Tab 2: 번역 실행 (Run Translation) ---
self.tab_translation = tk.Frame(self.notebook)
self.notebook.add(self.tab_translation, text="1차 번역 (Translation)")
# Config Frame in Tab 2
config_frame = tk.LabelFrame(self.tab_translation, text="경로 및 옵션 설정")
config_frame.pack(fill="x", padx=10, pady=5)
# Text Directory
self.create_dir_selector(config_frame, "텍스트/PDF 폴더:", self.text_dir, 0, is_file=False)
# Image Directory
self.create_dir_selector(config_frame, "이미지 폴더:", self.image_dir, 1, is_file=False)
# Output Directory
self.create_dir_selector(config_frame, "결과물 저장 폴더:", self.output_dir, 2, is_file=False)
# Glossary File (Translation)
self.create_dir_selector(config_frame, "단어 사전 파일 (.txt):", self.trans_glossary_file, 3, is_file=True)
# Action Frame in Tab 2
action_frame = tk.Frame(self.tab_translation)
action_frame.pack(fill="x", padx=10, pady=5)
# ── 버튼 ─────────────────────────────────────────────────────
# 왼쪽 2×2에 준비 동작, 오른쪽에 '번역 시작'을 두 줄 높이로 둔다.
# (번역 옵션은 여기서 버튼으로 열린다 — 탭에 펼쳐두면 화면을 넘겨 잘렸다)
btn_frame = tk.Frame(action_frame)
btn_frame.pack(fill="x", pady=(0, 6))
btn_frame.columnconfigure(0, weight=1, uniform="btn")
btn_frame.columnconfigure(1, weight=1, uniform="btn")
btn_frame.columnconfigure(2, weight=1, uniform="btn")
self.extract_images_btn = self._button(btn_frame, "PDF 이미지 추출",
self.start_extract_pdf_images, kind="action")
self.extract_images_btn.grid(row=0, column=0, sticky="nsew", padx=(0, 6), pady=(0, 6), ipady=8)
self.glossary_btn = self._button(btn_frame, "고유명사 자동 추출",
self.start_glossary_extraction, kind="action")
self.glossary_btn.grid(row=0, column=1, sticky="nsew", padx=(0, 6), pady=(0, 6), ipady=8)
self.options_btn = self._button(btn_frame, "번역 옵션",
self.open_translation_options, kind="accent")
self.options_btn.grid(row=1, column=0, sticky="nsew", padx=(0, 6), ipady=8)
self.preview_btn = self._button(btn_frame, "미리보기 (첫 3청크)",
self.start_quick_preview, kind="accent")
self.preview_btn.grid(row=1, column=1, sticky="nsew", padx=(0, 6), ipady=8)
self.start_btn = self._button(btn_frame, "번역 시작",
self.start_translation, kind="primary", size=13)
self.start_btn.grid(row=0, column=2, rowspan=2, sticky="nsew")
# ── 단어 사전 옵션 (컴팩트 바) ───────────────────────────────
self._build_glossary_bar(action_frame)
# ── 진행 상황 ────────────────────────────────────────────────
self.progress = ttk.Progressbar(action_frame, orient="horizontal", mode="determinate")
self.progress.pack(fill="x", pady=(2, 2))
self.status_label = tk.Label(action_frame, text="준비됨",
fg="#555", font=(self.ui_font_family, 9))
self.status_label.pack(anchor="w", pady=(2, 0))
self._build_cleaner_tab()
self._build_ccfolia_tab()
self._build_log_area()
# ── 번역 옵션 창 ──────────────────────────────────────────────────────
def open_translation_options(self):
"""번역 옵션을 별도 창에서 연다.
옵션이 스무 개 가까이 되어 탭에 펼쳐두면 창 높이를 넘겨 아래쪽 버튼이 잘렸다.
체크박스가 같은 변수를 그대로 쓰므로 창에서 바꾸면 즉시 반영된다.
"""
existing = getattr(self, "_options_win", None)
if existing is not None and existing.winfo_exists():
existing.lift()
existing.focus_set()
return
win = tk.Toplevel(self.root)
self._options_win = win
win.title("번역 옵션")
win.transient(self.root)
win.resizable(False, False)
body = tk.Frame(win, padx=16, pady=12)
body.pack(fill="both", expand=True)
self._build_options_body(body)
footer = tk.Frame(win, padx=16, pady=(0))
footer.pack(fill="x", pady=(0, 12))
tk.Label(footer,
text="바꾼 즉시 적용됩니다. 다음 실행에도 유지하려면 설정 탭에서 '설정 저장'을 누르세요.",
fg="#777", font=(self.ui_font_family, 8)).pack(side="left")
self._button(footer, "닫기", win.destroy, kind="quiet", size=9).pack(
side="right", ipadx=14, ipady=4)
# 본창 위쪽 가운데에 띄운다
win.update_idletasks()
pos_x = self.root.winfo_rootx() + max(0, (self.root.winfo_width() - win.winfo_width()) // 2)
pos_y = self.root.winfo_rooty() + 70
win.geometry(f"+{max(0, pos_x)}+{max(0, pos_y)}")
def _build_options_body(self, options_lf):
"""번역 옵션 위젯들. 창 안에 들어간다."""
# Row 1: 2차 교열
refine_check = tk.Checkbutton(options_lf,
text="2차 교열 활성화 — 번역 후 더 자연스러운 한국어로 다듬기",
variable=self.refine_enabled,
font=(self.ui_font_family, 9))
refine_check.pack(anchor="w", pady=(0, 4))
ttk.Separator(options_lf, orient="horizontal").pack(fill="x", pady=(0, 6))
# Row 2: DOCX 출력 + 폰트
docx_row = tk.Frame(options_lf)
docx_row.pack(anchor="w", fill="x")
docx_check = tk.Checkbutton(docx_row,
text="DOCX 출력 — 글씨 색상 / 볼드 복원",
variable=self.docx_output_enabled,
font=(self.ui_font_family, 9))
docx_check.pack(side="left")
tk.Label(docx_row, text="폰트:", fg="#555",
font=(self.ui_font_family, 9)).pack(side="left", padx=(18, 3))
ttk.Entry(docx_row, textvariable=self.docx_font_name, width=13).pack(side="left")
tk.Label(docx_row, text="(맑은 고딕, 바탕 …)", fg="#999",
font=(self.ui_font_family, 8)).pack(side="left", padx=5)
# 단순한 표만 제대로 들어간다 — 복잡한 표는 줄글로 폴백하므로 beta로 표시한다
tk.Checkbutton(docx_row, text="표를 Word 표로 (beta)", variable=self.docx_tables,
font=(self.ui_font_family, 9)).pack(side="left", padx=(10, 0))
# Row 2.5: 서식 유지 토글
fmt_row = tk.Frame(options_lf)
fmt_row.pack(anchor="w", fill="x", padx=(26, 0), pady=(5, 0))
tk.Label(fmt_row, text="서식 유지:", fg="#444", font=(self.ui_font_family, 9)).pack(side="left")
for label, var in (("굵게", self.fmt_bold), ("글씨색", self.fmt_color), ("제목 크기", self.fmt_heading)):
tk.Checkbutton(fmt_row, text=label, variable=var,
font=(self.ui_font_family, 9), fg="#444").pack(side="left", padx=(8, 0))
tk.Label(fmt_row, text="(끄면 토큰 절약)", fg="#999",
font=(self.ui_font_family, 8)).pack(side="left", padx=(10, 0))
# Row 3: 헤더 제거 (DOCX 하위 옵션, 들여쓰기)
tk.Checkbutton(options_lf,
text="페이지 헤더 제거 ([1페이지], [2~3페이지] 구분선 숨기기)",
variable=self.docx_remove_headers,
font=(self.ui_font_family, 9),
fg="#444").pack(anchor="w", padx=(26, 0), pady=(5, 0))
tk.Checkbutton(options_lf,
text="원문대조 HTML 출력 — 원문과 번역을 페이지 단위로 나란히 (API 비용 없음)",
variable=self.bilingual_enabled,
font=(self.ui_font_family, 9)).pack(anchor="w", pady=(4, 0))
ttk.Separator(options_lf, orient="horizontal").pack(fill="x", pady=(8, 4))
# Row 3.5: PDF 판독 방식
pdf_row = tk.Frame(options_lf)
pdf_row.pack(anchor="w", fill="x", pady=(0, 4))
tk.Label(pdf_row, text="PDF 판독 순서:", font=(self.ui_font_family, 9)).pack(side="left")
ttk.Combobox(pdf_row, textvariable=self.column_mode, width=16, state="readonly",
values=["자동 (컬럼 인식)", "1단 강제", "2단 강제", "원본 순서"]
).pack(side="left", padx=(6, 14))
tk.Checkbutton(pdf_row, text="머리말·꼬리말 제거", variable=self.remove_margins,
font=(self.ui_font_family, 9)).pack(side="left")
tk.Checkbutton(pdf_row, text="셀 순서 보정", variable=self.sort_lines,
font=(self.ui_font_family, 9)).pack(side="left", padx=(10, 0))
tk.Checkbutton(pdf_row, text="원본 문단 유지", variable=self.paragraph_breaks,
font=(self.ui_font_family, 9)).pack(side="left", padx=(10, 0))
tk.Checkbutton(options_lf,
text="용어집 자동 추출 — 사전 파일이 없을 때 번역 전 1회 추출 (고유명사 표기 통일)",
variable=self.auto_extract_glossary,
font=(self.ui_font_family, 9)).pack(anchor="w", pady=(0, 4))
img_row = tk.Frame(options_lf)
img_row.pack(anchor="w", fill="x", pady=(0, 4))
tk.Checkbutton(img_row,
text="복잡한 페이지는 이미지로 번역 — 번역 전 대상 페이지를 확인할 수 있습니다",
variable=self.image_fallback_enabled,
font=(self.ui_font_family, 9)).pack(side="left")
tk.Checkbutton(img_row, text="표 있는 페이지 포함", variable=self.detect_tables,
font=(self.ui_font_family, 9), fg="#444").pack(side="left", padx=(10, 0))
ttk.Separator(options_lf, orient="horizontal").pack(fill="x", pady=(8, 4))
# Row 4: 번역 재개
tk.Checkbutton(options_lf,
text="이미 번역된 파일 건너뛰기 (이어서 번역 / Resume)",
variable=self.resume_enabled,
font=(self.ui_font_family, 9)).pack(anchor="w", pady=(0, 4))
ttk.Separator(options_lf, orient="horizontal").pack(fill="x", pady=(0, 4))
# Row 5: 완료 후 옵션
completion_row = tk.Frame(options_lf)
completion_row.pack(anchor="w", fill="x")
tk.Label(completion_row, text="완료 후:",
font=(self.ui_font_family, 9), fg="#555").pack(side="left", padx=(0, 8))
tk.Checkbutton(completion_row,
text="폴더 자동 열기",
variable=self.auto_open_output,
font=(self.ui_font_family, 9)).pack(side="left", padx=(0, 16))
tk.Checkbutton(completion_row,
text="로그 파일 저장",
variable=self.save_log_enabled,
font=(self.ui_font_family, 9)).pack(side="left")
def _build_glossary_bar(self, parent):
"""단어 사전 관련 버튼 묶음 (한 줄짜리 얕은 바)."""
bar = tk.Frame(parent, bg="#F2F2F2", relief="flat", bd=0,
highlightbackground="#D8DDE1", highlightthickness=1)
bar.pack(fill="x", pady=(0, 6))
self.open_glossary_btn = tk.Button(bar,
text="추출된 단어 사전 열기 (auto_glossary.txt)",
command=self.open_extracted_glossary,
state="disabled",
bg="#F2F2F2", relief="flat", bd=0, highlightthickness=0,
activebackground="#E4E8EB", cursor="hand2",
font=(self.ui_font_family, 9), fg="#37474F")
self.open_glossary_btn.pack(side="left", padx=8, pady=5)
tk.Frame(bar, width=1, bg="#D8DDE1").pack(side="left", fill="y", pady=5)
self.auto_apply_check = tk.Checkbutton(bar,
text="추출 성공 시 단어 사전에 자동 적용",
variable=self.auto_apply_glossary,
bg="#F2F2F2", activebackground="#F2F2F2",
font=(self.ui_font_family, 9))
self.auto_apply_check.pack(side="left", padx=8, pady=5)
tk.Frame(bar, width=1, bg="#D8DDE1").pack(side="left", fill="y", pady=5)
tk.Button(bar,
text="✏ 사전 편집",
command=self.open_glossary_editor,
bg="#F2F2F2", relief="flat", bd=0, highlightthickness=0,
activebackground="#E4E8EB", cursor="hand2",
font=(self.ui_font_family, 9), fg="#37474F").pack(side="left", padx=8, pady=5)
def _build_cleaner_tab(self):
# --- Tab 3: 이미지 글자 제거 (beta) ---
self.tab_cleaner = tk.Frame(self.notebook)
self.notebook.add(self.tab_cleaner, text="이미지 글자 제거 (beta)")
cleaner_container = tk.LabelFrame(self.tab_cleaner, text="이미지 글자 제거 및 배경 복구 (Image Cleaner)")
cleaner_container.pack(fill="both", expand=True, padx=10, pady=10)
# Cleaner API Settings
ic_api_frame = tk.LabelFrame(cleaner_container, text="이미지 클리너 전용 설정 (Image Cleaner API Settings)")
ic_api_frame.pack(fill="x", padx=10, pady=5)
tk.Label(ic_api_frame, text="Gemini API Key:", width=15, anchor="w").grid(row=0, column=0, padx=5, pady=5)
tk.Entry(ic_api_frame, textvariable=self.ic_api_key, show="*", width=50).grid(row=0, column=1, padx=5, pady=5)
tk.Label(ic_api_frame, text="Model Name:", width=15, anchor="w").grid(row=1, column=0, padx=5, pady=5)
tk.Entry(ic_api_frame, textvariable=self.ic_model_name, width=50).grid(row=1, column=1, padx=5, pady=5)
# Cleaner Path Settings
ic_path_frame = tk.Frame(cleaner_container)
ic_path_frame.pack(fill="x", padx=10, pady=5)
self.create_dir_selector(ic_path_frame, "입력 폴더 (하위 포함):", self.ic_input_dir, 0, is_file=False)
self.create_dir_selector(ic_path_frame, "결과 저장 폴더:", self.ic_output_dir, 1, is_file=False)
# Prompt & Options
ic_opt_frame = tk.Frame(cleaner_container)
ic_opt_frame.pack(fill="x", padx=10, pady=5)
tk.Label(ic_opt_frame, text="지시 사항 (Prompt):", width=20, anchor="w").grid(row=0, column=0, padx=5, pady=5)
tk.Entry(ic_opt_frame, textvariable=self.ic_prompt, width=65).grid(row=0, column=1, padx=5, pady=5)
tk.Label(ic_opt_frame, text="(예: 캐릭터나 그림은 유지하고 글자만 자연스럽게 지워줘)", fg="gray", font=(self.ui_font_family, 8)).grid(row=1, column=1, sticky="w", padx=5)
tk.Checkbutton(ic_opt_frame, text="Alpha 채널(투명도) 유지", variable=self.ic_alpha_enabled).grid(row=2, column=0, columnspan=2, sticky="w", padx=5, pady=5)
self.ic_status_label = tk.Label(ic_opt_frame, text="이미지 클리너 준비됨")
self.ic_status_label.grid(row=2, column=1, sticky="e", padx=5)
# Buttons
ic_btn_frame = tk.Frame(cleaner_container)
ic_btn_frame.pack(fill="x", padx=10, pady=20)
ic_btn_frame.columnconfigure(0, weight=1, uniform="icbtn")
ic_btn_frame.columnconfigure(1, weight=2, uniform="icbtn")
self._button(ic_btn_frame, "한 장 미리보기", self.preview_image_clean,
kind="action").grid(row=0, column=0, sticky="ew", padx=(0, 8), ipady=8)
self.ic_start_btn = self._button(ic_btn_frame, "이미지 글자 제거 시작 (Batch)",
self.start_batch_clean, kind="primary", size=11)
self.ic_start_btn.grid(row=0, column=1, sticky="ew", ipady=8)
def _build_ccfolia_tab(self):
# --- Tab 4: 코코포리아 ---
self.tab_ccfolia = tk.Frame(self.notebook)
self.notebook.add(self.tab_ccfolia, text="코코포리아 룸 셋팅")
self.setup_ccfolia_tab(self.tab_ccfolia)
def _build_log_area(self):
# --- Global: Log Area (분할 아래쪽) ---
log_frame = tk.LabelFrame(self.paned, text="로그 및 미리보기 (Log & Preview)")
self.paned.add(log_frame, weight=1)
# height=10은 경계선을 맨 아래까지 내렸을 때의 최소 높이 역할을 한다
self.log_area = scrolledtext.ScrolledText(log_frame, state='disabled', height=10)
self.log_area.pack(fill="both", expand=True)
def open_extracted_glossary(self):
"""Opens the last extracted glossary text file."""
if hasattr(self, 'last_extracted_glossary') and self.last_extracted_glossary and os.path.exists(self.last_extracted_glossary):
import subprocess
if sys.platform == "win32":
os.startfile(self.last_extracted_glossary)
elif sys.platform == "darwin":
subprocess.call(["open", self.last_extracted_glossary])
else:
subprocess.call(["xdg-open", self.last_extracted_glossary])
else:
messagebox.showwarning("오류", "열 수 있는 자동 추출 사전 파일이 없습니다.")
def open_manual(self):
"""Opens the User Manual HTML file in default browser."""
try:
manual_name = "manual.html"
if getattr(sys, 'frozen', False):
base_path = sys._MEIPASS
else:
base_path = os.path.dirname(os.path.abspath(__file__))
manual_path = os.path.join(base_path, manual_name)
if os.path.exists(manual_path):
webbrowser.open(f"file://{manual_path}")
else:
# Fallback to CWD
local_path = os.path.join(os.getcwd(), manual_name)
if os.path.exists(local_path):
webbrowser.open(f"file://{local_path}")
else:
messagebox.showerror("Error", "매뉴얼 파일을 찾을 수 없습니다.")
except Exception as e:
messagebox.showerror("Error", f"매뉴얼 열기 실패: {e}")
def save_app_settings(self):
"""API 키와 모델명을 검증한 뒤 settings.json에 저장하고 Gemini 클라이언트를 재설정한다."""
ak = self.api_key_var.get().strip()
mn = self.model_name_var.get().strip()
# 저장 전 API 연결 검증 (실제 토큰을 소비하지 않는 count_tokens 호출)
from translator import validate_api_connection
valid, message = validate_api_connection(ak, mn)
if not valid:
messagebox.showerror("Validation Error", message)
if not messagebox.askyesno("Save Anyway?", "API 검증에 실패했습니다. 그래도 저장을 진행하시겠습니까?"):
return
if save_settings(
ak, mn,
image_cleaner_api_key=self.ic_api_key.get().strip(),
image_cleaner_model_name=self.ic_model_name.get().strip(),
image_cleaner_prompt=self.ic_prompt.get(),
image_cleaner_alpha_enabled=self.ic_alpha_enabled.get(),
auto_open_output=self.auto_open_output.get(),
save_log_enabled=self.save_log_enabled.get(),
min_image_size=self.min_image_size.get(),
price_input_per_1m=self.price_input_per_1m.get().strip() or "0",
price_output_per_1m=self.price_output_per_1m.get().strip() or "0",
column_mode=self.column_mode.get(),
remove_margins=self.remove_margins.get(),
image_fallback_enabled=self.image_fallback_enabled.get(),
auto_extract_glossary=self.auto_extract_glossary.get(),
fmt_bold=self.fmt_bold.get(),
fmt_color=self.fmt_color.get(),
fmt_heading=self.fmt_heading.get(),
bilingual_enabled=self.bilingual_enabled.get(),
sort_lines=self.sort_lines.get(),
detect_tables=self.detect_tables.get(),
docx_tables=self.docx_tables.get(),
paragraph_breaks=self.paragraph_breaks.get(),
):
# Re-configure runtime
configure_genai(
ak, mn,
cleaner_api_key=self.ic_api_key.get().strip(),
cleaner_model_name=self.ic_model_name.get().strip()
)
messagebox.showinfo("Success", "설정이 저장되었습니다.")
self.log("Settings saved.")
else:
messagebox.showerror("Error", "설정 저장 실패.")
def create_dir_selector(self, parent, label_text, var, row, is_file=False):
"""레이블 + 입력 필드 + 폴더/파일 선택 버튼으로 구성된 경로 선택 위젯 행을 생성한다."""
tk.Label(parent, text=label_text, width=20, anchor="w").grid(row=row, column=0, padx=5, pady=5)
entry = tk.Entry(parent, textvariable=var, width=50)
entry.grid(row=row, column=1, padx=5, pady=5)
cmd = lambda: self.browse_file(var) if is_file else self.browse_dir(var)
btn_text = "파일 선택" if is_file else "폴더 선택"
self._button(parent, btn_text, cmd, kind="quiet", size=9, bold=False).grid(
row=row, column=2, padx=5, pady=5, ipadx=8, ipady=3)
def browse_dir(self, var):
directory = filedialog.askdirectory()
if directory:
var.set(directory)
def browse_file(self, var):
filename = filedialog.askopenfilename(filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
if filename:
var.set(filename)
def log(self, message):
"""백그라운드 스레드에서 호출 가능한 로그 메서드. 메시지를 큐에 넣어 메인 스레드에서 처리한다."""
self.msg_queue.put(("log", message))
def update_progress(self, current, total, status_text):
"""프로그레스바와 상태 레이블을 갱신하는 메시지를 큐에 넣는다."""
self.msg_queue.put(("progress", (current, total, status_text)))
def process_queue(self):
"""100ms마다 호출되어 백그라운드 스레드가 쌓아둔 UI 업데이트 메시지를 처리한다.
Tkinter는 메인 스레드에서만 UI를 조작할 수 있으므로, 백그라운드 작업의 결과는
모두 msg_queue를 통해 이 메서드로 전달된다.
"""
try:
while True:
msg_type, data = self.msg_queue.get_nowait()
if msg_type == "log":
self.log_area.config(state='normal')
self.log_area.insert(tk.END, data + "\n")
self.log_area.see(tk.END)
self.log_area.config(state='disabled')
elif msg_type == "progress":
current, total, status_text = data
self.progress["maximum"] = total
self.progress["value"] = current
self.status_label.config(text=status_text)
elif msg_type == "done":
if hasattr(self, 'start_btn') and self.start_btn:
self.start_btn.config(state='normal')
if hasattr(self, 'glossary_btn') and self.glossary_btn:
self.glossary_btn.config(state='normal')
if hasattr(self, 'extract_images_btn') and self.extract_images_btn:
self.extract_images_btn.config(state='normal')
# Build completion message with stats
stats = data
if isinstance(stats, dict):
elapsed = stats.get("elapsed", 0)
m, s = divmod(int(elapsed), 60)
msg = (f"번역 완료!\n\n"
f"파일 {stats.get('files', 0)}개 · 청크 {stats.get('chunks', 0)}개\n"
f"소요: {m}분 {s}초")
if stats.get("errors", 0):
msg += f"\n⚠ 오류: {stats['errors']}개 (로그 확인)"
else:
msg = "번역 완료!"
# Auto-open output folder
try:
if hasattr(self, 'auto_open_output') and self.auto_open_output.get():
out_path = self.output_dir.get()
if out_path and os.path.exists(out_path):
os.startfile(out_path)
except Exception:
pass
# Save log file
try:
if hasattr(self, 'save_log_enabled') and self.save_log_enabled.get():
import datetime
log_content = self.log_area.get("1.0", tk.END)
out_path = self.output_dir.get()
if out_path and os.path.exists(out_path):
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
log_path = os.path.join(out_path, f"translation_log_{ts}.txt")
with open(log_path, "w", encoding="utf-8") as lf:
lf.write(log_content)
self.log_area.config(state='normal')
self.log_area.insert(tk.END, f"로그 저장됨: {os.path.basename(log_path)}\n")
self.log_area.config(state='disabled')
except Exception:
pass
messagebox.showinfo("완료", msg)
elif msg_type == "preview_result":
fname, result_text = data
popup = tk.Toplevel(self.root)
popup.title(f"미리보기 결과 — {fname}")
popup.geometry("700x500")
popup.transient(self.root)
txt = scrolledtext.ScrolledText(popup, wrap="word",
font=(self.ui_font_family, 10))
txt.pack(fill="both", expand=True, padx=10, pady=10)
txt.insert(tk.END, result_text)
txt.config(state='disabled')
self._button(popup, "닫기", popup.destroy,
kind="quiet", size=10).pack(pady=8, ipadx=24, ipady=6)
elif msg_type == "done_glossary":
if hasattr(self, 'start_btn') and self.start_btn:
self.start_btn.config(state='normal')
if hasattr(self, 'glossary_btn') and self.glossary_btn:
self.glossary_btn.config(state='normal')
if hasattr(self, 'extract_images_btn') and self.extract_images_btn:
self.extract_images_btn.config(state='normal')
elif msg_type == "glossary_success":
# data is out_file path
if hasattr(self, 'open_glossary_btn') and self.open_glossary_btn:
self.open_glossary_btn.config(state='normal')
self.last_extracted_glossary = data
if self.auto_apply_glossary.get():
self.trans_glossary_file.set(data)
messagebox.showinfo("사전 추출 완료", f"고유명사 추출이 완료되었습니다!\n저장 경로: {data}\n\n'단어 사전 파일' 입력란에 자동으로 적용되었습니다.")
else:
messagebox.showinfo("사전 추출 완료", f"고유명사 추출이 완료되었습니다!\n저장 경로: {data}")
elif msg_type == "error":
if hasattr(self, 'start_btn') and self.start_btn:
self.start_btn.config(state='normal')
if hasattr(self, 'glossary_btn') and self.glossary_btn:
self.glossary_btn.config(state='normal')
if hasattr(self, 'ic_start_btn') and self.ic_start_btn:
self.ic_start_btn.config(state='normal')
messagebox.showerror("Error", data)
elif msg_type == "ic_done":
if hasattr(self, 'ic_start_btn') and self.ic_start_btn:
self.ic_start_btn.config(state='normal')
self.ic_status_label.config(text="이미지 클리닝 완료")
self.msg_queue.task_done()
except queue.Empty:
pass
# 종료 시 취소할 수 있도록 예약 id를 들고 있는다
self._queue_job = self.root.after(100, self.process_queue)
def load_glossary_from_file(self, filepath):
"""'원어:한국어' 형식의 .txt 용어집 파일을 파싱해 dict로 반환한다."""
glossary = {}
if not filepath or not os.path.exists(filepath):
return glossary