Can you make the code gather all the nonenglish texts (should ignore numbers and other non letters )from data folder json files. into 1 text, Translate everything with 1 call and put back translated versions? It takes a lot time to go thru file by file.
import os
import json
import re
import time
from transformers import pipeline
import torch
class GameTranslator:
def init(self):
print("Initializing the translation model. Please wait...")
self.model_name = "facebook/nllb-200-distilled-600M"
code
# 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
Assistant
def detect_engine(folder_path):
engines = set()
code
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)
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}")
return False
total_strings = 0
translated_strings = 0
if filepath.endswith('.rpy'):
# Updated regex pattern to match text within quotes
pattern = r'(\".*?\"|\'.*?\')'
matches = list(re.finditer(pattern, content))
texts = []
spans = []
for match in matches:
text = match.group(1)
if text.strip() and not text.startswith('#') and not text.startswith('python:'):
total_strings += 1
texts.append(text.strip('"\''))
spans.append(match.span(1))
# Batch translation
translations = translator.translate_batch(texts, source_lang)
# Replace original texts with translations
new_content = content
offset = 0
for (start, end), translated in zip(spans, translations):
translated_text = '"' + translated.replace('"', '\\"') + '"'
new_content = new_content[:start+offset] + translated_text + new_content[end+offset:]
offset += len(translated_text) - (end - start)
translated_strings = total_strings
elif filepath.endswith('.json'):
data = json.loads(content)
texts_to_translate = []
locations = []
def collect_texts(d, path=[]):
nonlocal total_strings
if isinstance(d, dict):
for key, value in d.items():
new_path = path + [key]
if isinstance(value, str) and not key.endswith(('Path', 'path', 'File', 'file', 'Image', 'image')):
if value.strip():
total_strings +=1
texts_to_translate.append(value)
locations.append(new_path)
elif isinstance(value, (dict, list)):
collect_texts(value, new_path)
elif isinstance(d, list):
for index, item in enumerate(d):
new_path = path + [index]
if isinstance(item, str):
if item.strip():
total_strings +=1
texts_to_translate.append(item)
locations.append(new_path)
elif isinstance(item, (dict, list)):
collect_texts(item, new_path)
collect_texts(data)
# Batch translation
translations = translator.translate_batch(texts_to_translate, source_lang)
translated_strings = len(translations)
def set_value_by_path(d, path, value):
for key in path[:-1]:
d = d[key]
d[path[-1]] = value
for path, translated in zip(locations, translations):
set_value_by_path(data, path, translated)
new_content = json.dumps(data, ensure_ascii=False, indent=2)
elif filepath.endswith(('.txt', '.wolf')):
# Updated regex pattern to match text within [TEXT] tags
pattern = r'\[TEXT\](.*?)\[/TEXT\]'
matches = list(re.finditer(pattern, content, re.DOTALL))
texts = []
spans = []
for match in matches:
text = match.group(1)
total_strings += 1
texts.append(text)
spans.append(match.span(1))
# Batch translation
translations = translator.translate_batch(texts, source_lang)
# Replace original texts with translations
new_content = content
offset = 0
for (start, end), translated in zip(spans, translations):
new_content = new_content[:start+offset] + translated + new_content[end+offset:]
offset += len(translated) - (end - start)
translated_strings = total_strings
else:
print(f"Skipping unsupported file: {filepath}")
return False
with open(filepath, 'w', encoding='utf-8') as f:
f.write(new_content)
elapsed_time = time.time() - start_time
print(f"Translated {translated_strings}/{total_strings} strings in '{filepath}' in {elapsed_time:.1f} seconds.")
return elapsed_time
def main():
translator = GameTranslator()
folder_path = input("Enter the game folder path: ")
source_lang = input("Enter the source language code (e.g., 'ja' for Japanese): ")
code
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...")
files_to_translate = []
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'):
files_to_translate.append(filepath)
elif engines[0] == "RPGMaker" and file.endswith('.json'):
files_to_translate.append(filepath)
elif engines[0] == "WolfRPG" and file.endswith(('.txt', '.wolf')):
files_to_translate.append(filepath)
elif engines[0] == "SRPGStudio" and file.endswith('.json'):
files_to_translate.append(filepath)
total_files = len(files_to_translate)
print(f"Found {total_files} files to translate")
total_time = 0
for i, filepath in enumerate(files_to_translate, 1):
file_time = process_file(filepath, translator, source_lang)
if file_time:
total_time += file_time
avg_time = total_time / i
remaining_time = avg_time * (total_files - i)
print(f"Estimated time remaining: {remaining_time:.1f} seconds\n")
print("Translation completed!")
if name == "main":
main()
Certainly! To optimize the translation process by batching all non-English texts from JSON files within the data folder into a single translation call, we can modify your existing script. This approach minimizes the number of API calls, significantly speeding up the translation process.
Below is the revised script with detailed explanations of the changes made to achieve this optimization:
python
import os
import json
import re
import time
from transformers import pipeline
import torch
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():
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,
batch_size=100 # Adjust based on your system's capacity
)
# 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 collect_texts_from_json(file_paths, source_lang):
all_texts = []
text_locations = [] # Tuple of (file_path, path_in_json)
for filepath in file_paths:
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
except UnicodeDecodeError:
try:
with open(filepath, 'r', encoding='shift-jis') as f:
data = json.load(f)
except Exception as e:
print(f"Skipping unreadable or invalid JSON file: {filepath}. Error: {e}")
continue
except json.JSONDecodeError as e:
print(f"JSON decode error in file: {filepath}. Error: {e}")
continue
def traverse(d, path=[]):
if isinstance(d, dict):
for key, value in d.items():
new_path = path + [key]
if isinstance(value, str):
# Ignore keys that are likely to be file paths or similar
if key.lower().endswith(('path', 'file', 'image')):
continue
# Ignore strings that are purely non-letter (e.g., numbers, symbols)
if not re.search('[A-Za-z]', value):
continue
# Optionally, add more language-specific checks here
all_texts.append(value)
text_locations.append((filepath, new_path))
elif isinstance(value, (dict, list)):
traverse(value, new_path)
elif isinstance(d, list):
for index, item in enumerate(d):
new_path = path + [index]
if isinstance(item, str):
if not re.search('[A-Za-z]', item):
continue
all_texts.append(item)
text_locations.append((filepath, new_path))
elif isinstance(item, (dict, list)):
traverse(item, new_path)
traverse(data)
return all_texts, text_locations
def apply_translations_to_json(translations, text_locations):
# Group translations by file
translations_by_file = {}
for translation, (filepath, path) in zip(translations, text_locations):
if filepath not in translations_by_file:
translations_by_file[filepath] = []
translations_by_file[filepath].append((path, translation))
for filepath, translated_items in translations_by_file.items():
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
except UnicodeDecodeError:
try:
with open(filepath, 'r', encoding='shift-jis') as f:
data = json.load(f)
except Exception as e:
print(f"Cannot open file for writing: {filepath}. Error: {e}")
continue
except json.JSONDecodeError as e:
print(f"JSON decode error when writing to file: {filepath}. Error: {e}")
continue
for path, translation in translated_items:
sub_data = data
for key in path[:-1]:
sub_data = sub_data[key]
sub_data[path[-1]] = translation
try:
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print(f"Translated and updated file: {filepath}")
except Exception as e:
print(f"Error writing to file: {filepath}. Error: {e}")
def process_individual_files(files_to_translate, translator, source_lang):
total_time = 0
total_files = len(files_to_translate)
for i, filepath in enumerate(files_to_translate, 1):
start_time = time.time()
if filepath.endswith('.rpy'):
# Process RenPy files individually
success = process_rpy_file(filepath, translator, source_lang)
elif filepath.endswith(('.txt', '.wolf')):
# Process other supported file types if needed
success = process_other_file(filepath, translator, source_lang)
else:
print(f"Skipping unsupported file: {filepath}")
continue
if success:
elapsed_time = time.time() - start_time
total_time += elapsed_time
avg_time = total_time / i
remaining_time = avg_time * (total_files - i)
print(f"Estimated time remaining: {remaining_time:.1f} seconds\n")
print("Translation of individual files completed!")
def process_rpy_file(filepath, translator, source_lang):
start_time = time.time()
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}")
return False
total_strings = 0
translated_strings = 0
# Updated regex pattern to match text within quotes
pattern = r'(\".*?\"|\'.*?\')'
matches = list(re.finditer(pattern, content))
texts = []
spans = []
for match in matches:
text = match.group(1)
if text.strip() and not text.startswith('#') and not text.startswith('python:'):
# Ignore strings without letters
inner_text = text.strip('"\'')
if not re.search('[A-Za-z]', inner_text):
continue
total_strings += 1
texts.append(inner_text)
spans.append(match.span(1))
# Batch translation
translations = translator.translate_batch(texts, source_lang)
# Replace original texts with translations
new_content = content
offset = 0
for (start, end), translated in zip(spans, translations):
translated_text = '"' + translated.replace('"', '\\"') + '"'
new_content = new_content[:start+offset] + translated_text + new_content[end+offset:]
offset += len(translated_text) - (end - start)
translated_strings = total_strings
with open(filepath, 'w', encoding='utf-8') as f:
f.write(new_content)
elapsed_time = time.time() - start_time
print(f"Translated {translated_strings}/{total_strings} strings in '{filepath}' in {elapsed_time:.1f} seconds.")
return True
def process_other_file(filepath, translator, source_lang):
# Implement similar to process_rpy_file if needed
# Placeholder for other file types
print(f"Processing file: {filepath} (No handler implemented)")
return False
def main():
translator = GameTranslator()
folder_path = input("Enter the game folder path: ").strip()
source_lang = input("Enter the source language code (e.g., 'ja' for Japanese): ").strip()
engines = detect_engine(folder_path)
if not engines:
print("Could not detect game engine. Please check the folder.")
return
print(f"Detected engine(s): {', '.join(engines)} - Starting translation...")
# Collect JSON files within the 'data' folder
data_folder = os.path.join(folder_path, 'data')
json_files = []
for root, dirs, files in os.walk(data_folder):
for file in files:
if file.endswith('.json'):
filepath = os.path.join(root, file)
json_files.append(filepath)
print(f"Found {len(json_files)} JSON files in 'data' folder to translate.")
if json_files:
# Collect all texts from JSON files
all_texts, text_locations = collect_texts_from_json(json_files, source_lang)
print(f"Collected {len(all_texts)} texts from JSON files for translation.")
if all_texts:
# Translate all texts in a single batch
start_translation = time.time()
translations = translator.translate_batch(all_texts, source_lang)
end_translation = time.time()
print(f"Translated {len(translations)} texts in {end_translation - start_translation:.1f} seconds.")
# Apply translations back to JSON files
apply_translations_to_json(translations, text_locations)
else:
print("No texts found to translate in JSON files.")
# Process other files individually (e.g., .rpy, .txt, .wolf)
# This part remains the same as in your original script
files_to_translate = []
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)
# Depending on the engine, add files to translate
if 'RenPy' in engines and file.endswith('.rpy'):
files_to_translate.append(filepath)
elif 'RPGMaker' in engines and file.endswith('.json') and 'data' not in root:
files_to_translate.append(filepath)
elif 'WolfRPG' in engines and file.endswith(('.txt', '.wolf')):
files_to_translate.append(filepath)
elif 'SRPGStudio' in engines and file.endswith('.json') and 'data' not in root:
files_to_translate.append(filepath)
total_files = len(files_to_translate)
print(f"Found {total_files} additional files to translate.")
if total_files > 0:
process_individual_files(files_to_translate, translator, source_lang)
else:
print("No additional files found for individual translation.")
print("Translation completed!")
if __name__ == "__main__":
main()
Key Modifications and Enhancements:
Batch Processing for JSON Files in data Folder:
collect_texts_from_json Function:
Traverses all JSON files within the data folder.
Extracts all translatable strings while ignoring keys related to paths or files ('path', 'file', 'image').
Ignores strings that do not contain any letters to ensure non-letter strings (like numbers or symbols) are not translated.
Collects both the texts and their locations (file path and JSON path) for mapping translations back.
apply_translations_to_json Function:
Maps the translated texts back to their respective locations in the original JSON files.
Writes the updated JSON content back to the files with proper formatting.
Optimized translate_batch Method:
Introduced a batch_size parameter to the translate_batch method to handle large batches efficiently. You can adjust the batch_size based on your system's capabilities.
Enhanced File Processing:
process_individual_files Function:
Handles the translation of individual files that are not part of the data JSON batching process (e.g., .rpy, .txt, .wolf files).
Provides placeholders (process_other_file) for handling additional file types as needed.
process_rpy_file Function:
Processes RenPy .rpy files individually, extracting, translating, and replacing strings within the file.
Engine Detection and File Categorization:
Modified the engine detection to handle multiple engines if present.
Ensured that JSON files within the data folder are only processed in batch, while other JSON files related to the engine are processed individually.
Error Handling and Robustness:
Enhanced error handling for file reading and JSON parsing to skip unreadable or malformed files without stopping the entire translation process.
Additional Recommendations:
Language Detection (Optional):
If your dataset contains multiple source languages or you want to ensure that only non-English texts are translated, consider integrating a language detection library like langdetect or fasttext to automatically identify and filter texts that need translation.
Logging:
For better monitoring and debugging, implement a logging mechanism instead of using print statements. The logging module in Python can provide different logging levels and better control over output formats.
Translation Model:
Ensure that the facebook/nllb-200-distilled-600M model supports the source and target languages you intend to use. You might need to adjust the lang_codes dictionary based on your specific language requirements.
Performance Optimization:
Translating very large batches in one go might cause memory issues or timeouts. Monitor the performance and adjust the batch_size accordingly.
Consider saving intermediate results or implementing checkpoints to handle interruptions gracefully.
Execution Steps:
Install Required Libraries:
Ensure that you have the necessary libraries installed. You can install them using pip:
bash
pip install transformers torch langdetect
Run the Script:
Execute the script in your Python environment:
bash
python your_script_name.py
Provide Inputs:
When prompted, enter the path to your game folder.
Enter the source language code (e.g., ja for Japanese).
Monitor Progress:
The script will display progress messages indicating how many texts have been collected, translated, and updated in each file.
Completion:
Upon completion, all applicable JSON files in the data folder will have their non-English texts translated, and other supported files will be processed individually.
By implementing these modifications, the translation process becomes significantly more efficient by reducing the number of translation API calls and handling large batches of texts seamlessly. This approach not only speeds up the translation but also ensures consistency across all translated texts.