Datasets:
File size: 17,025 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 |
import anthropic
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
load_dotenv()
class TranslatorClaude:
def __init__(self, settings=None):
self.api_key = os.getenv('ANTHROPIC_API_KEY')
if not self.api_key:
raise ValueError("ANTHROPIC_API_KEY not found in .env file")
self.client = anthropic.Anthropic(api_key=self.api_key)
# ใช้ settings object ถ้ามี
if settings:
api_params = settings.get_api_parameters()
self.model = api_params.get('model', "claude-3-5-haiku-20241022")
self.displayed_model = api_params.get('displayed_model', "claude-3.5-haiku")
self.max_tokens = api_params.get('max_tokens', 500)
self.temperature = api_params.get('temperature', 0.7)
else:
# ถ้าไม่มี settings ให้ใช้ค่าเริ่มต้น
self.model = "claude-3-5-haiku-20241022"
self.displayed_model = "claude-3.5-haiku"
self.max_tokens = 500
self.temperature = 0.7
self.character_names_cache = set()
self.character_data = []
self.context_data = {}
self.character_styles = {}
self.character_names_cache.add("???")
self.load_npc_data()
self.load_example_translations()
print(f"[Claude API] Initialized with model: {self.displayed_model}")
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
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']}")
# Add NPCs to character_names_cache
for npc in npc_data['npcs']:
self.character_names_cache.add(npc['name'])
print("[Claude API] Successfully loaded NPC data")
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 = {
"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: บางครั้งเราก็ต้องเสี่ยงบ้างล่ะนะ เสี่ยงแบบคำนวณแล้วน่ะ แต่ก็ยังเป็นการเสี่ยงอยู่ดี"
}
print("[Claude API] Example translations loaded")
def update_parameters(self, model=None, max_tokens=None, temperature=None, **kwargs):
"""อัพเดทค่าพารามิเตอร์สำหรับการแปล"""
try:
changes = []
if model is not None:
old_model = self.model
# ตรวจสอบ model ID แทนชื่อที่แสดง
if model != "claude-3-5-haiku-20241022":
raise ValueError(f"Invalid model for Claude translator: {model}")
self.model = model
self.displayed_model = "claude-3.5-haiku" # ใช้ชื่อแสดงคงที่
changes.append(f"Model: {old_model} -> {model}")
if max_tokens is not None:
old_tokens = self.max_tokens
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_tokens} -> {max_tokens}")
if temperature is not None:
old_temp = self.temperature
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_temp} -> {temperature}")
if changes:
print("\n[Claude API] Parameters updated:")
for change in changes:
print(change)
print(f"Current model: {self.displayed_model}")
return True, None
except ValueError as e:
print(f"[Claude API] Parameter update failed: {str(e)}")
return False, str(e)
def is_valid_text(self, text):
"""ตรวจสอบความถูกต้องของข้อความ"""
return bool(re.search(r'\b\w{3,}\b', text))
def get_character_info(self, character_name):
"""ดึงข้อมูลตัวละคร"""
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 extract_character_name(self, text):
"""แยกชื่อตัวละครออกจากข้อความ"""
parts = text.split(':', 1)
if len(parts) > 1:
character_name = parts[0].strip()
if character_name in self.character_names_cache:
return character_name, parts[1].strip()
return "", text
def translate(self, text, source_lang="English", target_lang="Thai", force_translate=False):
"""แปลข้อความโดยใช้ Claude API"""
try:
print(f"[Claude API] Translating: {text}")
if not self.is_valid_text(text):
return ""
character_name, dialogue = self.extract_character_name(text)
character_info = self.get_character_info(character_name)
# สร้าง context สำหรับการแปล
context = ""
if character_info:
context = f"Character: {character_info['firstName']}, Gender: {character_info['gender']}, Role: {character_info['role']}, Relationship: {character_info['relationship']}"
elif character_name == "???":
context = "Character: Unknown, Role: Mystery character"
# ดึง character style
character_style = self.character_styles.get(character_name, "")
if character_name == "???":
character_style = "ใช้ภาษาที่เป็นปริศนา ชวนให้สงสัยในตัวตน แต่ยังคงบุคลิกที่น่าสนใจ"
# สร้าง prompt
system_prompt = (
"You are a professional translator specializing in video game localization for Final Fantasy XIV. "
"Translate the given English text to Thai with these requirements:\n"
"1. Keep the original tone and character's personality\n"
"2. Maintain character names and special terms in English\n"
"3. Use natural, conversational Thai that matches the game context\n"
"4. Use proper emotion and speech patterns\n"
"5. Use ellipsis (...) or em dash (—) for pauses\n"
"6. Avoid polite particles (ครับ/ค่ะ)\n"
"Provide only the translated text without explanations."
)
user_prompt = (
f"Context: {context}\n"
f"Character speaking style: {character_style}\n\n"
f"Do not translate these names: {', '.join(self.character_names_cache)}\n\n"
"Special terms:\n"
)
for term, explanation in self.context_data.items():
user_prompt += f"{term}: {explanation}\n"
user_prompt += f"\nText to translate: {dialogue}"
try:
response = self.client.messages.create(
model=self.model,
max_tokens=self.max_tokens,
temperature=self.temperature,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}]
)
translated_dialogue = response.content[0].text.strip()
# ตรวจสอบและแก้ไขชื่อตัวละคร
if translated_dialogue:
for name in self.character_names_cache:
if name in dialogue and name not in translated_dialogue:
translated_dialogue = translated_dialogue.replace(name, name)
translated_dialogue = re.sub(r'\b(ครับ|ค่ะ|ครับ/ค่ะ)\b', '', translated_dialogue).strip()
# เพิ่มชื่อตัวละครกลับเข้าไป
if character_name:
final_translation = f"{character_name}: {translated_dialogue}"
else:
final_translation = translated_dialogue
print(f"[Claude API] Translation complete")
return final_translation
except Exception as e:
print(f"[Claude API] Translation error: {str(e)}")
return f"[Translation Error: {str(e)}]"
except Exception as e:
print(f"[Claude API] Unexpected error: {str(e)}")
return ""
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 adaptive_translation(self, text, max_retries=3):
"""พยายามแปลซ้ำหากเกิดข้อผิดพลาด"""
for attempt in range(max_retries):
try:
translation = self.translate(text)
if translation:
return translation
except Exception:
if attempt == max_retries - 1:
return self.fallback_translation(text)
return self.fallback_translation(text)
def fallback_translation(self, text):
"""แปลแบบฉุกเฉินเมื่อไม่สามารถแปลปกติได้"""
return f"[ไม่สามารถแปลได้: {text}]"
def update_character_style(self, character_name, new_style):
"""อัพเดทสไตล์การพูดของตัวละคร"""
self.character_styles[character_name] = new_style
print(f"[Claude API] Updated style for {character_name}")
def reload_data(self):
"""โหลดข้อมูล NPC ใหม่"""
print("[Claude API] Reloading NPC data")
self.load_npc_data()
self.load_example_translations()
def get_current_parameters(self):
"""Return current translation parameters"""
return {
'model': self.model,
'displayed_model': self.displayed_model,
'max_tokens': self.max_tokens,
'temperature': self.temperature
}
def analyze_translation_quality(self, original_text, translated_text):
"""วิเคราะห์คุณภาพการแปล (ใช้เฉพาะเมื่อต้องการตรวจสอบ)"""
prompt = (
"As a translation quality assessor for Final Fantasy XIV, evaluate this translation:\n"
f"Original (English): {original_text}\n"
f"Translation (Thai): {translated_text}\n"
"Provide a brief assessment and score out of 10."
)
try:
response = self.client.messages.create(
model=self.model,
max_tokens=200,
temperature=0.7,
messages=[
{"role": "user", "content": prompt}
]
)
assessment = response.content[0].text.strip()
return assessment
except Exception as e:
print(f"[Claude API] Quality assessment error: {str(e)}")
return "Unable to assess translation quality."
# Example usage
if __name__ == "__main__":
try:
translator = TranslatorClaude()
# Single translation example
text_to_translate = "Y'shtola: The aetheric fluctuations in this area are most peculiar. We should proceed with caution."
translation = translator.translate(text_to_translate)
print(f"\nOriginal: {text_to_translate}")
print(f"Translation: {translation}")
# Unknown character example
unknown_character_text = "???: I apologize for startling you, but I have my reasons for lurking in the shadows."
unknown_translation = translator.translate(unknown_character_text)
print(f"\nOriginal: {unknown_character_text}")
print(f"Translation: {unknown_translation}")
# Batch translation example
texts_to_translate = [
"Urianger: Pray, let us consider the implications of our recent discoveries.",
"Wuk Lamat: Wow! This place is amazing! I can't wait to explore every nook and cranny!",
"Sphene: As princess of Alexandria, I must remain composed, but I admit this adventure excites me greatly."
]
print("\nBatch Translation Examples:")
batch_translations = translator.batch_translate(texts_to_translate)
for original, translated in zip(texts_to_translate, batch_translations):
print(f"\nOriginal: {original}")
print(f"Translation: {translated}")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}") |