import sys import os import tkinter as tk from tkinter import ttk, messagebox from PIL import ImageGrab, ImageEnhance, Image, ImageTk import easyocr import time import threading import difflib import logging import numpy as np import cv2 from text_corrector import TextCorrector import translated_ui from text_corrector import DialogueType from control_ui import Control_UI from translator import Translator from translator_claude import TranslatorClaude from settings import Settings, SettingsUI from advance_ui import AdvanceUI from mini_ui import MiniUI from loggings import LoggingManager from translator_factory import TranslatorFactory import keyboard import re from appearance import appearance_manager import importlib.util import warnings from translated_logs import Translated_Logs warnings.filterwarnings("ignore", category=UserWarning) logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) # Add the directory containing npc_manager.py to the Python path current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(current_dir) print(f"Current directory: {current_dir}") print(f"Python path: {sys.path}") # Attempt to import create_npc_manager npc_manager_path = os.path.join(current_dir, "npc_manager.py") print(f"NPC Manager file exists: {os.path.exists(npc_manager_path)}") print("Attempting to import create_npc_manager using importlib") try: spec = importlib.util.spec_from_file_location("npc_manager", npc_manager_path) npc_manager_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(npc_manager_module) create_npc_manager = getattr(npc_manager_module, "create_npc_manager", None) print(f"create_npc_manager imported using importlib: {create_npc_manager}") except Exception as e: print(f"Error importing create_npc_manager using importlib: {e}") create_npc_manager = None class MagicBabelApp: def __init__(self, root): # 1. การตั้งค่าพื้นฐานของ root window self.root = root self.root.withdraw() # ซ่อน main window ก่อน self.root.attributes("-topmost", True) # ตั้งค่าเริ่มต้นเป็น True self.translation_event = threading.Event() self.ocr_cache = {} self.ocr_speed = "normal" self.cache_timeout = 1.0 # 1 วินาที # 2. สร้างและแสดง splash screen def show_splash(): splash = tk.Toplevel(root) splash.overrideredirect(True) splash.attributes("-topmost", True) try: # โหลดและเตรียมภาพ แบบรองรับความโปร่งใส image = Image.open("MBBvisual.png") image = image.convert("RGBA") # กำหนดขนาดที่ต้องการ SPLASH_WIDTH = 1280 SPLASH_HEIGHT = 720 # คำนวณอัตราส่วนการย่อขยายเพื่อรักษาสัดส่วนภาพ original_ratio = image.width / image.height new_ratio = SPLASH_WIDTH / SPLASH_HEIGHT if new_ratio > original_ratio: new_width = int(SPLASH_HEIGHT * original_ratio) new_height = SPLASH_HEIGHT else: new_width = SPLASH_WIDTH new_height = int(SPLASH_WIDTH / original_ratio) image = image.resize((new_width, new_height), Image.Resampling.LANCZOS) photo = ImageTk.PhotoImage(image) # จัดตำแหน่งกลางจอ screen_width = splash.winfo_screenwidth() screen_height = splash.winfo_screenheight() x = (screen_width - new_width) // 2 y = (screen_height - new_height) // 2 splash.geometry(f"{new_width}x{new_height}+{x}+{y}") splash.attributes("-transparentcolor", "black") splash.configure(bg="black") logo = tk.Label(splash, image=photo, bg="black", bd=0) logo.photo = photo # เก็บ reference ป้องกัน garbage collection logo.pack(fill="both", expand=True) # เพิ่ม fade in effect for i in range(0, 20): alpha = i / 20.0 splash.attributes("-alpha", alpha) splash.update() time.sleep(0.02) return splash, photo except Exception as e: print(f"Error loading splash screen: {e}") if splash.winfo_exists(): splash.destroy() return None, None # 3. แสดง splash screen self.splash, self.splash_photo = show_splash() # 4. เริ่มต้นค่าต่างๆ self.root.title("MagicBabel for FFXIV") self.root.geometry("300x320") self.root.overrideredirect(True) # 5. Initialize core components self.settings = Settings() self.logging_manager = LoggingManager(self.settings) self.custom_font = appearance_manager.apply_style(self.root) self.logging_manager.log_startup_info() self.text_corrector = TextCorrector() # 6. Initialize variables & UI self.hotkeys = {} self.init_variables() self.load_shortcuts() self.load_icons() # 7. Initialize window positions self.last_main_ui_pos = None self.last_mini_ui_pos = None self.last_translated_ui_pos = None # 8. Create UI components self.mini_ui = MiniUI(self.root, self.show_main_ui_from_mini) self.mini_ui.set_toggle_translation_callback(self.toggle_translation) self.blink_interval = 500 self.mini_ui.blink_interval = self.blink_interval self.create_main_ui() self.create_translated_ui() self.create_translated_logs() self.create_settings_ui() # 9. อัพเดทไฮไลท์ปุ่มตามพื้นที่เริ่มต้น initial_area = self.settings.get("current_area", "A+B") # เปลี่ยนค่าเริ่มต้นเป็น A+B self.current_area = initial_area # เพิ่มบรรทัดนี้ self.update_area_button_highlights(initial_area) # 10. Initialize translation system self.init_ocr_and_translation() self.bind_events() self.apply_saved_settings() # 11. Initialize NPC manager self.npc_manager = None # 12. รอ 3 วินาทีแล้วปิด splash และแสดง main window def finish_startup(): time.sleep(3) if hasattr(self, "splash") and self.splash and self.splash.winfo_exists(): try: # Fade out animation for i in range(10, -1, -1): alpha = i / 10 self.splash.attributes("-alpha", alpha) self.splash.update() time.sleep(0.05) self.splash.destroy() except Exception: pass self.root.deiconify() self.logging_manager.log_info("MagicBabel application started and ready") threading.Thread(target=finish_startup, daemon=True).start() def init_mini_ui(self): self.mini_ui = MiniUI(self.root, self.show_main_ui_from_mini) self.mini_ui.set_toggle_translation_callback(self.toggle_translation) self.mini_ui.blink_interval = self.blink_interval def create_translated_logs(self): try: logging.info("Creating translated logs window...") # สร้าง window self.translated_logs_window = tk.Toplevel(self.root) # สร้างและเก็บ instance self.translated_logs_instance = Translated_Logs( self.translated_logs_window, self.settings ) # ไม่ต้อง withdraw() ที่นี่ เพราะ Translated_Logs จะเริ่มในสถานะซ่อนเองแล้ว self.logging_manager.log_info("Translated logs created successfully") except Exception as e: self.logging_manager.log_error(f"Error creating translated logs: {e}") logging.exception("Detailed error in create_translated_logs:") def load_shortcuts(self): self.toggle_ui_shortcut = self.settings.get_shortcut("toggle_ui", "alt+h") self.start_stop_shortcut = self.settings.get_shortcut( "start_stop_translate", "f9" ) def handle_error(self, error_message): self.logging_manager.log_error(f"Error: {error_message}") def load_icons(self): self.blink_icon = ImageTk.PhotoImage( Image.open("red_icon.png").resize((20, 20)) ) self.black_icon = ImageTk.PhotoImage( Image.open("black_icon.png").resize((20, 20)) ) self.pin_icon = ImageTk.PhotoImage(Image.open("pin.png").resize((20, 20))) self.unpin_icon = ImageTk.PhotoImage(Image.open("unpin.png").resize((20, 20))) def create_main_ui(self): # ปรับขนาดหน้าต่างหลักให้สูงขึ้น self.root.geometry("300x400") # เพิ่มความสูงให้มากขึ้นเพื่อรองรับทุกส่วน self.main_frame = tk.Frame(self.root, bg=appearance_manager.bg_color) self.main_frame.pack(expand=True, fill=tk.BOTH) self.topmost_button = tk.Button( self.main_frame, image=self.pin_icon, command=self.toggle_topmost, bg=appearance_manager.bg_color, bd=0, ) self.topmost_button.place(x=10, y=10) # ทุกปุ่ม hover แล้วจะเปลี่ยนเป็นสีแดง self.select_area_button = appearance_manager.create_styled_button( self.main_frame, "Select Area-A", self.start_selection_a, hover_bg="blue" ) self.select_area_button.pack(pady=10, expand=True) self.select_area_frame = tk.Frame( self.main_frame, bg=appearance_manager.bg_color ) self.select_area_frame.pack(pady=5, expand=True) self.select_area_b_button = appearance_manager.create_styled_button( self.select_area_frame, "Select-B", self.start_selection_b, hover_bg="blue" ) self.select_area_b_button.pack(side=tk.LEFT, padx=5, expand=True) self.select_area_c_button = appearance_manager.create_styled_button( self.select_area_frame, "Select-C", self.start_selection_c, hover_bg="blue" ) self.select_area_c_button.pack(side=tk.LEFT, padx=5, expand=True) self.show_area_button = appearance_manager.create_styled_button( self.main_frame, "Show Area", self.toggle_show_area, hover_bg="pink" ) self.show_area_button.pack(pady=10, expand=True) self.start_stop_button = appearance_manager.create_styled_button( self.main_frame, "Start Translation", self.toggle_translation, hover_bg="red", ) self.start_stop_button.pack(pady=10, expand=True) self.blink_label = tk.Label( self.main_frame, image=self.black_icon, bg=appearance_manager.bg_color ) self.blink_label.pack(side=tk.RIGHT, padx=(0, 10)) self.blink_label.place(relx=0.95, rely=0.5, anchor="center") self.settings_button = appearance_manager.create_styled_button( self.main_frame, "Settings", self.toggle_settings, hover_bg="black" ) self.settings_button.pack(pady=10, expand=True) self.npc_manager_button = appearance_manager.create_styled_button( self.main_frame, "NPC Manager", self.toggle_npc_manager, hover_bg="purple" ) self.npc_manager_button.pack(pady=10, expand=True) # เพิ่มปุ่มปิดโปรแกรม self.exit_button = appearance_manager.create_styled_button( self.root, "X", self.exit_program, hover_bg="grey" ) self.exit_button.place(x=270, y=10, width=20, height=20) # สร้าง Bottom Container Frame bottom_container = tk.Frame(self.root, bg="#1a1a1a") bottom_container.pack(side=tk.BOTTOM, fill=tk.X) # สร้าง Frame สำหรับปุ่มควบคุม button_frame = tk.Frame(bottom_container, bg="#1a1a1a", height=40) button_frame.pack(fill=tk.X) button_frame.pack_propagate(False) # สร้าง Frame ย่อยสำหรับปุ่มทั้งหมด buttons_container = tk.Frame(button_frame, bg="#1a1a1a") buttons_container.pack(expand=True, pady=5) # สร้าง info label สำหรับแสดงข้อมูล Model และ Screen Size self.info_label = tk.Label( bottom_container, text=self.get_current_settings_info(), bg="#1a1a1a", fg="white", font=("Consolas", 8), # คงขนาด font เท่าเดิม justify=tk.LEFT, # ชิดซ้าย height=2, # กำหนดความสูงให้พอดี 2 บรรทัด ) self.info_label.pack(pady=(0, 5)) # กำหนดสไตล์ปุ่มให้เหมาะสม button_style = { "font": ("Nasalization Rg", 10), # เปลี่ยนเป็นฟอนต์เดียวกับ UI หลัก "bg": appearance_manager.bg_color, "fg": "white", "bd": 0, "padx": 5, # ลด padding "pady": 2, "cursor": "hand2", "width": 6, # กำหนดความกว้างให้เท่ากันทุกปุ่ม } # สร้างและจัดวางปุ่ม self.tui_button = tk.Button( buttons_container, text="TUI", command=self.toggle_translated_ui, **button_style, ) self.tui_button.pack(side=tk.LEFT, padx=2) self.log_button = tk.Button( buttons_container, text="LOG", command=self.toggle_translated_logs, **button_style, ) self.log_button.pack(side=tk.LEFT, padx=2) self.mini_button = tk.Button( buttons_container, text="MINI", command=self.toggle_mini_ui, **button_style ) self.mini_button.pack(side=tk.LEFT, padx=2) self.con_button = tk.Button( buttons_container, text="CON", command=self.toggle_control, **button_style ) self.con_button.pack(side=tk.LEFT, padx=2) # เพิ่ม Event Binding สำหรับ hover effect ให้ทุกปุ่ม for button in [ self.tui_button, self.log_button, self.mini_button, self.con_button, ]: button.bind( "", lambda e, b=button: b.config( bg=( "#666666" if b.cget("bg") == appearance_manager.bg_color else "#595959" ) ), ) button.bind( "", lambda e, b=button: b.config( bg=( appearance_manager.bg_color if b.cget("bg") == "#666666" else "#404040" ) ), ) def update_area_button_highlights(self, areas): """อัพเดทสีปุ่มตามพื้นที่ที่กำลังทำงาน""" # Reset all buttons button_map = { "A": self.select_area_button, "B": self.select_area_b_button, "C": self.select_area_c_button, } # Reset all buttons first for button in button_map.values(): button.configure(fg="white", bg=appearance_manager.bg_color) # Convert areas to list if it's a string active_areas = areas.split("+") if isinstance(areas, str) else areas # Highlight active buttons for area in active_areas: if area in button_map: button_map[area].configure(fg="#00FFFF", bg="#404040") def setup_button_events(self): """Setup hover effects for UI control buttons""" for button in [self.tui_button, self.log_button]: button.bind( "", lambda e, b=button: b.config( bg=( "#666666" if b.cget("bg") == appearance_manager.bg_color else "#595959" ) ), ) button.bind( "", lambda e, b=button: b.config( bg=( appearance_manager.bg_color if b.cget("bg") == "#666666" else "#404040" ) ), ) def toggle_translated_ui(self): """Toggle Translated UI visibility without affecting translation state""" if self.translated_ui_window.winfo_exists(): if self.translated_ui_window.state() == "withdrawn": self.translated_ui_window.deiconify() self.translated_ui_window.lift() self.tui_button.config(bg="#404040") # สีเข้มเมื่อแสดง else: self.translated_ui_window.withdraw() self.tui_button.config(bg=appearance_manager.bg_color) # สีปกติเมื่อซ่อน def toggle_translated_logs(self): """Toggle Translated Logs visibility independently""" logging.info("Attempting to toggle translated logs") if not hasattr(self, "translated_logs_instance"): logging.error("translated_logs_instance not found") return if self.translated_logs_window.winfo_exists(): if self.translated_logs_window.state() == "withdrawn": self.translated_logs_window.deiconify() self.translated_logs_window.lift() self.translated_logs_instance.is_visible = True self.log_button.config(bg="#404040") # สีเข้มเมื่อแสดง else: self.translated_logs_window.withdraw() self.translated_logs_instance.is_visible = False self.log_button.config(bg=appearance_manager.bg_color) # สีปกติเมื่อซ่อน def toggle_control(self): """Toggle the control UI window""" if hasattr(self, "control_ui") and self.control_ui.root.winfo_exists(): if self.control_ui.root.state() == "withdrawn": # ซิงค์สถานะก่อนแสดง areas = self.current_area.split("+") for area in ["A", "B", "C"]: self.control_ui.area_states[area] = area in areas self.control_ui.show_window() self.con_button.config(bg="#404040") else: self.control_ui.close_window() self.con_button.config(bg=appearance_manager.bg_color) else: control_root = tk.Toplevel(self.root) self.control_ui = Control_UI( control_root, self.force_translate, self.switch_area, self.settings ) # ซิงค์สถานะเริ่มต้น areas = self.current_area.split("+") for area in ["A", "B", "C"]: self.control_ui.area_states[area] = area in areas # เพิ่ม callback สำหรับปรับความเร็ว OCR self.control_ui.speed_callback = self.set_ocr_speed self.con_button.config(bg="#404040") def set_ocr_speed(self, speed_mode): """ ตั้งค่าความเร็วในการ OCR Args: speed_mode: 'normal' หรือ 'high' """ self.ocr_speed = speed_mode self.cache_timeout = 0.5 if speed_mode == "high" else 1.0 self.logging_manager.log_info(f"OCR speed set to: {speed_mode}") # อัพเดท settings self.settings.set("ocr_speed", speed_mode) self.settings.save_settings() def add_message(self, text): if hasattr(self, "translated_logs_instance"): self.translated_logs_instance.add_message(text) def get_current_settings_info(self): """รับข้อมูล Model และ Screen Size ปัจจุบัน""" model = self.settings.get_displayed_model() # ใช้ displayed_model แทน model ID screen_size = self.settings.get("screen_size", "2560x1440") return f"MODEL : {model}\nSCREEN : {screen_size}" def toggle_topmost(self): current_state = self.root.attributes("-topmost") self.root.attributes("-topmost", not current_state) self.topmost_button.config( image=self.unpin_icon if current_state else self.pin_icon ) def toggle_npc_manager(self): if create_npc_manager is None: messagebox.showwarning("Warning", "NPC Manager is not available.") return try: # กรณีที่ยังไม่มี instance if self.npc_manager is None: self.npc_manager = create_npc_manager(self.root, self.reload_npc_data) self.npc_manager.show_window() self.update_button_highlight(self.npc_manager_button, True) return # กรณีที่ window ถูกทำลายหรือไม่มีอยู่ if ( not hasattr(self.npc_manager, "window") or not self.npc_manager.window.winfo_exists() ): self.npc_manager = create_npc_manager(self.root, self.reload_npc_data) self.npc_manager.show_window() self.update_button_highlight(self.npc_manager_button, True) return # กรณีที่ window มีอยู่แล้ว is_visible = ( self.npc_manager.window.state() != "withdrawn" and self.npc_manager.window.winfo_viewable() ) if is_visible: self.npc_manager.window.withdraw() self.update_button_highlight(self.npc_manager_button, False) if hasattr(self.npc_manager, "search_var"): self.npc_manager.search_var.set("") else: self.npc_manager.show_window() self.update_button_highlight(self.npc_manager_button, True) except Exception as e: error_msg = f"Failed to toggle NPC Manager: {str(e)}" self.logging_manager.log_error(error_msg) messagebox.showerror("Error", error_msg) self.npc_manager = None def reload_npc_data(self): """Reload NPC data and update related components""" print("Reloading NPC data...") if hasattr(self, "translator") and self.translator: self.translator.reload_data() if hasattr(self, "text_corrector") and self.text_corrector: self.text_corrector.reload_data() if hasattr(self, "translated_ui"): character_names = self.text_corrector.names self.translated_ui.update_character_names(character_names) print("NPC data reload completed") def show_main_ui_from_mini(self): self.save_ui_positions() self.mini_ui.mini_ui.withdraw() self.root.deiconify() self.root.attributes("-topmost", True) self.root.lift() if self.last_main_ui_pos: self.root.geometry(self.last_main_ui_pos) def create_translated_ui(self): self.translated_ui_window = tk.Toplevel(self.root) # ตรวจสอบและส่ง character_names จาก text_corrector character_names = set() if hasattr(self, "text_corrector") and hasattr(self.text_corrector, "names"): character_names = self.text_corrector.names self.translated_ui = translated_ui.Translated_UI( self.translated_ui_window, self.toggle_translation, self.stop_translation, self.force_translate, self.toggle_main_ui, self.toggle_ui, self.settings, self.switch_area, self.logging_manager, character_names=character_names, main_app=self, # ส่ง main application reference ) # จัดตำแหน่งหน้าต่าง window_width = self.settings.get("width", 960) window_height = self.settings.get("height", 240) screen_width = self.root.winfo_screenwidth() screen_height = self.root.winfo_screenheight() x = (screen_width - window_width) // 2 y = (screen_height - window_height) // 2 self.translated_ui_window.geometry(f"+{x}+{y}") self.translated_ui_window.withdraw() def create_settings_ui(self): self.settings_ui = SettingsUI( self.root, self.settings, self.apply_settings, self.update_hotkeys ) self.settings_ui.set_ocr_toggle_callback(self.ocr_toggle_callback) self.settings_ui.close_settings() def init_ocr_and_translation(self): """Initialize OCR และ translator""" try: # ส่วน OCR initialization ยังคงเหมือนเดิม translate_area = self.settings.get_translate_area("A") self.start_x = translate_area["start_x"] self.start_y = translate_area["start_y"] self.end_x = translate_area["end_x"] self.end_y = translate_area["end_y"] use_gpu = self.settings.get("use_gpu_for_ocr", False) self.reader = easyocr.Reader(["en", "ko"], gpu=use_gpu) logging.info(f"Initialized OCR with languages: English, Korean") self.logging_manager.log_info(f"Initialized OCR with GPU: {use_gpu}") self.text_corrector = TextCorrector() # สร้าง translator ใหม่โดยใช้ Factory self.translator = TranslatorFactory.create_translator(self.settings) # Log current parameters params = self.translator.get_current_parameters() self.logging_manager.log_info(f"\nCurrent translator parameters:") self.logging_manager.log_info(f"Model: {params.get('model')}") self.logging_manager.log_info(f"Parameters: {params}\n") except Exception as e: self.logging_manager.log_error(f"Failed to initialize translator: {e}") messagebox.showerror("Translator Error", str(e)) self.translator = None def get_cached_ocr_result(self, area, image_hash): """ดึงผลลัพธ์ OCR จาก cache""" if area in self.ocr_cache: cached_time, cached_hash, result = self.ocr_cache[area] if ( time.time() - cached_time < self.cache_timeout and cached_hash == image_hash ): return result return None def cache_ocr_result(self, area, image_hash, result): """เก็บผลลัพธ์ OCR ลง cache""" self.ocr_cache[area] = (time.time(), image_hash, result) def toggle_ocr_gpu(self): current_use_gpu = self.settings.get("use_gpu_for_ocr", False) new_use_gpu = not current_use_gpu self.settings.set_gpu_for_ocr(new_use_gpu) use_gpu = self.settings.get("use_gpu_for_ocr") self.reader = easyocr.Reader(["en"], gpu=use_gpu) self.logging_manager.log_info(f"Switched OCR to {'GPU' if use_gpu else 'CPU'}") def ocr_toggle_callback(self): self.reinitialize_ocr() def init_variables(self): self.is_translating = False self.is_resizing = False self.translation_thread = None self.last_text = "" self.last_translation = "" self.last_translation_time = 0 self.last_force_time = 0 self.force_next_translation = False self.blinking = False self.mini_ui_blinking = False self.main_window_pos = None self.translated_window_pos = None self.mini_ui_pos = None self.settings_window_pos = None self.show_area_window = None self.is_area_shown = False self.x = None self.y = None self.current_area = "A" # ค่าเริ่มต้น def bind_events(self): self.root.bind("", self.start_move) self.root.bind("", self.stop_move) self.root.bind("", self.do_move) toggle_ui_shortcut = self.settings.get_shortcut("toggle_ui", "alt+h") start_stop_shortcut = self.settings.get_shortcut("start_stop_translate", "f9") if self.settings.get("enable_ui_toggle"): if "toggle_ui" in self.hotkeys: keyboard.remove_hotkey(self.hotkeys["toggle_ui"]) self.hotkeys["toggle_ui"] = keyboard.add_hotkey( toggle_ui_shortcut, self.toggle_ui ) if "start_stop_translate" in self.hotkeys: keyboard.remove_hotkey(self.hotkeys["start_stop_translate"]) self.hotkeys["start_stop_translate"] = keyboard.add_hotkey( start_stop_shortcut, self.toggle_translation ) if self.settings.get("enable_auto_hide"): for key in ["w", "a", "s", "d"]: if key in self.hotkeys: keyboard.remove_hotkey(self.hotkeys[key]) self.hotkeys[key] = keyboard.add_hotkey( key, self.hide_and_stop_translation ) self.logging_manager.log_info( f"Hotkeys bound: Toggle UI: {toggle_ui_shortcut}, Start/Stop Translate: {start_stop_shortcut}" ) def update_hotkeys(self): self.load_shortcuts() self.remove_all_hotkeys() self.bind_events() self.logging_manager.log_info( f"Hotkeys updated: Toggle UI: {self.toggle_ui_shortcut}, Start/Stop Translate: {self.start_stop_shortcut}" ) def apply_saved_settings(self): self.translated_ui.update_transparency(self.settings.get("transparency")) self.translated_ui.adjust_font_size(self.settings.get("font_size")) self.translated_ui.update_font(self.settings.get("font")) self.translated_ui_window.geometry( f"{self.settings.get('width')}x{self.settings.get('height')}" ) self.remove_all_hotkeys() self.bind_events() def remove_all_hotkeys(self): for key in list(self.hotkeys.keys()): try: keyboard.remove_hotkey(self.hotkeys[key]) del self.hotkeys[key] except Exception: pass self.hotkeys.clear() def toggle_settings(self): if self.settings_ui.settings_visible: self.settings_ui.close_settings() self.settings_button.config(text="Settings") self.update_button_highlight(self.settings_button, False) else: self.settings_ui.open_settings( self.root.winfo_x(), self.root.winfo_y(), self.root.winfo_width() ) self.settings_button.config(text="Close Settings") self.update_button_highlight(self.settings_button, True) def apply_settings(self, settings_dict): """Apply settings and update UI components""" try: # อัพเดท translated UI ถ้ามีการเปลี่ยนแปลงที่เกี่ยวข้อง if hasattr(self, "translated_ui") and self.translated_ui: if "transparency" in settings_dict: self.translated_ui.update_transparency( settings_dict["transparency"] ) if "font_size" in settings_dict: self.translated_ui.adjust_font_size(settings_dict["font_size"]) if "font" in settings_dict: self.translated_ui.update_font(settings_dict["font"]) # อัพเดทขนาดหน้าต่าง if "width" in settings_dict and "height" in settings_dict: width = settings_dict["width"] height = settings_dict["height"] self.translated_ui.root.geometry(f"{width}x{height}") # Force update UI self.translated_ui.force_check_overflow() self.translated_ui.root.update_idletasks() # อัพเดทค่า flags if "enable_force_translate" in settings_dict: self.enable_force_translate = settings_dict["enable_force_translate"] if "enable_auto_hide" in settings_dict: self.enable_auto_hide = settings_dict["enable_auto_hide"] if "enable_ui_toggle" in settings_dict: self.enable_ui_toggle = settings_dict["enable_ui_toggle"] # อัพเดท info label ถ้ามี if hasattr(self, "info_label"): self.info_label.config(text=self.get_current_settings_info()) logging.info("Settings applied successfully") return True except Exception as e: error_msg = f"Error applying settings: {e}" logging.error(error_msg) messagebox.showerror("Error", error_msg) return False def reinitialize_ocr(self): use_gpu = self.settings.get("use_gpu_for_ocr", False) self.reader = easyocr.Reader(["en"], gpu=use_gpu) self.logging_manager.log_info( f"OCR reinitialized with [{'GPU' if use_gpu else 'CPU'}]" ) def update_api_settings(self): """อัพเดท API settings แบบใหม่""" try: api_params = self.settings.get_api_parameters() if not api_params: raise ValueError("No API parameters found") if self.translator: # แยกการอัพเดทตามประเภท translator is_claude = api_params.get("model") == "claude-3-5-haiku-20241022" if is_claude != isinstance(self.translator, TranslatorClaude): # สร้าง translator ใหม่ถ้าประเภทไม่ตรงกัน self.init_ocr_and_translation() else: # อัพเดทพารามิเตอร์ if is_claude: self.translator.update_parameters( model=api_params["model"], max_tokens=api_params["max_tokens"], temperature=api_params["temperature"], ) else: self.translator.update_parameters( model=api_params["model"], max_tokens=api_params["max_tokens"], temperature=api_params["temperature"], top_p=api_params.get("top_p", 0.9), ) self.logging_manager.log_info(f"API settings updated: {api_params}") except Exception as e: self.logging_manager.log_error(f"Error updating API settings: {e}") raise def toggle_show_area(self): if self.is_area_shown: self.hide_show_area() self.update_button_highlight(self.show_area_button, False) else: self.show_area() self.update_button_highlight(self.show_area_button, True) def show_area(self): """แสดงพื้นที่ที่เลือกทั้งหมดบนหน้าจอ""" if not hasattr(self, "settings"): logging.error("Settings not initialized") return try: # ลบหน้าต่างเก่า if hasattr(self, "show_area_windows"): for window in self.show_area_windows.values(): if window and window.winfo_exists(): window.destroy() self.show_area_windows = {} active_areas = ( self.current_area.split("+") if isinstance(self.current_area, str) else [self.current_area] ) for area in active_areas: translate_area = self.settings.get_translate_area(area) if not translate_area: continue window = tk.Toplevel(self.root) window.overrideredirect(True) window.attributes("-alpha", 0.4) window.attributes("-topmost", True) # คำนวณตำแหน่งและขนาด scale_x, scale_y = self.get_screen_scale() x = int(translate_area["start_x"] * scale_x) y = int(translate_area["start_y"] * scale_y) width = int( (translate_area["end_x"] - translate_area["start_x"]) * scale_x ) height = int( (translate_area["end_y"] - translate_area["start_y"]) * scale_y ) window.geometry(f"{width}x{height}+{x}+{y}") canvas = tk.Canvas(window, bg="red", highlightthickness=0) canvas.pack(fill=tk.BOTH, expand=True) window.lift() self.show_area_windows[area] = window self.show_area_button.config(text="HIDE AREA") self.is_area_shown = True except Exception as e: logging.error(f"Error showing areas: {str(e)}") messagebox.showerror( "Error", "Failed to show selected areas. Check logs for details." ) self.is_area_shown = False def sync_initial_areas(self): """Sync initial area states between MBB and Control UI""" try: # โหลดค่าจาก settings หรือใช้ค่าเริ่มต้น self.current_area = self.settings.get("current_area", "A+B") # อัพเดทสถานะใน Control UI ถ้ามีการสร้างแล้ว if hasattr(self, "control_ui") and self.control_ui: areas = self.current_area.split("+") for area in ["A", "B", "C"]: self.control_ui.area_states[area] = area in areas self.control_ui.update_button_highlights() # อัพเดทไฮไลท์ปุ่มใน main UI self.update_area_button_highlights(self.current_area) except Exception as e: logging.error(f"Error in sync_initial_areas: {e}") # ถ้าเกิดข้อผิดพลาด ให้ใช้ค่าเริ่มต้น self.current_area = "A+B" self.update_area_button_highlights("A+B") def update_button_highlight(self, button, is_active): """อัพเดทสถานะไฮไลท์ของปุ่ม Args: button: ปุ่มที่ต้องการอัพเดท is_active: สถานะการไฮไลท์ (True/False) """ if is_active: button.configure(fg="#00FFFF", bg="#404040") else: button.configure(fg="white", bg=appearance_manager.bg_color) def hide_show_area(self): if hasattr(self, "show_area_windows"): for window in self.show_area_windows.values(): if window and window.winfo_exists(): window.destroy() self.show_area_windows.clear() else: self.show_area_windows = {} if hasattr(self, "show_area_window") and self.show_area_window: self.show_area_window.destroy() self.show_area_window = None self.show_area_button.config(text="Show Area") self.is_area_shown = False def start_selection_a(self): """เริ่มการเลือกพื้นที่ A สำหรับชื่อผู้พูด""" self.start_selection("A") def start_selection_b(self): """เริ่มการเลือกพื้นที่ B สำหรับบทสนทนาหลัก""" self.start_selection("B") def start_selection_c(self): """เริ่มการเลือกพื้นที่ C สำหรับข้อความเสริม""" self.start_selection("C") def start_selection(self, area): """เริ่มการเลือกพื้นที่แปลใหม่ Args: area (str): พื้นที่ที่ต้องการเลือก ('A', 'B', หรือ 'C') """ # เก็บสถานะการแสดงพื้นที่เดิมไว้ was_showing_area = self.is_area_shown # ซ่อนหน้าต่างแสดงพื้นที่เดิม (ถ้ามี) เพื่อไม่ให้ซ้ำซ้อน self.hide_show_area() self.root.withdraw() # สร้างหน้าต่างสำหรับเลือกพื้นที่ self.top = tk.Toplevel(self.root) screen_size = self.settings.get("screen_size", "2560x1440") self.top.geometry( f"{self.root.winfo_screenwidth()}x{self.root.winfo_screenheight()}+0+0" ) self.top.attributes("-topmost", True) self.top.attributes("-alpha", 0.3) self.top.overrideredirect(True) self.top.lift() self.top.focus_force() # สร้าง Canvas สำหรับวาดพื้นที่เลือก self.selection_canvas = tk.Canvas( self.top, bg="white", cursor="crosshair", highlightthickness=0 ) self.selection_canvas.pack(fill=tk.BOTH, expand=tk.YES) # แสดงพื้นที่ที่เปิดอยู่เดิมด้วยสีแดงโปร่งแสง active_areas = self.current_area.split("+") for active_area in active_areas: translate_area = self.settings.get_translate_area(active_area) if translate_area: scale_x, scale_y = self.get_screen_scale() x1 = int(translate_area["start_x"] * scale_x) y1 = int(translate_area["start_y"] * scale_y) x2 = int(translate_area["end_x"] * scale_x) y2 = int(translate_area["end_y"] * scale_y) # สร้างกรอบสีแดงโปร่งแสง self.selection_canvas.create_rectangle( x1, y1, x2, y2, outline="red", fill="red", stipple="gray50", tags=f"area_{active_area}", ) # เพิ่มป้ายกำกับพื้นที่ self.selection_canvas.create_text( x1 + 30, y1 + 20, text=f"Area {active_area}", fill="red", font=("Nasalization Rg", 12, "bold"), ) # แสดงคำแนะนำ instruction_text = f"คลิกซ้าย-ลาก เลือกพื้นที่ {area}\n" if area == "A": instruction_text += "สำหรับเลือก ชื่อผู้พูด" elif area == "B": instruction_text += "สำหรับเลือก บทสนทนาหลัก" else: instruction_text += "เลือกพื้นที่เสริมที่ต้องการ" self.instruction_label = tk.Label( self.top, text=instruction_text, fg="black", bg="white", font=("Nasalization Rg", 30), ) self.instruction_label.place(relx=0.5, rely=0.5, anchor="center") # ตัวแปรสำหรับเก็บจุดเริ่มต้นและสิ้นสุดการลาก self.start_x = None self.start_y = None self.selection_rect = None # Bind events self.selection_canvas.bind( "", lambda e: self.start_drag(e, area) ) self.selection_canvas.bind("", self.update_selection) self.selection_canvas.bind( "", lambda e: self.finish_selection(e, area) ) self.top.bind("", lambda e: self.cancel_selection()) def start_drag(self, event, area): self.start_x = event.x self.start_y = event.y if self.selection_rect: self.selection_canvas.delete(self.selection_rect) self.instruction_label.place_forget() def update_selection(self, event): if self.selection_rect: self.selection_canvas.delete(self.selection_rect) self.selection_rect = self.selection_canvas.create_rectangle( self.start_x, self.start_y, event.x, event.y, outline="red", fill="red", stipple="gray50", ) def finish_selection(self, event, area): """ จัดการการเลือกพื้นที่เสร็จสิ้น และอัพเดตพื้นที่การแปล Args: event: tkinter event object area: พื้นที่ที่กำลังเลือก ('A', 'B', หรือ 'C') """ if self.start_x is not None and self.start_y is not None: try: # คำนวณค่าพิกัดและปรับ scale scale_x, scale_y = self.get_screen_scale() x1 = min(self.start_x, event.x) / scale_x y1 = min(self.start_y, event.y) / scale_y x2 = max(self.start_x, event.x) / scale_x y2 = max(self.start_y, event.y) / scale_y # ตรวจสอบขนาดพื้นที่ขั้นต่ำ if abs(x2 - x1) < 10 or abs(y2 - y1) < 10: messagebox.showwarning("พื้นที่เล็กเกินไป", "กรุณาเลือกพื้นที่ให้ใหญ่กว่านี้") return # บันทึกพื้นที่ self.settings.set_translate_area( int(x1), int(y1), int(x2), int(y2), area ) # ตรวจสอบ unsave if hasattr(self, "control_ui") and self.control_ui: self.control_ui.has_unsaved_changes = True # รักษาพื้นที่เดิมที่เปิดอยู่ current_areas = set(self.current_area.split("+")) current_areas.add(area) # เพิ่มพื้นที่ใหม่เข้าไป # อัพเดตสถานะและ UI self.current_area = "+".join(sorted(current_areas)) # เรียงลำดับ A, B, C self.switch_area(self.current_area) # แสดงข้อความยืนยัน confirm_label = tk.Label( self.top, text=f"บันทึกพื้นที่ {area} เรียบร้อยแล้ว", fg="lime", bg="black", font=("Nasalization Rg", 14), ) confirm_label.place(relx=0.5, rely=0.5, anchor="center") # Log การอัพเดต self.logging_manager.log_info( f"Updated area {area}. Active areas: {self.current_area}" ) # ปิดหน้าต่างหลังจาก delay และแสดงพื้นที่สีแดง def close_and_show_area(): self.close_selection() # เปิดการแสดงพื้นที่สีแดงหลังปิดหน้าต่างเลือกพื้นที่ self.is_area_shown = False # รีเซ็ตสถานะก่อน self.show_area() # แสดงพื้นที่ทั้งหมดที่เปิดอยู่ self.show_area_button.config(text="HIDE AREA") # อัพเดตไฮไลท์ปุ่ม Show Area self.update_button_highlight(self.show_area_button, True) self.top.after(1000, close_and_show_area) except Exception as e: self.logging_manager.log_error(f"Error in finish_selection: {e}") messagebox.showerror("Error", f"เกิดข้อผิดพลาด: {str(e)}") def close_selection(self): """ปิดหน้าต่างเลือกพื้นที่และกลับสู่หน้าหลัก""" if hasattr(self, "top") and self.top: self.top.destroy() self.root.deiconify() def get_screen_scale(self): """คำนวณ scale factor สำหรับหน้าจอ""" screen_size = self.settings.get("screen_size", "2560x1440") screen_width, screen_height = map(int, screen_size.split("x")) scale_x = self.root.winfo_screenwidth() / screen_width scale_y = self.root.winfo_screenheight() / screen_height return scale_x, scale_y def scale_coordinates(self, x, y): """ปรับค่าพิกัดตาม scale ของหน้าจอ""" scale_x, scale_y = self.get_screen_scale() return int(x * scale_x), int(y * scale_y) def cancel_selection(self): self.top.destroy() self.root.deiconify() def preprocess_image(self, image): """ ปรับปรุงคุณภาพของภาพก่อนส่งเข้า OCR: 1. Resize ภาพให้ใหญ่ขึ้น 1.5 เท่า เพื่อเพิ่มรายละเอียด 2. ปรับ contrast เพื่อเพิ่มความชัดของตัวอักษร 3. แปลงเป็นภาพขาวดำ Args: image: PIL.Image object Returns: PIL.Image: ภาพที่ผ่านการปรับปรุงแล้ว """ try: # 1. ขยายภาพให้ใหญ่ขึ้น 1.5 เท่า width = int(image.width * 1.5) height = int(image.height * 1.5) image = image.resize((width, height), Image.Resampling.LANCZOS) # 2. ปรับ contrast เพื่อเพิ่มความชัดของตัวอักษร enhancer = ImageEnhance.Contrast(image) image = enhancer.enhance(1.3) # ปรับค่า contrast # 3. แปลงเป็นภาพขาวดำ คงรายละเอียดของ grayscale image = image.convert("L") return image except Exception as e: logging.error(f"Error in image preprocessing: {e}") # ถ้าเกิดข้อผิดพลาด ให้ใช้ภาพต้นฉบับ return image def capture_and_ocr(self): """ฟังก์ชันจับภาพและแปลงเป็นข้อความด้วย OCR""" # แปลงพื้นที่ที่ active ให้เป็นรูปแบบ list เสมอ active_areas = ( self.current_area.split("+") if isinstance(self.current_area, str) else [self.current_area] ) results = [] self._update_status_line("OCR scanning...") # แสดงสถานะ # วนลูปตามพื้นที่ที่เปิดใช้งาน for area in active_areas: # ดึงข้อมูลพื้นที่จาก settings translate_area = self.settings.get_translate_area(area) if not translate_area: continue start_x = translate_area["start_x"] start_y = translate_area["start_y"] end_x = translate_area["end_x"] end_y = translate_area["end_y"] # ตรวจสอบพื้นที่ว่าง if start_x == end_x or start_y == end_y: continue try: # คำนวณ scale ตามขนาดหน้าจอ screen_size = self.settings.get("screen_size", "2560x1440") screen_width, screen_height = map(int, screen_size.split("x")) scale_x = self.root.winfo_screenwidth() / screen_width scale_y = self.root.winfo_screenheight() / screen_height # คำนวณพิกัดที่จะจับภาพ x1 = int(min(start_x, end_x) * scale_x) y1 = int(min(start_y, end_y) * scale_y) x2 = int(max(start_x, end_x) * scale_x) y2 = int(max(start_y, end_y) * scale_y) # จับภาพหน้าจอและประมวลผล img = ImageGrab.grab(bbox=(x1, y1, x2, y2)) img = self.preprocess_image(img) # สร้างชื่อไฟล์ชั่วคราวที่ไม่ซ้ำกัน temp_path = f"temp_screenshot_{area}_{int(time.time()*1000)}.png" try: # บันทึกและอ่านข้อความจากภาพ img.save(temp_path) result = self.reader.readtext(temp_path, detail=0) text = " ".join(result) # เพิ่มผลลัพธ์ถ้ามีข้อความ if text: results.append((area, text)) finally: # ทำความสะอาดไฟล์ชั่วคราว try: if os.path.exists(temp_path): os.remove(temp_path) except Exception as e: logging.warning(f"Could not remove temp file {temp_path}: {e}") except Exception as e: self._update_status_line(f"Error in area {area}: {str(e)}") continue return results def is_choice_dialogue(self, text): """ตรวจสอบว่าเป็น choice dialogue หรือไม่ Args: text (str): ข้อความที่ต้องการตรวจสอบ Returns: bool: True ถ้าเป็น choice dialogue """ choice_patterns = [ "What will you say?", "คุณจะพูดว่าอย่างไร?", "Select an option.", "Choose your response.", ] # ทำความสะอาดข้อความก่อนตรวจสอบ cleaned_text = text.strip() for pattern in choice_patterns: if pattern in cleaned_text: self._update_status_line(f"Choice detected: {pattern}") return True return False def toggle_translation(self): try: if not self.is_translating: # ตรวจสอบและรอ thread เดิมให้จบก่อน if self.translation_thread and self.translation_thread.is_alive(): self.translation_thread.join(timeout=1) if not self.is_resizing: # ตรวจสอบพื้นที่ที่เปิดใช้งาน active_areas = ( self.current_area.split("+") if isinstance(self.current_area, str) else [self.current_area] ) valid_areas = True for area in active_areas: translate_area = self.settings.get_translate_area(area) if not translate_area: valid_areas = False break start_x = translate_area["start_x"] start_y = translate_area["start_y"] end_x = translate_area["end_x"] end_y = translate_area["end_y"] if start_x == end_x or start_y == end_y: valid_areas = False break if not valid_areas: messagebox.showwarning( "Warning", f"Please select translation areas for all active areas: {', '.join(active_areas)}", ) return # เริ่มการแปล self.is_translating = True self.translation_event.set() self.start_stop_button.config(text="Stop Translation") # เพิ่มการไฮไลท์ปุ่มเมื่อเริ่มการแปล self.update_button_highlight(self.start_stop_button, True) self.blinking = True self.blink_label.after(self.blink_interval, self.blink) # แสดง UI self.translated_ui_window.deiconify() # เริ่ม translation thread self.translation_thread = threading.Thread( target=self.translation_loop, daemon=True, name="TranslationThread", ) self.translation_thread.start() self.logging_manager.log_info("Translation thread started") else: return else: self.stop_translation() # เพิ่มการยกเลิกไฮไลท์ปุ่มเมื่อหยุดการแปล self.update_button_highlight(self.start_stop_button, False) self.translation_event.clear() if self.translation_thread: self.translation_thread.join(timeout=2) self.is_translating = False self.mini_ui.update_translation_status(self.is_translating) except Exception as e: self.logging_manager.log_error( f"An error occurred in toggle_translation: {e}" ) messagebox.showerror("Error", f"An error occurred: {e}") self.is_translating = False self.mini_ui.update_translation_status(False) # กรณีเกิดข้อผิดพลาด ยกเลิกไฮไลท์ปุ่ม self.update_button_highlight(self.start_stop_button, False) def stop_translation(self): if self.is_translating: self.is_translating = False self.translation_event.clear() # เพิ่มบรรทัดนี้ self.start_stop_button.config(text="Start Translation") self.blinking = False self.mini_ui.update_translation_status(False) self.blink_label.config(image=self.black_icon) if self.translation_thread: self.translation_thread.join(timeout=5) self.logging_manager.log_info("Translation thread stopped") # ซ่อนเฉพาะ translated UI if self.translated_ui_window.winfo_exists(): self.translated_ui_window.withdraw() def hide_and_stop_translation(self): if self.settings.get("enable_auto_hide") and self.is_translating: if self.translated_ui_window.state() == "normal": self.stop_translation() self.translated_ui_window.withdraw() def text_similarity(self, text1, text2): return difflib.SequenceMatcher(None, text1, text2).ratio() def translation_loop(self): """จัดการการแปลและแสดงผลอย่างต่อเนื่อง""" last_translated_text = "" # เก็บข้อความที่แปลล่าสุด waiting_for_message = False # สถานะการรอข้อความ temp_name = None # เก็บชื่อชั่วคราว is_processing = False # ป้องกันการทำงานซ้ำซ้อน while self.is_translating: try: # ป้องกันการทำงานซ้ำซ้อน if is_processing: time.sleep(0.4) continue is_processing = True # รอสัญญาณจาก Event if not self.translation_event.wait(timeout=0.2): self._update_status_line("Waiting for text...") is_processing = False continue # จับภาพและ OCR results = self.capture_and_ocr() if not results: self._update_status_line("Waiting for text...") is_processing = False continue current_time = time.time() combined_text = "" # 1. ตรวจสอบ choice dialogue ก่อนเสมอ for area, text in results: if area == "B": corrected_text = self.text_corrector.correct_text(text) choice_patterns = [ "What will you say", "What will you do", "Select an option", "Choose your response", ] is_choice = False for pattern in choice_patterns: if pattern.lower() in corrected_text.lower(): is_choice = True combined_text = "What will you say?\n" options_part = corrected_text.split(pattern, 1)[-1] if options_part: options = [ opt.strip() for opt in re.split(r"[.!?\n]+", options_part) if opt.strip() ] combined_text += "\n".join(options) break if is_choice: self._update_status_line("Choice dialogue detected!") break # 2. ถ้าไม่ใช่ choice ให้ดำเนินการปกติ if not combined_text: if self.current_area == "A+B": name_part = "" message_part = "" # 2.1 รวบรวมข้อความจากแต่ละพื้นที่ for area, text in results: corrected_text = self.text_corrector.correct_text(text) if area == "A": name_part = corrected_text.strip() if name_part.startswith("?") or name_part in [ "222", "222?", ]: name_part = "???" elif area == "B": message_part = corrected_text.strip() # 2.2 จัดการข้อความตามกรณีต่างๆ if message_part: # มีข้อความใน B # ตรวจสอบว่าข้อความใน B มีชื่อนำหน้าหรือไม่ speaker, content, dialogue_type = ( self.text_corrector.split_speaker_and_content( message_part ) ) if speaker: # ถ้าพบชื่อในข้อความ B combined_text = f"{speaker}: {content}" temp_name = None waiting_for_message = False elif name_part: # ถ้ามีชื่อจาก A combined_text = f"{name_part}: {message_part}" temp_name = None waiting_for_message = False else: # ไม่มีชื่อเลย แปลเหมือน C combined_text = message_part elif name_part: # มีแค่ชื่อ if waiting_for_message and temp_name == name_part: # ถ้ายังคงเป็นชื่อเดิม รอข้อความต่อไป is_processing = False continue else: # ถ้าเป็นชื่อใหม่ เก็บไว้รอ combined_text = name_part temp_name = name_part waiting_for_message = True else: # กรณี B หรือ C if len(results) == 1: area, text = results[0] corrected_text = self.text_corrector.correct_text(text) combined_text = corrected_text.strip() else: narrator_part = "" for area, text in results: corrected_text = self.text_corrector.correct_text(text) if area == "C": narrator_part = corrected_text.strip() combined_text = narrator_part if narrator_part else "" # 3. ดำเนินการแปลถ้ามีข้อความ if combined_text: similarity = self.text_similarity(combined_text, self.last_text) if ( similarity < 0.5 or current_time - self.last_translation_time > 30 or self.force_next_translation ): if self.translator: self._update_status_line("Translating...") translated_text = self.translator.translate(combined_text) if translated_text and len(translated_text.strip()) > 0: if ( translated_text != last_translated_text or self.force_next_translation ): self._update_status_line("✓ Translation updated") self.root.after( 0, lambda: self.translated_ui.update_text( translated_text ), ) if hasattr(self, "translated_logs_instance"): self.translated_logs_instance.add_message( translated_text ) last_translated_text = translated_text self.last_translation = translated_text self.last_text = combined_text self.last_translation_time = current_time self.force_next_translation = False is_processing = False except Exception as e: self._update_status_line(f"Error in translation_loop: {e}") self.logging_manager.log_error(f"Translation loop error: {e}") is_processing = False self.translation_event.wait(timeout=0.4) def _update_status_line(self, message): """อัพเดทข้อความสถานะในบรรทัดเดียว""" print(f"\r{message:<60}", end="", flush=True) # ใช้ 60 ช่องสำหรับข้อความ self.logging_manager.update_status(message) def save_ui_positions(self): self.last_main_ui_pos = self.root.geometry() if hasattr(self, "mini_ui"): self.last_mini_ui_pos = self.mini_ui.mini_ui.geometry() if hasattr(self, "translated_ui_window"): self.last_translated_ui_pos = self.translated_ui_window.geometry() def load_ui_positions(self): if self.last_main_ui_pos: self.root.geometry(self.last_main_ui_pos) if self.last_mini_ui_pos and hasattr(self, "mini_ui"): self.mini_ui.mini_ui.geometry(self.last_mini_ui_pos) if self.last_translated_ui_pos and hasattr(self, "translated_ui_window"): self.translated_ui_window.geometry(self.last_translated_ui_pos) def do_move(self, event): if self.x is not None and self.y is not None: deltax = event.x - self.x deltay = event.y - self.y x = self.root.winfo_x() + deltax y = self.root.winfo_y() + deltay self.root.geometry(f"+{x}+{y}") self.save_ui_positions() def toggle_ui(self): if self.settings.get("enable_ui_toggle"): self.save_ui_positions() if self.root.state() == "normal": # สลับจาก Main UI เป็น Mini UI self.main_window_pos = self.root.geometry() self.root.withdraw() self.mini_ui.mini_ui.deiconify() self.mini_ui.mini_ui.lift() self.mini_ui.mini_ui.attributes("-topmost", True) if self.last_mini_ui_pos: self.mini_ui.mini_ui.geometry(self.last_mini_ui_pos) else: # สลับจาก Mini UI เป็น Main UI self.root.deiconify() self.root.attributes("-topmost", True) self.root.lift() if self.last_main_ui_pos: self.root.geometry(self.last_main_ui_pos) self.mini_ui.mini_ui.withdraw() # ทำให้แน่ใจว่า Translated UI ยังคงแสดงอยู่ถ้ากำลังแปลอยู่ if self.is_translating and self.translated_ui_window.winfo_exists(): self.translated_ui_window.lift() self.translated_ui_window.attributes("-topmost", True) # อัพเดตสถานะของ Mini UI if hasattr(self, "mini_ui"): self.mini_ui.update_translation_status(self.is_translating) def toggle_mini_ui(self): """Toggle between Main UI and Mini UI""" self.save_ui_positions() if self.root.state() == "normal": # Switch to Mini UI main_x = self.root.winfo_x() main_y = self.root.winfo_y() main_width = self.root.winfo_width() main_height = self.root.winfo_height() self.root.withdraw() self.mini_ui.mini_ui.deiconify() self.mini_ui.mini_ui.lift() self.mini_ui.mini_ui.attributes("-topmost", True) # Position Mini UI at the center of Main UI's last position self.mini_ui.position_at_center_of_main( main_x, main_y, main_width, main_height ) else: # Switch to Main UI self.root.deiconify() self.root.lift() self.root.attributes("-topmost", True) if self.last_main_ui_pos: self.root.geometry(self.last_main_ui_pos) self.mini_ui.mini_ui.withdraw() # Update Mini UI status if hasattr(self, "mini_ui"): self.mini_ui.update_translation_status(self.is_translating) def toggle_main_ui(self): self.save_ui_positions() if self.root.state() == "normal": self.root.withdraw() else: self.root.deiconify() if self.last_main_ui_pos: self.root.geometry(self.last_main_ui_pos) def start_move(self, event): self.x = event.x self.y = event.y def stop_move(self, event): self.x = None self.y = None def update_mini_ui_move(self): original_do_move = self.mini_ui.do_move_mini_ui def new_do_move_mini_ui(event): original_do_move(event) self.save_ui_positions() self.mini_ui.do_move_mini_ui = new_do_move_mini_ui def setup_ui_position_tracking(self): self.update_mini_ui_move() self.load_ui_positions() def blink(self): if self.blinking: current_image = self.blink_label.cget("image") new_image = ( self.blink_icon if current_image == str(self.black_icon) else self.black_icon ) self.blink_label.config(image=new_image) self.blink_label.after(self.blink_interval, self.blink) else: self.blink_label.config(image=self.black_icon) def force_translate(self): current_time = time.time() if current_time - self.last_force_time >= 2: self.force_next_translation = True self.last_force_time = current_time def update_highlight_on_preset_change(self, areas): """อัพเดตการแสดงพื้นที่ไฮไลท์เมื่อมีการเปลี่ยน preset Args: areas (list): รายการพื้นที่ที่ต้องแสดง """ try: # ถ้ากำลังแสดงพื้นที่อยู่ if self.is_area_shown: # บันทึกสถานะการแสดงผล was_showing = True # ซ่อนพื้นที่เก่า self.hide_show_area() # แสดงพื้นที่ใหม่ทันที self.show_area() # อัพเดตสถานะปุ่ม self.show_area_button.config(text="HIDE AREA") self.update_button_highlight(self.show_area_button, True) logging.info(f"Updated highlight areas: {areas}") except Exception as e: logging.error(f"Error updating highlights: {e}") def switch_area(self, areas): """Switch to specified area(s) and update highlights Args: areas: string หรือ list ของพื้นที่ เช่น "A+B" หรือ ["A", "B"] """ try: # แปลงให้เป็น list เสมอ area_list = areas if isinstance(areas, list) else areas.split("+") # ตรวจสอบความถูกต้องของพื้นที่ for area in area_list: if area not in ["A", "B", "C"]: self.logging_manager.log_error(f"Invalid area: {area}") return # อัพเดต current_area self.current_area = "+".join(area_list) self.settings.set("current_area", self.current_area) # อัพเดท Control UI if hasattr(self, "control_ui") and self.control_ui.root.winfo_exists(): for area in ["A", "B", "C"]: self.control_ui.area_states[area] = area in area_list self.control_ui.update_button_highlights() # อัพเดท Main UI self.update_area_button_highlights(area_list) # ถ้ามีการแสดงพื้นที่สีแดงอยู่ ให้อัพเดตทันที if self.is_area_shown: self.hide_show_area() # ลบพื้นที่เก่า self.show_area() # แสดงพื้นที่ใหม่ self.logging_manager.log_info(f"Switched to areas {self.current_area}") self.force_translate() except Exception as e: self.logging_manager.log_error(f"Error in switch_area: {e}") def exit_program(self): self.stop_translation() self.hide_show_area() self.remove_all_hotkeys() try: keyboard.unhook_all() except Exception as e: self.logging_manager.log_error(f"Error unhooking keyboard: {e}") # เพิ่ม translated_logs_window เข้าไปในรายการ windows ที่ต้องปิด windows_to_close = [ self.translated_ui_window, self.translated_logs_window, # เพิ่มบรรทัดนี้ self.mini_ui.mini_ui, ] if hasattr(self.settings_ui, "settings_window"): windows_to_close.append(self.settings_ui.settings_window) if hasattr(self.settings_ui, "advance_ui") and self.settings_ui.advance_ui: windows_to_close.append(self.settings_ui.advance_ui.advance_window) for window in windows_to_close: if window: try: window.destroy() except Exception as e: self.logging_manager.log_error(f"Error destroying window: {e}") if self.translation_thread and self.translation_thread.is_alive(): self.translation_thread.join(timeout=5) try: self.root.quit() self.root.destroy() except Exception as e: self.logging_manager.log_error(f"Error destroying root window: {e}") self.logging_manager.log_info("MagicBabel application closed") sys.exit(0) if __name__ == "__main__": try: root = tk.Tk() app = MagicBabelApp(root) app.setup_ui_position_tracking() root.mainloop() except Exception as e: messagebox.showerror( "Critical Error", f"An unexpected error occurred: {e}\n\nPlease check the log file for details.", )