Created
September 14, 2025 16:13
-
-
Save garudamods/e1b83db03ef9ff613566c99e8d7af6e9 to your computer and use it in GitHub Desktop.
Automatically applies translations from VNTranslator TM to RenPy translation files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| RenPy TM Replacer | |
| Automatically applies translations from VNTranslator TM to RenPy translation files | |
| Author: Fazx - GarudaMods | |
| Requirements: | |
| - RenPy translation files must be generated first using RenPy Launcher | |
| (Actions -> Generate Translations -> Select target language) | |
| - Translation memory file from VNTranslator (.db format) | |
| - RenPy translation directory containing .rpy files | |
| VNTranslator TM File Format: | |
| <engine>-<source_lang>-<target_lang>.db | |
| Examples: lmstudio-English-Japanese.db, deepl-en-ja.db, google-en-ja.db | |
| Usage Examples: | |
| # help and options | |
| python renpy_tm_replacer.py --help | |
| # basic usage - only replace empty translations | |
| python renpy_tm_replacer.py --tm="path/to/tm.db" --tl-dir="game/tl/Japanese" | |
| # replace empty translation with source text (if no translation found) | |
| python renpy_tm_replacer.py --tm="path/to/tm.db" --tl-dir="game/tl/Japanese" --no-empty | |
| # replace all translations (including existing ones) | |
| python renpy_tm_replacer.py --tm="path/to/tm.db" --tl-dir="game/tl/Japanese" --all-replace | |
| """ | |
| import os | |
| import sys | |
| import argparse | |
| import re | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple, Set | |
| import logging | |
| version = "1.1" | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s', | |
| stream=sys.stdout, | |
| force=True | |
| ) | |
| logger = logging.getLogger(__name__) | |
| try: | |
| import bson | |
| except ImportError: | |
| logger.error("bson library not found. Please install it with: pip install pymongo") | |
| sys.exit(1) | |
| class RenpyTranslationProcessor: | |
| def __init__(self, tm_file: str, tl_dir: str, no_empty: bool = False, all_replace: bool = False): | |
| self.tm_file = tm_file | |
| self.tl_dir = tl_dir | |
| """ | |
| no_empty: | |
| [true] empty translations will be replaced with source text | |
| [false] empty translations will remain empty if no translation found | |
| """ | |
| self.no_empty = no_empty | |
| """ | |
| all_replace: | |
| [true] all translations will be replaced | |
| [false] only empty translations will be replaced | |
| """ | |
| self.all_replace = all_replace | |
| self.translation_memory: Dict[str, str] = {} | |
| self.processed_files = 0 | |
| self.replaced_strings = 0 | |
| self.untranslated_strings: List[Tuple[str, str, str]] = [] # (file, line_num, text) | |
| self.tm_report_data: List[Dict] = [] | |
| self.mt_engine = "" | |
| self.source_lang = "" | |
| self.target_lang = "" | |
| logger.info(f"RenPy TM Replacer v{version}") | |
| if self.no_empty: | |
| logger.info("[ON] No Empty") | |
| else: | |
| logger.info("[OFF] No Empty") | |
| if self.all_replace: | |
| logger.info("[ON] Force replace mode") | |
| else: | |
| logger.info("[OFF] Force replace mode") | |
| # print tm file and target translation dir | |
| logger.info(f"Translation memory file: {self.tm_file}") | |
| logger.info(f"Translation directory: {self.tl_dir}") | |
| # parse file name to get mt_engine and langs | |
| # format: <mt_engine>-<source_lang>-<target_lang>.db | |
| tm_file_name = os.path.basename(self.tm_file) | |
| match = re.match(r'^(.*?)-(.*?)-(.*?)\.db$', tm_file_name) | |
| if match: | |
| self.mt_engine, self.source_lang, self.target_lang = match.groups() | |
| logger.info(f"Parsed translation memory file: {self.mt_engine}, {self.source_lang}, {self.target_lang}") | |
| """ | |
| load translation memory from file | |
| structure data: [[<index>, {<object>}], ...] | |
| """ | |
| def load_translation_memory(self) -> bool: | |
| try: | |
| if not os.path.exists(self.tm_file): | |
| logger.error(f"Translation memory file not found: {self.tm_file}") | |
| return False | |
| # read file | |
| with open(self.tm_file, 'rb') as f: | |
| raw_data = f.read() | |
| # decode data | |
| try: | |
| data = bson.decode_all(raw_data) | |
| if data: | |
| tm_array = data[0] # assuming the array is the first data | |
| else: | |
| # try to decode as a single data | |
| tm_array = bson.decode(raw_data) | |
| except Exception as e: | |
| logger.error(f"Error decoding: {e}") | |
| return False | |
| # process translation memory dict | |
| # tm_array is a dict where keys are numeric indices and values are translation entries | |
| for key, entry_data in tm_array.items(): | |
| if isinstance(entry_data, dict): | |
| source = entry_data.get('what', '').strip() | |
| target = entry_data.get('translated', '').strip() | |
| if source and target: | |
| # store the mapping with original text (including quotes) | |
| self.translation_memory[source] = target | |
| # store without outer quotes for flexible matching | |
| source_clean = self._clean_quotes(source) | |
| target_clean = self._clean_quotes(target) | |
| if source_clean != source: | |
| self.translation_memory[source_clean] = target_clean | |
| # store report data | |
| self.tm_report_data.append({ | |
| 'key': key, | |
| 'id': entry_data.get('id', ''), | |
| 'source': source, | |
| 'target': target, | |
| 'status': entry_data.get('status', 0), | |
| 'type': entry_data.get('type', ''), | |
| 'order': entry_data.get('order', 0) | |
| }) | |
| logger.info(f"Loaded {len(self.translation_memory)} TM entries") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Error loading translation memory: {e}") | |
| return False | |
| """ | |
| clean outer quotes from a string if present | |
| """ | |
| def _clean_quotes(self, text: str) -> str: | |
| if len(text) >= 2 and text.startswith('"') and text.endswith('"'): | |
| return text[1:-1] | |
| return text | |
| """ | |
| escape special characters in a string | |
| """ | |
| def _escape_string(self, text: str) -> str: | |
| text = text.replace('\\', '\\\\') # escape backslash (\ -> \\) | |
| text = text.replace('"', '\\"') # escape double quote | |
| return text | |
| """ | |
| unescape special characters in a string or reverse the escaping process | |
| """ | |
| def _unescape_string(self, text: str) -> str: | |
| text = text.replace('\\"', '"') | |
| text = text.replace('\\\\', '\\') | |
| return text | |
| """ | |
| find translation for a given source text | |
| """ | |
| def _find_translation(self, source_text: str) -> str: | |
| # direct match | |
| if source_text in self.translation_memory: | |
| return self.translation_memory[source_text] | |
| # try with quotes added | |
| quoted_source = f'"{source_text}"' | |
| if quoted_source in self.translation_memory: | |
| result = self.translation_memory[quoted_source] | |
| return self._clean_quotes(result) | |
| # try unescaped version | |
| unescaped = self._unescape_string(source_text) | |
| if unescaped in self.translation_memory: | |
| return self.translation_memory[unescaped] | |
| # try unescaped with quotes | |
| quoted_unescaped = f'"{unescaped}"' | |
| if quoted_unescaped in self.translation_memory: | |
| result = self.translation_memory[quoted_unescaped] | |
| return self._clean_quotes(result) | |
| return None | |
| """ | |
| process a single renpy translation file | |
| format: | |
| old "source text" | |
| new "" | |
| replace empty new with translation from memory | |
| returns number of replacements made | |
| """ | |
| def process_translation_file(self, file_path: str) -> int: | |
| try: | |
| with open(file_path, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| lines = content.split('\n') | |
| modified_lines = [] | |
| replacements_in_file = 0 | |
| i = 0 | |
| while i < len(lines): | |
| line = lines[i] | |
| # match "old" line pattern | |
| old_pattern = r'^(\s*)old\s+"(.*?)"(\s*)$' | |
| old_match = re.match(old_pattern, line) | |
| if old_match and i + 1 < len(lines): | |
| source_text = old_match.group(2) | |
| next_line = lines[i + 1] | |
| # check if next line is "new" with content or empty | |
| new_pattern = r'^(\s*)new\s+"(.*?)"(\s*)$' | |
| new_match = re.match(new_pattern, next_line) | |
| if new_match: | |
| current_translation = new_match.group(2) | |
| should_replace = False | |
| if self.all_replace: | |
| should_replace = True | |
| else: | |
| # only replace if current translation is empty | |
| should_replace = not current_translation or current_translation.strip() == "" | |
| if should_replace: | |
| translation = self._find_translation(source_text) | |
| if translation: | |
| # replace with translation | |
| escaped_translation = self._escape_string(translation) | |
| indent = new_match.group(1) | |
| trailing = new_match.group(3) | |
| modified_lines.append(line) | |
| modified_lines.append(f'{indent}new "{escaped_translation}"{trailing}') | |
| replacements_in_file += 1 | |
| i += 2 | |
| continue | |
| elif self.no_empty: | |
| # replace with source text | |
| escaped_source = self._escape_string(source_text) | |
| indent = new_match.group(1) | |
| trailing = new_match.group(3) | |
| modified_lines.append(line) | |
| modified_lines.append(f'{indent}new "{escaped_source}"{trailing}') | |
| replacements_in_file += 1 | |
| i += 2 | |
| continue | |
| else: | |
| # add to untranslated list | |
| self.untranslated_strings.append((file_path, i + 1, source_text)) | |
| else: | |
| # check for character dialogue pattern | |
| # pattern: # character "dialogue" | |
| block_pattern = r'^(\s*)#\s*(\w+)\s*"([^"]*)"' | |
| block_match = re.match(block_pattern, line) | |
| if block_match and i + 1 < len(lines): | |
| indent = block_match.group(1) | |
| character = block_match.group(2) | |
| dialogue = block_match.group(3) | |
| next_line = lines[i + 1] | |
| should_replace = False | |
| # match empty translation line: character "" | |
| translation_match = re.match(rf'^(\s*){character}\s*"(.*?)"', next_line) | |
| if translation_match: | |
| current_translation = translation_match.group(2) | |
| # check if should replace | |
| should_replace = False | |
| if self.all_replace: | |
| should_replace = True # Replace all translations | |
| else: | |
| # only replace if current translation is empty | |
| should_replace = not current_translation or current_translation.strip() == "" | |
| if should_replace: | |
| translation = self._find_translation(dialogue) | |
| if translation: | |
| # replace with translation | |
| escaped_translation = self._escape_string(translation) | |
| new_line = f'{translation_match.group(1)}{character} "{escaped_translation}"' | |
| modified_lines.append(line) | |
| modified_lines.append(new_line) | |
| replacements_in_file += 1 | |
| i += 2 | |
| continue | |
| elif self.no_empty: | |
| # replace with source text | |
| escaped_dialogue = self._escape_string(dialogue) | |
| new_line = f'{translation_match.group(1)}{character} "{escaped_dialogue}"' | |
| modified_lines.append(line) | |
| modified_lines.append(new_line) | |
| replacements_in_file += 1 | |
| i += 2 | |
| continue | |
| else: | |
| # add to untranslated list | |
| self.untranslated_strings.append((file_path, i + 2, dialogue)) | |
| # add current line if not processed above | |
| modified_lines.append(line) | |
| i += 1 | |
| # write back if changes were made | |
| if replacements_in_file > 0: | |
| modified_content = '\n'.join(modified_lines) | |
| with open(file_path, 'w', encoding='utf-8') as f: | |
| f.write(modified_content) | |
| logger.debug(f"--> {os.path.basename(file_path)}: {replacements_in_file} replacements") | |
| """ | |
| else: | |
| # try method 2 | |
| replacements_in_file = self._process_character_dialogue_blocks(content, file_path) | |
| if replacements_in_file > 0: | |
| logger.debug(f"--> {os.path.basename(file_path)}: {replacements_in_file} character dialogue replacements") | |
| """ | |
| return replacements_in_file | |
| except Exception as e: | |
| logger.error(f"Error processing file {file_path}: {e}") | |
| return 0 | |
| """ | |
| process translation blocks with # character "dialogue" and character "" pattern | |
| returns number of replacements made | |
| """ | |
| def _process_character_dialogue_blocks(self, content: str, file_path: str) -> int: | |
| lines = content.split('\n') | |
| modified_lines = [] | |
| replacements_in_file = 0 | |
| i = 0 | |
| while i < len(lines): | |
| line = lines[i] | |
| cus_pattern = r'^translate\s+\w+\s+\w+:' | |
| cus_match = re.match(cus_pattern, line) | |
| # check if this is a translation block start | |
| if cus_match and i + 1 < len(lines): | |
| modified_lines.append(line) | |
| i += 1 | |
| # process the translation block content | |
| while i < len(lines): | |
| current_line = lines[i] | |
| # check for line with character dialogue | |
| block_pattern = r'^(\s*)#\s*(\w+)\s*"([^"]*)"' | |
| block_match = re.match(block_pattern, current_line) | |
| if block_match: | |
| indent = block_match.group(1) | |
| character = block_match.group(2) | |
| dialogue = block_match.group(3) | |
| modified_lines.append(current_line) | |
| i += 1 | |
| # if empty translation line | |
| if i < len(lines): | |
| next_line = lines[i] | |
| empty_translation_match = re.match(rf'^(\s*){character}\s*""', next_line) | |
| if empty_translation_match: | |
| # check if should replace | |
| should_replace = self.all_replace or True | |
| if should_replace: | |
| translation = self._find_translation(dialogue) | |
| if translation: | |
| # replace with translation | |
| escaped_translation = self._escape_string(translation) | |
| new_line = f'{empty_translation_match.group(1)}{character} "{escaped_translation}"' | |
| modified_lines.append(new_line) | |
| replacements_in_file += 1 | |
| else: | |
| # keep original dialogue as fallback | |
| escaped_dialogue = self._escape_string(dialogue) | |
| new_line = f'{empty_translation_match.group(1)}{character} "{escaped_dialogue}"' | |
| modified_lines.append(new_line) | |
| replacements_in_file += 1 | |
| # add to untranslated list | |
| self.untranslated_strings.append((file_path, i + 1, dialogue)) | |
| i += 1 | |
| continue | |
| # check if have reached the end of translation block | |
| if current_line.strip() == '' or (current_line.strip() != '' and not current_line.startswith(' ')): | |
| if current_line.strip() != '': | |
| break | |
| modified_lines.append(current_line) | |
| i += 1 | |
| else: | |
| modified_lines.append(line) | |
| i += 1 | |
| if replacements_in_file > 0: | |
| modified_content = '\n'.join(modified_lines) | |
| with open(file_path, 'w', encoding='utf-8') as f: | |
| f.write(modified_content) | |
| return replacements_in_file | |
| """ | |
| process all .rpy files in the translation dir (game/tl/<language>) | |
| """ | |
| def process_translation_directory(self) -> bool: | |
| try: | |
| tl_path = Path(self.tl_dir) | |
| if not tl_path.exists(): | |
| logger.error(f"Translation directory not found: {self.tl_dir}") | |
| return False | |
| # find all .rpy files | |
| rpy_files = list(tl_path.glob("**/*.rpy")) | |
| if not rpy_files: | |
| logger.warning(f"No .rpy files found in {self.tl_dir}") | |
| return False | |
| logger.info(f"Found {len(rpy_files)} translation files to process") | |
| for rpy_file in rpy_files: | |
| replacements = self.process_translation_file(str(rpy_file)) | |
| self.replaced_strings += replacements | |
| self.processed_files += 1 | |
| return True | |
| except Exception as e: | |
| logger.error(f"Error processing translation directory: {e}") | |
| return False | |
| """ | |
| generate translation memory report | |
| """ | |
| def generate_tm_report(self) -> bool: | |
| try: | |
| report_file = "__translation-memory.txt" | |
| with open(report_file, 'w', encoding='utf-8') as f: | |
| f.write("TRANSLATION MEMORY REPORT\n") | |
| f.write("=" * 50 + "\n") | |
| f.write(f"TM Path: {self.tm_file}\n") | |
| f.write(f"Total entries loaded: {len(self.tm_report_data)}\n") | |
| f.write("-" * 50 + "\n") | |
| f.write("TRANSLATION ENTRIES:\n\n") | |
| for i, entry in enumerate(self.tm_report_data, 1): | |
| f.write(f"Entry {i}:\n") | |
| f.write(f" ID: {entry['id']}\n") | |
| f.write(f" Source: {entry['source']}\n") | |
| f.write(f" Target: {entry['target']}\n") | |
| f.write("\n") | |
| logger.info(f"Translation memory report generated: {report_file}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Error generating TM report: {e}") | |
| return False | |
| """ | |
| generate report of untranslated strings | |
| """ | |
| def generate_untranslated_report(self) -> bool: | |
| try: | |
| report_file = "__untranslated-strings.txt" | |
| with open(report_file, 'w', encoding='utf-8') as f: | |
| f.write("UNTRANSLATED STRINGS REPORT\n") | |
| f.write("=" * 50 + "\n") | |
| f.write(f"Total untranslated strings: {len(self.untranslated_strings)}\n") | |
| f.write(f"Files processed: {self.processed_files}\n") | |
| f.write(f"Strings replaced: {self.replaced_strings}\n") | |
| f.write("-" * 50 + "\n") | |
| if self.untranslated_strings: | |
| f.write("UNTRANSLATED STRINGS:\n\n") | |
| # Group by file | |
| by_file = {} | |
| for file_path, line_num, text in self.untranslated_strings: | |
| if file_path not in by_file: | |
| by_file[file_path] = [] | |
| by_file[file_path].append((line_num, text)) | |
| for file_path, strings in by_file.items(): | |
| f.write(f"File: {file_path}\n") | |
| for line_num, text in strings: | |
| f.write(f" Line {line_num}: {text}\n") | |
| f.write("\n") | |
| else: | |
| f.write("All strings have been translated!\n") | |
| logger.info(f"Untranslated strings report generated: {report_file}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Error generating untranslated report: {e}") | |
| return False | |
| def run(self) -> bool: | |
| logger.info("Starting...") | |
| # load tm | |
| if not self.load_translation_memory(): | |
| logger.error("Failed to load translation memory") | |
| return False | |
| # process translation files | |
| if not self.process_translation_directory(): | |
| logger.error("Failed to process translation directory") | |
| return False | |
| logger.info(f"Processing complete: {self.processed_files} files processed, {self.replaced_strings} strings replaced") | |
| # generate reports | |
| self.generate_tm_report() | |
| self.generate_untranslated_report() | |
| # summary | |
| logger.info("=" * 50) | |
| logger.info("PROCESSING SUMMARY") | |
| logger.info(f"Files processed: {self.processed_files}") | |
| logger.info(f"Strings replaced: {self.replaced_strings}") | |
| logger.info(f"Untranslated strings: {len(self.untranslated_strings)}") | |
| logger.info("Reports generated: __translation-memory.txt, untranslated_strings_report.txt") | |
| logger.info("Processing completed successfully!") | |
| return True | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="RenPy TM Replacer \nversion: " + version, | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| epilog=""" | |
| Examples: | |
| # basic usage - only replace empty translations | |
| python renpy_tm_replacer.py --tm="path/to/tm.db" --tl-dir="game/tl/Japanese" | |
| # fill empty translations with source text (if no translation found) | |
| python renpy_tm_replacer.py --tm="path/to/tm.db" --tl-dir="game/tl/Japanese" --no-empty | |
| # replace all translations (including existing ones) | |
| python renpy_tm_replacer.py --tm="path/to/tm.db" --tl-dir="game/tl/Japanese" --all-replace | |
| python renpy_tm_replacer.py --tm="X:\\vntranslator\\translation\\lmstudio-English-Japanese.db" --tl-dir="X:\\mygame\\game\\tl\\Japanese" --no-empty --all-replace | |
| """ | |
| ) | |
| parser.add_argument( | |
| '--tm', '-t', | |
| required=True, | |
| metavar='', | |
| help='Path to translation memory file (.db)' | |
| ) | |
| parser.add_argument( | |
| '--tl-dir', '-d', | |
| required=True, | |
| metavar='', | |
| help='Path to translation directory containing .rpy files' | |
| ) | |
| parser.add_argument( | |
| '--no-empty', '-n', | |
| action='store_true', | |
| help='Fill empty translations with source text (if no translation found)' | |
| ) | |
| parser.add_argument( | |
| '--all-replace', '-a', | |
| action='store_true', | |
| help='Replace all translations' | |
| ) | |
| parser.add_argument( | |
| '--verbose', '-v', | |
| action='store_true', | |
| help='Enable verbose logging' | |
| ) | |
| args = parser.parse_args() | |
| if args.verbose: | |
| logging.getLogger().setLevel(logging.DEBUG) | |
| # validate args | |
| if not os.path.exists(args.tm): | |
| logger.error(f"Translation memory file not found: {args.tm}") | |
| sys.exit(1) | |
| if not os.path.exists(args.tl_dir): | |
| logger.error(f"Translation directory not found: {args.tl_dir}") | |
| sys.exit(1) | |
| # create processor and run | |
| processor = RenpyTranslationProcessor(args.tm, args.tl_dir, args.no_empty, args.all_replace) | |
| try: | |
| success = processor.run() | |
| sys.exit(0 if success else 1) | |
| except KeyboardInterrupt: | |
| logger.info("Processing interrupted by user") | |
| sys.exit(1) | |
| except Exception as e: | |
| logger.error(f"Unexpected error: {e}") | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment