Datasets:
File size: 32,481 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 |
from openai import OpenAI
import os
from dotenv import load_dotenv
import re
import tkinter as tk
from tkinter import messagebox
import json
import difflib
import time
import logging
from translation_logger import TranslationLogger
from enum import Enum
from text_corrector import TextCorrector, DialogueType
load_dotenv()
class DialogueCache:
def __init__(self):
self.name_history = [] # เก็บประวัติชื่อที่ validate แล้ว 5 ชื่อล่าสุด
self.last_speaker = None # เก็บชื่อล่าสุดที่ validate แล้ว
self.MAX_HISTORY = 5
self.session_speakers = []
self.name_translations = {}
self.speaker_styles = {} # เพิ่มตรงนี้เพื่อเก็บรูปแบบการพูดของตัวละคร
def add_validated_name(self, name):
"""เพิ่มชื่อที่ผ่านการ validate แล้วเท่านั้น"""
if name and name not in self.name_history:
# ถ้ามีครบ 5 ตัวแล้ว ให้ลบตัวแรกออก
if len(self.name_history) >= self.MAX_HISTORY:
self.name_history.pop(0)
self.name_history.append(name)
self.last_speaker = name
def add_speaker(self, speaker_name, translated_name=None):
"""เพิ่มชื่อผู้พูดพร้อมการแปล (ถ้ามี)"""
if speaker_name:
if speaker_name not in self.session_speakers:
self.session_speakers.append(speaker_name)
if speaker_name not in self.name_history:
self.add_validated_name(speaker_name)
if translated_name:
self.name_translations[speaker_name] = translated_name
def get_speaker_translation(self, speaker_name):
"""ดึงการแปลชื่อที่เคยแปลไว้"""
return self.name_translations.get(speaker_name)
def get_last_speaker(self):
"""ดึงชื่อล่าสุดที่ validate แล้ว"""
return self.last_speaker
def get_recent_names(self):
"""ดึงประวัติชื่อที่ validate แล้ว"""
return self.name_history
def get_speaker_style(self, speaker_name):
"""ดึงรูปแบบการพูดของตัวละคร"""
return self.speaker_styles.get(speaker_name, "")
def clear(self):
"""ล้าง cache"""
self.name_history.clear()
self.last_speaker = None
def clear_session(self):
"""ล้างข้อมูลเซสชั่น"""
self.session_speakers.clear()
self.name_translations.clear()
self.speaker_styles.clear() # เพิ่มการล้าง speaker_styles
self.last_speaker = None
def add_validated_name(self, name):
"""เพิ่มชื่อที่ผ่านการ validate แล้วเท่านั้น"""
if name and name != self.last_speaker:
self.last_speaker = name
if name not in self.name_history:
self.name_history.append(name)
if len(self.name_history) > self.MAX_HISTORY:
self.name_history.pop(0)
def add_speaker(self, speaker_name, translated_name=None):
"""เพิ่มชื่อผู้พูดในเซสชั่น"""
if speaker_name:
if speaker_name not in self.session_speakers:
self.session_speakers.append(speaker_name)
self.last_speaker = speaker_name
if translated_name:
self.name_translations[speaker_name] = translated_name
def get_speaker_translation(self, speaker_name):
"""ดึงการแปลชื่อที่เคยแปลไว้"""
return self.name_translations.get(speaker_name)
def get_last_speaker(self):
"""ดึงชื่อล่าสุดที่ validate แล้ว"""
return self.last_speaker
def get_recent_names(self):
"""ดึงประวัติชื่อที่ validate แล้ว"""
return self.name_history
def get_speaker_style(self, speaker_name):
"""ดึงรูปแบบการพูดของตัวละคร"""
return self.speaker_styles.get(speaker_name, "")
def clear(self):
"""ล้าง cache"""
self.name_history.clear()
self.last_speaker = None
def clear_session(self):
"""ล้างข้อมูลเซสชั่น"""
self.session_speakers.clear()
self.name_translations.clear()
self.speaker_styles.clear() # เพิ่มการล้าง speaker_styles
self.last_speaker = None
class Translator:
def __init__(self, settings=None):
self.api_key = os.getenv("OPENAI_API_KEY")
if not self.api_key:
raise ValueError("OPENAI_API_KEY not found in .env file")
self.client = OpenAI(api_key=self.api_key)
self.translation_logger = TranslationLogger()
# ใช้ settings object ถ้ามี
if settings:
api_params = settings.get_api_parameters()
self.model = api_params.get("model", "gpt-4o")
self.max_tokens = api_params.get("max_tokens", 500)
self.temperature = api_params.get("temperature", 0.7)
self.top_p = api_params.get("top_p", 0.9)
else:
# ถ้าไม่มี settings ให้โหลดจากไฟล์
try:
with open("settings.json", "r") as f:
settings_data = json.load(f)
api_params = settings_data.get("api_parameters", {})
self.model = api_params.get("model", "gpt-4o")
self.max_tokens = api_params.get("max_tokens", 500)
self.temperature = api_params.get("temperature", 0.7)
self.top_p = api_params.get("top_p", 0.9)
except (FileNotFoundError, json.JSONDecodeError):
self.model = "gpt-4o"
self.max_tokens = 500
self.temperature = 0.7
self.top_p = 0.9
logging.warning("Could not load settings.json, using default values")
self.cache = DialogueCache()
self.last_translations = {}
self.character_names_cache = set()
self.text_corrector = TextCorrector()
self.load_npc_data()
self.load_example_translations()
def get_current_parameters(self):
"""Return current translation parameters"""
return {
"model": self.model, # สำหรับ GPT ใช้ค่าเดียวกันทั้ง model และ displayed_model
"displayed_model": self.model,
"max_tokens": self.max_tokens,
"temperature": self.temperature,
"top_p": self.top_p,
}
def load_npc_data(self):
try:
with open("NPC.json", "r", encoding="utf-8") as file:
npc_data = json.load(file)
self.character_data = npc_data["main_characters"]
self.context_data = npc_data["lore"]
self.character_styles = npc_data["character_roles"]
# Update character_names_cache
self.character_names_cache = set() # เคลียร์ก่อน
self.character_names_cache.add("???") # เพิ่ม ??? เป็นลำดับแรก
# Load main characters
for char in self.character_data:
self.character_names_cache.add(char["firstName"])
if char["lastName"]:
self.character_names_cache.add(
f"{char['firstName']} {char['lastName']}"
)
# Load NPCs
for npc in npc_data["npcs"]:
self.character_names_cache.add(npc["name"])
print(
"Translator: Loaded character names:", self.character_names_cache
) # Debug log
# เพิ่มรูปแบบการพูดเข้า cache
for name, style in self.character_styles.items():
self.cache.speaker_styles[name] = style
# ตรวจสอบว่ามี style สำหรับ ???
if "???" not in self.character_styles:
self.character_styles["???"] = "ใช้ภาษาที่เป็นปริศนา ชวนให้สงสัยในตัวตน"
self.cache.speaker_styles["???"] = self.character_styles["???"]
except FileNotFoundError:
raise FileNotFoundError("NPC.json file not found")
except json.JSONDecodeError:
raise ValueError("Invalid JSON in NPC.json")
def load_example_translations(self):
self.example_translations = {
# ตัวอย่างการแปลข้อความสั้น
"'Tis": "ช่างเป็น...",
"'I do": "ฉันเข้าใจ",
"'do": "ฉันเข้าใจ",
"'Twas": "มันเคยเป็น...",
"Nay": "หามิได้",
"Aye": "เป็นเช่นนั้น",
"Mayhaps": "บางที...",
"Hm...": "อืม...",
"Wait!": "เดี๋ยวก่อน!",
"My friend...": "สหายข้า...",
"Tataru?": "Tataru เหรอ?",
"Estinien!": "Estinien!",
"sigh": "เฮ่อ..",
"Hmph.": "ฮึ่ม.",
# ตัวอย่างข้อความประโยคยาว
"Y'shtola: The aetheric fluctuations in this area are most peculiar. We should proceed with caution.": "Y'shtola: ความผันผวนของพลังอีเธอร์แถบนี้... น่าพิศวงยิ่งนัก เราควรก้าวต่อไปด้วยความระมัดระวัง",
"Alphinaud: The political implications of our actions here could be far-reaching. We must consider every possible outcome.": "Alphinaud: นัยทางการเมืองจากการกระทำของพวกเราในครั้งนี้ อาจส่งผลกระทบไปไกล เราต้องนึกถึงทุกความเป็นไปได้อย่างถี่ถ้วน",
"Alisaie: I won't stand idly by while others risk their lives. If we're to face this threat, we do so together.": "Alisaie: ฉันจะไม่ยืนดูดายในขณะที่คนอื่นเสี่ยงชีวิตหรอกนะ ถ้าเราต้องเผชิญหน้ากับภัยคุกคามนี้ เราก็จะสู้ไปด้วยกันนี่แหล่ะ!",
"Urianger: Pray, let us contemplate the implications of our recent discoveries. The path ahead may yet be fraught with unforeseen perils.": "Urianger: ข้าขอวิงวอน ให้พวกเราใคร่ครวญถึงนัยสำคัญแห่งการค้นพบล่าสุดของพวกเรา หนทางเบื้องหน้าอาจเต็มไปด้วยภยันตรายอันมิอาจคาดเดา",
"Thancred: Sometimes, you have to take risks. Calculated risks, mind you. But risks all the same.": "Thancred: บางครั้งเราก็ต้องเสี่ยงบ้างล่ะนะ เสี่ยงแบบคำนวณแล้วน่ะ แต่ก็ยังเป็นการเสี่ยงอยู่ดี",
}
def update_parameters(
self, model=None, max_tokens=None, temperature=None, top_p=None, **kwargs
):
"""อัพเดทค่าพารามิเตอร์สำหรับการแปล"""
try:
old_params = {
"model": self.model,
"max_tokens": self.max_tokens,
"temperature": self.temperature,
"top_p": self.top_p,
}
changes = []
if model is not None:
valid_models = ["gpt-4o", "gpt-4o-mini"]
if model not in valid_models:
raise ValueError(
f"Invalid model for GPT translator. Must be one of: {', '.join(valid_models)}"
)
self.model = model # model ID และ displayed_model เป็นค่าเดียวกันสำหรับ GPT
changes.append(f"Model: {old_params['model']} -> {model}")
if max_tokens is not None:
if not (100 <= max_tokens <= 1000):
raise ValueError(
f"Max tokens must be between 100 and 1000, got {max_tokens}"
)
self.max_tokens = max_tokens
changes.append(
f"Max tokens: {old_params['max_tokens']} -> {max_tokens}"
)
if temperature is not None:
if not (0.5 <= temperature <= 0.9):
raise ValueError(
f"Temperature must be between 0.5 and 0.9, got {temperature}"
)
self.temperature = temperature
changes.append(
f"Temperature: {old_params['temperature']} -> {temperature}"
)
if top_p is not None:
if not (0.5 <= top_p <= 0.9):
raise ValueError(f"Top P must be between 0.5 and 0.9, got {top_p}")
self.top_p = top_p
changes.append(f"Top P: {old_params['top_p']} -> {top_p}")
if changes:
print("\n=== GPT Parameters Updated ===")
for change in changes:
print(change)
print(f"Current model: {self.model}")
print("==========================\n")
return True, None
except ValueError as e:
print(f"[GPT] Parameter update failed: {str(e)}")
return False, str(e)
def translate(
self, text, source_lang="English", target_lang="Thai", is_choice_option=False
):
"""
แปลข้อความพร้อมจัดการบริบทของตัวละคร
Args:
text: ข้อความที่ต้องการแปล
source_lang: ภาษาต้นฉบับ (default: English)
target_lang: ภาษาเป้าหมาย (default: Thai)
is_choice_option: เป็นข้อความตัวเลือกหรือไม่ (default: False)
Returns:
str: ข้อความที่แปลแล้ว
"""
try:
if not text:
logging.warning("Empty text received for translation")
return ""
# ใช้ text_corrector instance ที่สร้างไว้แล้ว
speaker, content, dialogue_type = (
self.text_corrector.split_speaker_and_content(text)
)
# เพิ่มการตรวจสอบพิเศษสำหรับ 22
if text.strip() in ["22", "22?", "222", "222?"]:
return "???"
# กรณีพิเศษสำหรับ ??? หรือ 222
if text.strip() in ["222", "222?", "???"]:
return "???"
# ตรวจสอบว่าเป็นข้อความตัวเลือกหรือไม่
if not is_choice_option:
is_choice, prompt_part, choices = self.is_similar_to_choice_prompt(text)
if is_choice:
return self.translate_choice(text)
# กรณีมีชื่อผู้พูด
if dialogue_type == DialogueType.CHARACTER and speaker:
# กรณีพิเศษสำหรับ ???
if speaker.startswith("?"):
speaker = "???"
character_name = speaker
dialogue = content
# ตรวจสอบ cache สำหรับการแปล
if (
dialogue in self.last_translations
and character_name == self.cache.get_last_speaker()
):
translated_dialogue = self.last_translations[dialogue]
return f"{character_name}: {translated_dialogue}"
# 1. ดึงข้อมูลพื้นฐานของตัวละคร
character_info = self.get_character_info(character_name)
context = ""
if character_info:
context = (
f"Character: {character_info['firstName']}, "
f"Gender: {character_info['gender']}, "
f"Role: {character_info['role']}, "
f"Relationship: {character_info['relationship']}"
)
elif character_name == "???":
context = "Character: Unknown, Role: Mystery character"
# 2. ดึงรูปแบบการพูด
character_style = self.character_styles.get(character_name, "")
if not character_style and character_name == "???":
character_style = (
"ใช้ภาษาที่เป็นปริศนา ชวนให้สงสัยในตัวตน แต่ยังคงบุคลิกที่น่าสนใจ"
)
self.cache.add_speaker(character_name)
else:
# กรณีข้อความทั่วไป
dialogue = text
character_name = ""
context = ""
character_style = ""
# สร้าง prompt และแปล
special_terms = self.context_data.copy()
example_prompt = "Here are examples of good translations:\\n\\n"
for eng, thai in self.example_translations.items():
example_prompt += f"English: {eng}\\nThai: {thai}\\n\\n"
prompt = (
"You are a professional translator specializing in video game localization for Final Fantasy XIV. "
"Your task is to translate English game text to Thai with these requirements:\\n"
"1. Translate the text naturally while preserving the character's tone and style\\n"
"2. Keep proper nouns and character names in English\\n"
"3. For very short text, treat it as either: phrase, exclamation, or name calling only\\n"
"4. If the text contains unclear parts, translate what you can understand and mark unclear parts with [...]\\n"
"5. Maintain character speech patterns and emotional expressions\\n"
"6. Use ellipsis (...) or em dash (—) for pauses as in the original\\n"
"7. Avoid polite particles unless part of character's style\\n"
"8. Focus on natural, conversational Thai that matches the game context\\n"
f"Context: {context}\\n"
f"Character's style: {character_style}\\n"
f"Do not translate: {', '.join(self.character_names_cache)}\\n\\n"
"Special terms:\\n"
)
for term, explanation in special_terms.items():
prompt += f"{term}: {explanation}\\n"
prompt += f"\\n{example_prompt}\\nText to translate: {dialogue}"
try:
response = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": dialogue},
],
max_tokens=self.max_tokens,
temperature=self.temperature,
top_p=self.top_p,
)
translated_dialogue = response.choices[0].message.content.strip()
# เพิ่มการบันทึก log ตรงนี้
try:
self.translation_logger.log_translation(text, translated_dialogue)
except Exception as e:
logging.error(f"Error logging translation: {e}")
# ทำความสะอาดข้อความแปล
translated_dialogue = re.sub(
r"\b(ครับ|ค่ะ|ครับ/ค่ะ)\b", "", translated_dialogue
).strip()
for term in special_terms:
translated_dialogue = re.sub(
r"\b" + re.escape(term) + r"\b",
term,
translated_dialogue,
flags=re.IGNORECASE,
)
# บันทึกลง cache
self.last_translations[dialogue] = translated_dialogue
if character_name:
self.cache.add_validated_name(character_name) # เพิ่มชื่อเข้า cache
return f"{character_name}: {translated_dialogue}"
return translated_dialogue
except ValueError as e:
logging.error(f"Error in is_similar_to_choice_prompt: {str(e)}")
return self.translate_choice(text)
except Exception as e:
logging.error(f"Unexpected error in translation: {str(e)}")
return f"[Error: {str(e)}]"
def is_similar_to_choice_prompt(self, text, threshold=0.8):
"""
ตรวจสอบและแยกส่วนประกอบของ choice dialogue
Returns:
tuple: (is_choice, prompt_part, choices)
"""
try:
# 1. ถ้าไม่มีข้อความหรือสั้นเกินไป ถือว่าไม่ใช่ choice
if not text or len(text) < 10:
return False, None, []
# 2. ตัวอย่างรูปแบบ header ที่ต้องตรวจจับ
choice_headers = [
"What will you say?",
"What will you do?",
"Select an option.",
"Choose your response.",
]
# 3. ตรวจสอบ header ตรงๆ
if not any(header.lower() in text.lower() for header in choice_headers):
return False, None, []
# 4. แยก header
header = "What will you say?"
remaining_text = text.replace(header, "").strip()
# 5. คำขึ้นต้นที่พบบ่อยในตัวเลือก - สำคัญมากห้ามลบ!
common_starts = [
"I suppose",
"I think",
"I will",
"I'll",
"I can",
"We should",
"We can",
"We will",
"We'll",
"Yes",
"No",
"Perhaps",
"Maybe",
"The ",
"But ",
"So ",
"You ",
"Let's",
"Please",
"Thank",
"Very",
]
# 6. ลองแยกด้วย ! หรือ . ก่อน
choices = [c.strip() for c in re.split("[!.]", remaining_text) if c.strip()]
# 7. ถ้าแยกไม่ได้ ใช้ common_starts
if len(choices) <= 1:
temp_text = remaining_text
choices = []
for start in common_starts:
if start in temp_text:
parts = temp_text.split(start)
if parts[0]:
choices.append(parts[0].strip())
temp_text = start + parts[1]
if temp_text:
choices.append(temp_text.strip())
# 8. ต้องมีอย่างน้อย 1 ตัวเลือก
if choices:
return True, header, choices
return False, None, []
except Exception as e:
logging.error(f"Error in is_similar_to_choice_prompt: {str(e)}")
return False, None, []
def translate_choice(self, text):
"""แปลข้อความตัวเลือกของผู้เล่น
Args:
text: ข้อความที่จะแปล เช่น "What will you say?\nOption 1\nOption 2"
Returns:
str: ข้อความที่แปลแล้ว เช่น "คุณจะพูดว่าอย่างไร?\nตัวเลือก 1\nตัวเลือก 2"
"""
try:
# 1. ตรวจสอบและแยกส่วนประกอบ
is_choice, header, choices = self.is_similar_to_choice_prompt(text)
if is_choice:
# 2. กำหนด header ภาษาไทยแบบคงที่
translated_header = "คุณจะพูดว่าอย่างไร?"
translated_choices = []
# 3. แปลเฉพาะส่วน choices โดยตัด header ออก
for choice in choices:
choice = choice.strip()
if not choice:
continue
# 4. แปลแต่ละตัวเลือก โดยใช้ is_choice_option=True
translated_choice = self.translate(choice, is_choice_option=True)
if translated_choice:
# 5. ตรวจสอบและป้องกันการซ้ำซ้อนกับ header
if translated_choice != translated_header:
translated_choices.append(translated_choice)
# 6. รวมผลลัพธ์ในรูปแบบที่ถูกต้อง
if translated_choices:
# ใช้ \n เพียงครั้งเดียวระหว่าง header และ choices
result = f"{translated_header}\n" + "\n".join(translated_choices)
logging.debug(f"Choice translation result: {result}")
return result
# 7. กรณีไม่มี choices ส่งคืนเฉพาะ header
return translated_header
# 8. กรณีไม่ใช่ข้อความตัวเลือก แปลปกติ
return self.translate(text)
except Exception as e:
logging.error(f"Error in translating choices: {str(e)}")
return f"[Error in choice translation: {str(e)}]"
def get_character_info(self, character_name):
if character_name == "???":
return {
"firstName": "???",
"gender": "unknown",
"role": "Mystery character",
"relationship": "Unknown/Mysterious",
"pronouns": {"subject": "ฉัน", "object": "ฉัน", "possessive": "ของฉัน"},
}
for char in self.character_data:
if (
character_name == char["firstName"]
or character_name == f"{char['firstName']} {char['lastName']}".strip()
):
return char
return None
def batch_translate(self, texts, batch_size=10):
"""แปลข้อความเป็นชุด"""
translated_texts = []
for i in range(0, len(texts), batch_size):
batch = texts[i : i + batch_size]
translated_batch = [self.translate(text) for text in batch]
translated_texts.extend(translated_batch)
return translated_texts
def analyze_translation_quality(self, original_text, translated_text):
"""วิเคราะห์คุณภาพการแปล"""
prompt = (
"As a translation quality assessor, evaluate the following translation from English to Thai. "
"Consider factors such as accuracy, naturalness, and preservation of the original tone and style. "
f"Original (English): {original_text}\n"
f"Translation (Thai): {translated_text}\n"
"Provide a brief assessment and a score out of 10."
)
try:
# เปลี่ยนเป็นการใช้ client ใหม่
response = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": "Assess the translation quality."},
],
max_tokens=200,
)
return response.choices[0].message.content.strip()
except Exception as e:
logging.error(f"Error in translation quality analysis: {str(e)}")
return "Unable to assess translation quality due to an error."
def reload_data(self):
"""โหลดข้อมูลใหม่และล้าง cache"""
print("Translator: Reloading NPC data...") # เพิ่มบรรทัดนี้
self.load_npc_data()
self.load_example_translations()
self.cache.clear_session()
self.last_translations.clear()
print("Translator: Data reloaded successfully") # เพิ่มบรรทัดนี้
if __name__ == "__main__":
try:
translator = Translator()
# ตัวอย่างการแปลข้อความเดี่ยว
test_cases = [
"Y'shtola: The aetheric fluctuations in this area are most peculiar.",
"Y'shtola: We should proceed with caution.",
"???: Who goes there?",
"What will you say?\nYes, of course.\nI'm not sure about this.",
"The wind howls through the ancient ruins.",
]
print("=== Translation Test Cases ===")
for text in test_cases:
translated = translator.translate(text)
print(f"\nOriginal: {text}")
print(f"Translation: {translated}")
except ValueError as e:
print(f"Error: {e}")
|