Certainly! To optimize your translation process by aggregating all translatable texts across multiple files and performing a single translation call, you can restructure your script as follows:
-
Collect All Translatable Texts:
- Traverse through all relevant files and extract texts that need translation.
- Store their file paths and their specific locations within the files.
-
Filter Non-English Texts:
- Ensure that only non-English texts are collected.
- Ignore numbers and non-letter characters as per your requirement.
-
Perform a Single Translation Call:
- Concatenate all collected texts and send them to the translation model in one batch.
- Receive all translations at once.
-
Distribute Translations Back:
- Map the translated texts back to their respective locations in the original files.
- Write the translated content back to the files.
Below is the revised script implementing this approach:
import os
import json
import re
import time
from transformers import pipeline
import torch
from collections import defaultdict
class GameTranslator:
def __init__(self):
print("Initializing the translation model. Please wait...")
self.model_name = "facebook/nllb-200-distilled-600M"
# Check if CUDA is available and has enough memory
if torch.cuda.is_available() and torch.cuda.get_device_properties(0).total_memory > 4 * 1024 * 1024 * 1024:
self.device = 0
print("Using GPU for translation")
else:
self.device = -1
print("Using CPU for translation")
self.translator = pipeline("translation",
model=self.model_name,
device=self.device)
self.lang_codes = {
'en': 'eng_Latn', 'ja': 'jpn_Jpan', 'zh': 'zho_Hans',
'ko': 'kor_Hang', 'ru': 'rus_Cyrl', 'fr': 'fra_Latn',
'de': 'deu_Latn', 'es': 'spa_Latn', 'it': 'ita_Latn',
'pt': 'por_Latn'
}
def translate_batch(self, texts, source_lang):
if not texts:
return []
source_code = self.lang_codes.get(source_lang, 'eng_Latn')
target_code = 'eng_Latn'
try:
results = self.translator(texts,
src_lang=source_code,
tgt_lang=target_code)
# Handle the case where results may not be a list
if isinstance(results, dict):
results = [results]
translations = [res['translation_text'] for res in results]
return translations
except Exception as e:
print(f"Translation error: {e}")
# Return original texts in case of error
return texts
def detect_engine(folder_path):
engines = set()
for root, dirs, files in os.walk(folder_path):
if any(f.endswith('.rpy') for f in files) and 'game' in dirs:
engines.add('RenPy')
if any(f in files for f in ['Game.rpgproject', 'RPG_RT.lmt', 'RPG_RT.ldb', 'RPG_RT.ini']):
engines.add('RPGMaker')
elif any(f.endswith('.json') and 'data' in dirs for f in files):
engines.add('RPGMaker')
if any(f.endswith('.wolf') for f in files) or 'Data.wolf' in files or 'Data' in dirs:
engines.add('WolfRPG')
if 'Runtime.json' in files or any(f.startswith('srpg_studio') for f in files):
engines.add('SRPGStudio')
if any(f.endswith('.ks') for f in files) or 'tyrano' in dirs:
engines.add('TyranoBuilder')
if 'ProjectSettings' in dirs and 'Assets' in dirs:
engines.add('Unity')
if 'Content' in dirs and 'Config' in dirs:
engines.add('UnrealEngine')
if any(f.endswith('.tscn') for f in files) or 'project.godot' in files:
engines.add('Godot')
return list(engines)
def is_text_translatable(text, source_lang_code):
# Simple heuristic: Check if the text contains non-English letters
# Adjust this function based on your specific needs
if not text.strip():
return False
# Remove numbers and non-letter characters
cleaned_text = re.sub(r'[^A-Za-z]', '', text)
if cleaned_text:
# Assume it's English if it has only Latin letters
# You can enhance this detection as needed
return False
return True
def collect_texts(folder_path, engines, source_lang):
collected = []
file_text_map = defaultdict(list) # file_path -> list of (original_text, location_info)
for root, _, files in os.walk(folder_path):
for file in files:
if file == 'Animations.json':
continue # Skip Animations.json
filepath = os.path.join(root, file)
if engines[0] == "RenPy" and file.endswith('.rpy'):
file_type = 'rpy'
elif engines[0] == "RPGMaker" and file.endswith('.json'):
file_type = 'json'
elif engines[0] == "WolfRPG" and file.endswith(('.txt', '.wolf')):
file_type = 'wolf'
elif engines[0] == "SRPGStudio" and file.endswith('.json'):
file_type = 'json'
else:
continue # Unsupported file type for detected engine
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
except UnicodeDecodeError:
try:
with open(filepath, 'r', encoding='shift-jis') as f:
content = f.read()
except:
print(f"Skipping unreadable file: {filepath}")
continue
if file_type == 'rpy':
pattern = r'(\".*?\"|\'.*?\')'
matches = list(re.finditer(pattern, content))
for match in matches:
text = match.group(1).strip('"\'')
if text and is_text_translatable(text, source_lang):
collected.append(text)
file_text_map[filepath].append(('rpy', match.span(1), text))
elif file_type == 'json':
try:
data = json.loads(content)
except json.JSONDecodeError:
print(f"Skipping invalid JSON file: {filepath}")
continue
def collect_from_json(d, path=[]):
if isinstance(d, dict):
for key, value in d.items():
new_path = path + [key]
if isinstance(value, str):
if is_text_translatable(value, source_lang):
collected.append(value)
file_text_map[filepath].append(('json', new_path, value))
elif isinstance(value, (dict, list)):
collect_from_json(value, new_path)
elif isinstance(d, list):
for index, item in enumerate(d):
new_path = path + [index]
if isinstance(item, str):
if is_text_translatable(item, source_lang):
collected.append(item)
file_text_map[filepath].append(('json', new_path, item))
elif isinstance(item, (dict, list)):
collect_from_json(item, new_path)
collect_from_json(data)
elif file_type == 'wolf':
pattern = r'\[TEXT\](.*?)\[/TEXT\]'
matches = list(re.finditer(pattern, content, re.DOTALL))
for match in matches:
text = match.group(1).strip()
if text and is_text_translatable(text, source_lang):
collected.append(text)
file_text_map[filepath].append(('wolf', match.span(1), text))
return collected, file_text_map
def apply_translations(file_text_map, translations, folder_path, engines, source_lang):
# Map from original text to translated text
translation_map = dict(zip([item[2] for items in file_text_map.values() for item in items], translations))
for filepath, entries in file_text_map.items():
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
except UnicodeDecodeError:
try:
with open(filepath, 'r', encoding='shift-jis') as f:
content = f.read()
except:
print(f"Skipping unreadable file during writing: {filepath}")
continue
if any(e[0] == 'rpy' for e in entries):
new_content = content
offset = 0
for entry in entries:
if entry[0] != 'rpy':
continue
span = entry[1]
original_text = entry[2]
translated_text = translation_map.get(original_text, original_text)
translated_text = '"' + translated_text.replace('"', '\\"') + '"'
new_content = new_content[:span[0]+offset] + translated_text + new_content[span[1]+offset:]
offset += len(translated_text) - (span[1] - span[0])
content = new_content
elif any(e[0] == 'json' for e in entries):
try:
data = json.loads(content)
except json.JSONDecodeError:
print(f"Skipping invalid JSON file during writing: {filepath}")
continue
for entry in entries:
if entry[0] != 'json':
continue
path = entry[1]
original_text = entry[2]
translated_text = translation_map.get(original_text, original_text)
# Navigate to the correct location in the JSON structure
def set_value(d, path, value):
for key in path[:-1]:
d = d[key]
d[path[-1]] = value
set_value(data, path, translated_text)
content = json.dumps(data, ensure_ascii=False, indent=2)
elif any(e[0] == 'wolf' for e in entries):
new_content = content
offset = 0
for entry in entries:
if entry[0] != 'wolf':
continue
span = entry[1]
original_text = entry[2]
translated_text = translation_map.get(original_text, original_text)
new_content = new_content[:span[0]+offset] + translated_text + new_content[span[1]+offset:]
offset += len(translated_text) - (span[1] - span[0])
content = new_content
# Write the updated content back to the file
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
print(f"Translated file: {filepath}")
def main():
translator = GameTranslator()
folder_path = input("Enter the game folder path: ").strip('"').strip("'")
source_lang = input("Enter the source language code (e.g., 'ja' for Japanese): ").lower()
engines = detect_engine(folder_path)
if not engines:
print("Could not detect game engine. Please check the folder.")
return
print(f"Detected engine: {engines[0]} - Starting translation...")
start_time = time.time()
# Step 1: Collect all translatable texts
collected_texts, file_text_map = collect_texts(folder_path, engines, source_lang)
total_strings = len(collected_texts)
print(f"Found {total_strings} strings to translate across {len(file_text_map)} files.")
if total_strings == 0:
print("No translatable texts found.")
return
# Step 2: Perform a single translation call
print("Translating all texts in a single batch...")
translations = translator.translate_batch(collected_texts, source_lang)
if len(translations) != total_strings:
print("Warning: Number of translations does not match number of original texts.")
# Step 3: Apply translations back to files
print("Applying translations back to files...")
apply_translations(file_text_map, translations, folder_path, engines, source_lang)
elapsed_time = time.time() - start_time
print(f"Translation completed in {elapsed_time:.1f} seconds.")
if __name__ == "__main__":
main()
Explanation of Changes
-
Function is_text_translatable:
- This function checks whether a given text is eligible for translation by verifying if it contains non-English letters.
- It removes numbers and non-letter characters and determines if the remaining text indicates a non-English language.
- You might need to enhance this logic based on the specific languages you're targeting.
-
Function collect_texts:
- Traverses all relevant files based on the detected game engine.
- Extracts texts using regex patterns tailored to each file type (e.g.,
.rpy, .json, .txt, .wolf).
- Filters out texts that contain only numbers or non-letter characters.
- Stores the texts along with their file paths and location information for later replacement.
-
Function apply_translations:
- Maps each original text to its translated counterpart.
- Updates the respective files by replacing the original texts with their translations.
- Handles different file types accordingly:
- RenPy (
.rpy): Replaces text within quotes.
- JSON (
.json): Navigates the JSON structure to replace string values.
- WolfRPG (
.txt, .wolf): Replaces text within [TEXT]...[/TEXT] tags.
-
Optimized Translation Call:
- After collecting all texts, they are sent to the translation model in one single batch (
translator.translate_batch).
- This reduces the overhead of multiple model calls and speeds up the overall translation process.
-
Handling File Reading/Writing:
- The script attempts to read files using
utf-8 encoding first, then falls back to shift-jis if necessary.
- Ensures that unreadable files are skipped gracefully without interrupting the entire process.
-
Progress Reporting:
- Provides feedback on the number of strings found and the progress of applying translations back to files.
Additional Recommendations
-
Memory Considerations:
- Translating all texts in a single call is efficient but may consume significant memory, especially for large projects.
- If you encounter memory issues, consider batching the translations into smaller chunks (e.g., 1000 texts per batch).
-
Language Detection:
- The current
is_text_translatable function uses a simple heuristic.
- For more accurate detection, consider integrating a language detection library like
langdetect or fasttext.
-
Error Handling:
- The script includes basic error handling. Depending on your needs, you might want to enhance it to handle specific exceptions or provide more detailed logging.
-
Backup Files:
- Before performing in-place translations, it's advisable to create backups of your original files to prevent data loss in case of unexpected issues.
-
Progress Indicators:
- For very large projects, integrating progress bars (e.g., using
tqdm) can provide real-time feedback on the translation progress.
Dependencies
Ensure you have the necessary libraries installed. You can install them using pip:
pip install transformers torch
Usage
-
Run the Script:
python translate_game.py
-
Provide Inputs:
- Game Folder Path: Enter the path to your game’s root folder.
- Source Language Code: Enter the language code of the original text (e.g.,
ja for Japanese).
The script will detect the game engine, collect all translatable texts, perform a single translation batch, and apply the translations back to the respective files.
Conclusion
By restructuring the script to aggregate all translatable texts and perform a single translation call, you can significantly reduce the processing time. This approach is efficient and leverages the capabilities of modern translation models effectively. Always ensure to test the script on a small subset of your project first to verify its correctness before applying it to the entire project.