|
|
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"
|
|
|
)
|
|
|
|
|
|
|
|
|
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}")
|
|
|
|
|
|
|
|
|
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):
|
|
|
|
|
|
self.root = root
|
|
|
self.root.withdraw()
|
|
|
self.root.attributes("-topmost", True)
|
|
|
self.translation_event = threading.Event()
|
|
|
self.ocr_cache = {}
|
|
|
self.ocr_speed = "normal"
|
|
|
self.cache_timeout = 1.0
|
|
|
|
|
|
|
|
|
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
|
|
|
logo.pack(fill="both", expand=True)
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
self.splash, self.splash_photo = show_splash()
|
|
|
|
|
|
|
|
|
self.root.title("MagicBabel for FFXIV")
|
|
|
self.root.geometry("300x320")
|
|
|
self.root.overrideredirect(True)
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
self.hotkeys = {}
|
|
|
self.init_variables()
|
|
|
self.load_shortcuts()
|
|
|
self.load_icons()
|
|
|
|
|
|
|
|
|
self.last_main_ui_pos = None
|
|
|
self.last_mini_ui_pos = None
|
|
|
self.last_translated_ui_pos = None
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
initial_area = self.settings.get("current_area", "A+B")
|
|
|
self.current_area = initial_area
|
|
|
self.update_area_button_highlights(initial_area)
|
|
|
|
|
|
|
|
|
self.init_ocr_and_translation()
|
|
|
self.bind_events()
|
|
|
self.apply_saved_settings()
|
|
|
|
|
|
|
|
|
self.npc_manager = None
|
|
|
|
|
|
|
|
|
def finish_startup():
|
|
|
time.sleep(3)
|
|
|
|
|
|
if hasattr(self, "splash") and self.splash and self.splash.winfo_exists():
|
|
|
try:
|
|
|
|
|
|
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...")
|
|
|
|
|
|
|
|
|
self.translated_logs_window = tk.Toplevel(self.root)
|
|
|
|
|
|
|
|
|
self.translated_logs_instance = Translated_Logs(
|
|
|
self.translated_logs_window, self.settings
|
|
|
)
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
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 = tk.Frame(self.root, bg="#1a1a1a")
|
|
|
bottom_container.pack(side=tk.BOTTOM, fill=tk.X)
|
|
|
|
|
|
|
|
|
button_frame = tk.Frame(bottom_container, bg="#1a1a1a", height=40)
|
|
|
button_frame.pack(fill=tk.X)
|
|
|
button_frame.pack_propagate(False)
|
|
|
|
|
|
|
|
|
buttons_container = tk.Frame(button_frame, bg="#1a1a1a")
|
|
|
buttons_container.pack(expand=True, pady=5)
|
|
|
|
|
|
|
|
|
self.info_label = tk.Label(
|
|
|
bottom_container,
|
|
|
text=self.get_current_settings_info(),
|
|
|
bg="#1a1a1a",
|
|
|
fg="white",
|
|
|
font=("Consolas", 8),
|
|
|
justify=tk.LEFT,
|
|
|
height=2,
|
|
|
)
|
|
|
self.info_label.pack(pady=(0, 5))
|
|
|
|
|
|
|
|
|
button_style = {
|
|
|
"font": ("Nasalization Rg", 10),
|
|
|
"bg": appearance_manager.bg_color,
|
|
|
"fg": "white",
|
|
|
"bd": 0,
|
|
|
"padx": 5,
|
|
|
"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)
|
|
|
|
|
|
|
|
|
for button in [
|
|
|
self.tui_button,
|
|
|
self.log_button,
|
|
|
self.mini_button,
|
|
|
self.con_button,
|
|
|
]:
|
|
|
button.bind(
|
|
|
"<Enter>",
|
|
|
lambda e, b=button: b.config(
|
|
|
bg=(
|
|
|
"#666666"
|
|
|
if b.cget("bg") == appearance_manager.bg_color
|
|
|
else "#595959"
|
|
|
)
|
|
|
),
|
|
|
)
|
|
|
button.bind(
|
|
|
"<Leave>",
|
|
|
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):
|
|
|
"""อัพเดทสีปุ่มตามพื้นที่ที่กำลังทำงาน"""
|
|
|
|
|
|
button_map = {
|
|
|
"A": self.select_area_button,
|
|
|
"B": self.select_area_b_button,
|
|
|
"C": self.select_area_c_button,
|
|
|
}
|
|
|
|
|
|
|
|
|
for button in button_map.values():
|
|
|
button.configure(fg="white", bg=appearance_manager.bg_color)
|
|
|
|
|
|
|
|
|
active_areas = areas.split("+") if isinstance(areas, str) else areas
|
|
|
|
|
|
|
|
|
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(
|
|
|
"<Enter>",
|
|
|
lambda e, b=button: b.config(
|
|
|
bg=(
|
|
|
"#666666"
|
|
|
if b.cget("bg") == appearance_manager.bg_color
|
|
|
else "#595959"
|
|
|
)
|
|
|
),
|
|
|
)
|
|
|
button.bind(
|
|
|
"<Leave>",
|
|
|
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
|
|
|
|
|
|
|
|
|
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}")
|
|
|
|
|
|
|
|
|
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()
|
|
|
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:
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
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 = 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,
|
|
|
)
|
|
|
|
|
|
|
|
|
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:
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
self.translator = TranslatorFactory.create_translator(self.settings)
|
|
|
|
|
|
|
|
|
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("<Button-1>", self.start_move)
|
|
|
self.root.bind("<ButtonRelease-1>", self.stop_move)
|
|
|
self.root.bind("<B1-Motion>", 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:
|
|
|
|
|
|
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}")
|
|
|
|
|
|
|
|
|
self.translated_ui.force_check_overflow()
|
|
|
self.translated_ui.root.update_idletasks()
|
|
|
|
|
|
|
|
|
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"]
|
|
|
|
|
|
|
|
|
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:
|
|
|
|
|
|
is_claude = api_params.get("model") == "claude-3-5-haiku-20241022"
|
|
|
|
|
|
if is_claude != isinstance(self.translator, TranslatorClaude):
|
|
|
|
|
|
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:
|
|
|
|
|
|
self.current_area = self.settings.get("current_area", "A+B")
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
self.selection_canvas.bind(
|
|
|
"<ButtonPress-1>", lambda e: self.start_drag(e, area)
|
|
|
)
|
|
|
self.selection_canvas.bind("<B1-Motion>", self.update_selection)
|
|
|
self.selection_canvas.bind(
|
|
|
"<ButtonRelease-1>", lambda e: self.finish_selection(e, area)
|
|
|
)
|
|
|
self.top.bind("<Escape>", 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_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
|
|
|
)
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
self.current_area = "+".join(sorted(current_areas))
|
|
|
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")
|
|
|
|
|
|
|
|
|
self.logging_manager.log_info(
|
|
|
f"Updated area {area}. Active areas: {self.current_area}"
|
|
|
)
|
|
|
|
|
|
|
|
|
def close_and_show_area():
|
|
|
self.close_selection()
|
|
|
|
|
|
self.is_area_shown = False
|
|
|
self.show_area()
|
|
|
self.show_area_button.config(text="HIDE 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:
|
|
|
|
|
|
width = int(image.width * 1.5)
|
|
|
height = int(image.height * 1.5)
|
|
|
image = image.resize((width, height), Image.Resampling.LANCZOS)
|
|
|
|
|
|
|
|
|
enhancer = ImageEnhance.Contrast(image)
|
|
|
image = enhancer.enhance(1.3)
|
|
|
|
|
|
|
|
|
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_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:
|
|
|
|
|
|
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:
|
|
|
|
|
|
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:
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
self.translated_ui_window.deiconify()
|
|
|
|
|
|
|
|
|
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")
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
if not self.translation_event.wait(timeout=0.2):
|
|
|
self._update_status_line("Waiting for text...")
|
|
|
is_processing = False
|
|
|
continue
|
|
|
|
|
|
|
|
|
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 = ""
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
if not combined_text:
|
|
|
if self.current_area == "A+B":
|
|
|
name_part = ""
|
|
|
message_part = ""
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
if message_part:
|
|
|
|
|
|
speaker, content, dialogue_type = (
|
|
|
self.text_corrector.split_speaker_and_content(
|
|
|
message_part
|
|
|
)
|
|
|
)
|
|
|
|
|
|
if speaker:
|
|
|
combined_text = f"{speaker}: {content}"
|
|
|
temp_name = None
|
|
|
waiting_for_message = False
|
|
|
elif name_part:
|
|
|
combined_text = f"{name_part}: {message_part}"
|
|
|
temp_name = None
|
|
|
waiting_for_message = False
|
|
|
else:
|
|
|
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:
|
|
|
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 ""
|
|
|
|
|
|
|
|
|
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)
|
|
|
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":
|
|
|
|
|
|
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:
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
if self.is_translating and self.translated_ui_window.winfo_exists():
|
|
|
self.translated_ui_window.lift()
|
|
|
self.translated_ui_window.attributes("-topmost", True)
|
|
|
|
|
|
|
|
|
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":
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
self.mini_ui.position_at_center_of_main(
|
|
|
main_x, main_y, main_width, main_height
|
|
|
)
|
|
|
|
|
|
else:
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
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:
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
self.current_area = "+".join(area_list)
|
|
|
self.settings.set("current_area", self.current_area)
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
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}")
|
|
|
|
|
|
|
|
|
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.",
|
|
|
)
|
|
|
|