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