Datasets:
File size: 84,161 Bytes
3bb13c3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 |
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(
"<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):
"""อัพเดทสีปุ่มตามพื้นที่ที่กำลังทำงาน"""
# 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(
"<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
# เพิ่ม 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("<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:
# อัพเดท 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(
"<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
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.",
)
|