|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import json |
| 4 | +import subprocess |
| 5 | +import sys |
| 6 | +from pathlib import Path |
| 7 | +from typing import Dict, Any, Set |
| 8 | + |
| 9 | + |
| 10 | +def load_json(file_path: Path) -> Dict[str, Any]: |
| 11 | + with open(file_path, 'r', encoding='utf-8') as f: |
| 12 | + return json.load(f) |
| 13 | + |
| 14 | + |
| 15 | +def save_json(file_path: Path, data: Dict[str, Any]) -> None: |
| 16 | + with open(file_path, 'w', encoding='utf-8') as f: |
| 17 | + json.dump(data, f, ensure_ascii=False, indent=2) |
| 18 | + f.write('\n') |
| 19 | + |
| 20 | + |
| 21 | +def get_changed_keys(en_file: Path) -> Set[str]: |
| 22 | + # Get git diff to find which keys were added or modified in en_US.json. |
| 23 | + print("Getting git diff...", flush=True) |
| 24 | + |
| 25 | + try: |
| 26 | + result = subprocess.run( |
| 27 | + ['git', 'diff', 'HEAD~1', 'HEAD', '--', str(en_file)], |
| 28 | + capture_output=True, |
| 29 | + text=True, |
| 30 | + check=False, |
| 31 | + cwd=en_file.parent.parent |
| 32 | + ) |
| 33 | + |
| 34 | + print(f"Git diff return code: {result.returncode}", flush=True) |
| 35 | + |
| 36 | + if result.returncode != 0: |
| 37 | + print(f"Git diff error: {result.stderr}", flush=True) |
| 38 | + sys.exit(1) |
| 39 | + |
| 40 | + if not result.stdout.strip(): |
| 41 | + print("No diff found - file unchanged", flush=True) |
| 42 | + return set() |
| 43 | + |
| 44 | + # Parse diff output to extract changed keys. |
| 45 | + changed_keys = set() |
| 46 | + for line in result.stdout.split('\n'): |
| 47 | + if line.startswith('+') and not line.startswith('+++'): |
| 48 | + content = line[1:].strip() |
| 49 | + if content.startswith('"') and '":' in content: |
| 50 | + try: |
| 51 | + key = content.split('"')[1] |
| 52 | + changed_keys.add(key) |
| 53 | + except IndexError: |
| 54 | + continue |
| 55 | + |
| 56 | + return changed_keys |
| 57 | + |
| 58 | + except Exception as e: |
| 59 | + print(f"Exception in get_changed_keys: {e}", flush=True) |
| 60 | + sys.exit(1) |
| 61 | + |
| 62 | + |
| 63 | +def translate_keys(keys_dict: Dict[str, str], target_language: str) -> Dict[str, str]: |
| 64 | + # Use LLM to translate English strings to target language. |
| 65 | + prompt = f"""You are a professional translator working on localization for Harmonoid, a music player application. Translate the following JSON object from English to {target_language}. |
| 66 | +
|
| 67 | +CONTEXT: These strings are UI text for a music player app. They include terms related to music playback, playlists, albums, artists, audio settings, and media library management. |
| 68 | +
|
| 69 | +IMPORTANT RULES: |
| 70 | +1. Keep all JSON keys EXACTLY the same (do not translate keys) |
| 71 | +2. Only translate the VALUES |
| 72 | +3. Preserve any special formatting like quotes (\"\"), placeholders (\"M\", \"N\", \"X\", \"ENTRY\", \"PLAYLIST\", etc.) |
| 73 | +4. Maintain the same meaning, punctuation, capitalization, structure and formatting |
| 74 | +5. Use appropriate music/audio terminology for the target language |
| 75 | +6. Return ONLY the translated JSON object, no additional text |
| 76 | +7. Ensure the output is valid JSON |
| 77 | +8. Try to keep the same string length as the original string (if possible) |
| 78 | +
|
| 79 | +Input JSON: |
| 80 | +{json.dumps(keys_dict, ensure_ascii=False, indent=2)}""" |
| 81 | + |
| 82 | + print(f"Calling LLM...", flush=True) |
| 83 | + |
| 84 | + try: |
| 85 | + # Create the process with explicit stdin pipe |
| 86 | + process = subprocess.Popen( |
| 87 | + ['llm', '-m', 'github/gpt-5'], |
| 88 | + stdin=subprocess.PIPE, |
| 89 | + stdout=subprocess.PIPE, |
| 90 | + stderr=subprocess.PIPE, |
| 91 | + text=True |
| 92 | + ) |
| 93 | + |
| 94 | + # Write the prompt and close stdin to signal EOF |
| 95 | + stdout, stderr = process.communicate(input=prompt) |
| 96 | + returncode = process.returncode |
| 97 | + |
| 98 | + print(f"LLM returned with code {returncode}", flush=True) |
| 99 | + |
| 100 | + if returncode != 0: |
| 101 | + print(f"Error: {stderr}", flush=True) |
| 102 | + return keys_dict |
| 103 | + |
| 104 | + content = stdout.strip() |
| 105 | + |
| 106 | + if not content: |
| 107 | + print(f"Empty response from LLM", flush=True) |
| 108 | + return keys_dict |
| 109 | + |
| 110 | + # Strip markdown code block formatting if present. |
| 111 | + if content.startswith('```'): |
| 112 | + content = content.split('```')[1] |
| 113 | + if content.startswith('json'): |
| 114 | + content = content[4:] |
| 115 | + content = content.split('```')[0].strip() |
| 116 | + |
| 117 | + try: |
| 118 | + return json.loads(content) |
| 119 | + except json.JSONDecodeError as e: |
| 120 | + print(f"JSON error: {e}", flush=True) |
| 121 | + print(f"Content: {content[:200]}...", flush=True) |
| 122 | + return keys_dict |
| 123 | + except Exception as e: |
| 124 | + print(f"Exception calling LLM: {e}", flush=True) |
| 125 | + return keys_dict |
| 126 | + |
| 127 | + |
| 128 | +def main(): |
| 129 | + print("Starting translation script...", flush=True) |
| 130 | + |
| 131 | + # Setup paths. |
| 132 | + script_dir = Path(__file__).parent |
| 133 | + project_root = script_dir.parent.parent |
| 134 | + localizations_dir = project_root / "localizations" |
| 135 | + index_file = project_root / "index.json" |
| 136 | + en_file = localizations_dir / "en_US.json" |
| 137 | + |
| 138 | + print(f"Paths:", flush=True) |
| 139 | + print(f" project_root: {project_root}", flush=True) |
| 140 | + print(f" en_file: {en_file}", flush=True) |
| 141 | + |
| 142 | + if not en_file.exists(): |
| 143 | + print(f"Error: {en_file} not found", flush=True) |
| 144 | + sys.exit(1) |
| 145 | + |
| 146 | + # Load English localization file. |
| 147 | + en_data = load_json(en_file) |
| 148 | + print(f"Loaded {len(en_data)} keys from en_US.json", flush=True) |
| 149 | + |
| 150 | + # Get keys that were changed in the latest commit. |
| 151 | + changed_keys = get_changed_keys(en_file) |
| 152 | + |
| 153 | + if not changed_keys: |
| 154 | + print("No changed keys found - nothing to translate", flush=True) |
| 155 | + sys.exit(0) |
| 156 | + |
| 157 | + print(f"Found {len(changed_keys)} changed keys: {', '.join(sorted(changed_keys))}", flush=True) |
| 158 | + |
| 159 | + # Load list of available languages from index.json. |
| 160 | + if not index_file.exists(): |
| 161 | + print(f"Error: {index_file} not found", flush=True) |
| 162 | + sys.exit(1) |
| 163 | + |
| 164 | + languages = load_json(index_file) |
| 165 | + print(f"Loaded {len(languages)} languages", flush=True) |
| 166 | + |
| 167 | + # Translate changed keys for each language. |
| 168 | + for lang_info in languages: |
| 169 | + lang_code = lang_info['code'] |
| 170 | + lang_name = lang_info['name'] |
| 171 | + |
| 172 | + # Skip English since it's the source language. |
| 173 | + if lang_code == 'en_US': |
| 174 | + continue |
| 175 | + |
| 176 | + print(f"\n[{lang_code}] {lang_name}", flush=True) |
| 177 | + |
| 178 | + target_file = localizations_dir / f"{lang_code}.json" |
| 179 | + existing_data = load_json(target_file) if target_file.exists() else {} |
| 180 | + |
| 181 | + # Filter to only keys that need translation. |
| 182 | + keys_to_translate = {k: en_data[k] for k in changed_keys if k in en_data} |
| 183 | + |
| 184 | + if not keys_to_translate: |
| 185 | + print("Up to date", flush=True) |
| 186 | + continue |
| 187 | + |
| 188 | + print(f"Translating {len(keys_to_translate)} keys...", flush=True) |
| 189 | + |
| 190 | + # Translate in batches to avoid overwhelming the LLM. |
| 191 | + batch_size = 50 |
| 192 | + translated = {} |
| 193 | + keys = list(keys_to_translate.keys()) |
| 194 | + |
| 195 | + for i in range(0, len(keys), batch_size): |
| 196 | + batch_keys = keys[i:i + batch_size] |
| 197 | + batch_dict = {k: keys_to_translate[k] for k in batch_keys} |
| 198 | + |
| 199 | + batch_num = i // batch_size + 1 |
| 200 | + total_batches = (len(keys) + batch_size - 1) // batch_size |
| 201 | + print(f"Batch {batch_num}/{total_batches}", flush=True) |
| 202 | + |
| 203 | + batch_translated = translate_keys(batch_dict, lang_name) |
| 204 | + translated.update(batch_translated) |
| 205 | + |
| 206 | + # Merge translations with existing data and maintain key order from en_US.json. |
| 207 | + final_data = {**existing_data, **translated} |
| 208 | + ordered_data = {k: final_data.get(k, en_data[k]) for k in en_data.keys()} |
| 209 | + |
| 210 | + save_json(target_file, ordered_data) |
| 211 | + print(f"✓ Saved", flush=True) |
| 212 | + |
| 213 | + print("\n✓ Done", flush=True) |
| 214 | + |
| 215 | + |
| 216 | +if __name__ == "__main__": |
| 217 | + main() |
0 commit comments