MagiciteBabel / translator.py
iarcanar's picture
Upload 23 files
3bb13c3 verified
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}")