-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18n.py
More file actions
362 lines (337 loc) · 14.1 KB
/
Copy pathi18n.py
File metadata and controls
362 lines (337 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"""
Internationalization (i18n) module for UnityScraper GUI
Supports multiple languages with easy extensibility
"""
import json
import logging
import re
from pathlib import Path
from typing import Dict, Optional
logger = logging.getLogger(__name__)
# Supported languages
SUPPORTED_LANGUAGES = ['en', 'es', 'fr', 'de', 'it', 'pt', 'ja']
LANGUAGE_CODE_RE = re.compile(r"^[a-z]{2,3}(?:-[A-Z]{2})?$")
# Translation strings
TRANSLATIONS = {
'en': {
'title': 'UnityScraper - Enhanced Edition',
'titleids': 'TitleIDs:',
'titleids_hint': 'Comma-separated (e.g., 555308C5,00000155)',
'output_dir': 'Output Dir:',
'browse': 'Browse',
'settings': 'Settings',
'workers': 'Workers:',
'rate_limit': 'Rate Limit (s):',
'timeout': 'Timeout (s):',
'max_retries': 'Max Retries:',
'bandwidth': 'Bandwidth (KB/s):',
'use_https': 'XboxUnity HTTP endpoints (required)',
'verify_checksums': 'Verify checksums',
'dry_run': 'Dry run (no downloads)',
'not_connected': 'Not connected',
'start_download': 'Start Download',
'stop': 'Stop',
'test_connection': 'Test Connection',
'retry_failed': 'Retry Failed',
'save_config': 'Save Config',
'load_config': 'Load Config',
'export_db': 'Export DB',
'show_stats': 'Show Stats',
'clear_log': 'Clear Log',
'log_output': 'Log Output',
'status_testing': 'Testing connection...',
'status_connected_https': 'Connected via HTTP',
'status_connected_http': '✓ Connected via HTTP',
'status_failed': '✗ Connection failed: {}',
'error_no_titleids': 'Please enter at least one TitleID',
'success_config_saved': 'Configuration saved',
'error_config_save': 'Failed to save config: {}',
'success_config_loaded': 'Configuration loaded',
'error_config_load': 'Failed to load config: {}',
'success_retry_completed': 'Failed downloads retry completed!',
'error_retry_failed': 'Retry failed: {}',
'success_export': 'Database exported successfully!',
'error_export': 'Export failed: {}',
'stats_title': 'Database Statistics',
'stats_titleids': 'Total TitleIDs: {}',
'stats_covers': 'Total Covers: {}',
'stats_updates': 'Total Updates: {}',
'stats_last_week': 'Downloads Last Week: {}',
'stats_most_scraped': 'Most Scraped:',
'verify_integrity': 'Verify file integrity',
'download_speed': 'Speed: {} MB/s',
'filter_status': 'Filter by Status:',
'filter_date': 'Filter by Date:',
'all': 'All',
'pending': 'Pending',
'downloaded': 'Downloaded',
'failed': 'Failed',
'nav_library': 'LIBRARY',
'nav_add_games': 'ADD GAMES',
'nav_downloads': 'DOWNLOADS',
'nav_backups': 'BACKUP MANAGER',
'nav_profiles': 'PROFILES & SAVES',
'nav_tools': 'TOOL CENTER',
'nav_collections': 'COLLECTIONS',
'nav_knowledge': 'KNOWLEDGE',
'nav_community': 'COMMUNITY HUB',
'nav_health': 'ARCHIVE HEALTH',
'nav_settings': 'SETTINGS',
'nav_about': 'HELP & ABOUT',
},
'es': {
'title': 'UnityScraper - Edición Mejorada',
'titleids': 'IDs de Título:',
'titleids_hint': 'Separados por comas (ej., 555308C5,00000155)',
'output_dir': 'Directorio de Salida:',
'browse': 'Examinar',
'settings': 'Configuración',
'workers': 'Trabajadores:',
'rate_limit': 'Límite de Velocidad (s):',
'timeout': 'Tiempo de Espera (s):',
'max_retries': 'Reintentos Máximos:',
'bandwidth': 'Ancho de Banda (KB/s):',
'use_https': 'XboxUnity HTTP endpoints (required)',
'verify_checksums': 'Verificar sumas de comprobación',
'dry_run': 'Ejecución de prueba (sin descargas)',
'not_connected': 'No conectado',
'start_download': 'Iniciar Descarga',
'stop': 'Detener',
'test_connection': 'Probar Conexión',
'retry_failed': 'Reintentar Fallos',
'save_config': 'Guardar Configuración',
'load_config': 'Cargar Configuración',
'export_db': 'Exportar BD',
'show_stats': 'Mostrar Estadísticas',
'clear_log': 'Limpiar Registro',
'log_output': 'Salida de Registro',
'status_testing': 'Probando conexión...',
'status_connected_https': 'Connected via HTTP',
'status_connected_http': '✓ Conectado vía HTTP',
'status_failed': '✗ Conexión fallida: {}',
'error_no_titleids': 'Ingrese al menos un ID de Título',
'success_config_saved': 'Configuración guardada',
'error_config_save': 'Error al guardar configuración: {}',
'success_config_loaded': 'Configuración cargada',
'error_config_load': 'Error al cargar configuración: {}',
'success_retry_completed': '¡Reintentos de descargas fallidas completados!',
'error_retry_failed': 'Reintento fallido: {}',
'success_export': '¡Base de datos exportada correctamente!',
'error_export': 'Error en exportación: {}',
'stats_title': 'Estadísticas de la Base de Datos',
'verify_integrity': 'Verificar integridad de archivos',
'download_speed': 'Velocidad: {} MB/s',
'filter_status': 'Filtrar por Estado:',
'filter_date': 'Filtrar por Fecha:',
},
'fr': {
'title': 'UnityScraper - Édition Améliorée',
'titleids': 'IDs de Titre:',
'titleids_hint': 'Séparés par des virgules (ex., 555308C5,00000155)',
'output_dir': 'Répertoire de Sortie:',
'browse': 'Parcourir',
'settings': 'Paramètres',
'workers': 'Travailleurs:',
'rate_limit': 'Limite de Débit (s):',
'timeout': 'Délai d\'Attente (s):',
'max_retries': 'Tentatives Maximales:',
'bandwidth': 'Largeur de Bande (KB/s):',
'use_https': 'XboxUnity HTTP endpoints (required)',
'verify_checksums': 'Vérifier les sommes de contrôle',
'dry_run': 'Essai (sans téléchargements)',
'not_connected': 'Non connecté',
'start_download': 'Démarrer le Téléchargement',
'stop': 'Arrêter',
'test_connection': 'Tester la Connexion',
'retry_failed': 'Réessayer les Échecs',
'save_config': 'Enregistrer la Configuration',
'load_config': 'Charger la Configuration',
'export_db': 'Exporter BD',
'show_stats': 'Afficher les Statistiques',
'clear_log': 'Effacer le Journal',
'log_output': 'Sortie du Journal',
'status_testing': 'Test de connexion...',
'status_connected_https': 'Connected via HTTP',
'status_connected_http': '✓ Connecté via HTTP',
'status_failed': '✗ Connexion échouée: {}',
'error_no_titleids': 'Veuillez entrer au moins un ID de Titre',
'verify_integrity': 'Vérifier l\'intégrité des fichiers',
'download_speed': 'Vitesse: {} MB/s',
'filter_status': 'Filtrer par État:',
'filter_date': 'Filtrer par Date:',
},
'de': {
'title': 'UnityScraper - Verbesserte Edition',
'titleids': 'Titel-IDs:',
'titleids_hint': 'Kommagetrennt (z.B. 555308C5,00000155)',
'output_dir': 'Ausgabeverzeichnis:',
'browse': 'Durchsuchen',
'settings': 'Einstellungen',
'workers': 'Worker:',
'rate_limit': 'Geschwindigkeitsbegrenzung (s):',
'timeout': 'Zeitüberschreitung (s):',
'max_retries': 'Maximale Versuche:',
'bandwidth': 'Bandbreite (KB/s):',
'use_https': 'XboxUnity HTTP endpoints (required)',
'verify_checksums': 'Checksummen überprüfen',
'dry_run': 'Testlauf (keine Downloads)',
'not_connected': 'Nicht verbunden',
'start_download': 'Download starten',
'stop': 'Stopp',
'test_connection': 'Verbindung testen',
'retry_failed': 'Fehler erneut versuchen',
'save_config': 'Konfiguration speichern',
'load_config': 'Konfiguration laden',
'export_db': 'DB exportieren',
'show_stats': 'Statistiken anzeigen',
'clear_log': 'Protokoll löschen',
'log_output': 'Protokollausgabe',
'verify_integrity': 'Dateiintegrität überprüfen',
'download_speed': 'Geschwindigkeit: {} MB/s',
'filter_status': 'Nach Status filtern:',
'filter_date': 'Nach Datum filtern:',
},
'ja': {
'title': 'UnityScraper - 拡張版',
'titleids': 'タイトルID:',
'titleids_hint': 'カンマ区切り (例: 555308C5,00000155)',
'output_dir': '出力ディレクトリ:',
'browse': '参照',
'settings': '設定',
'workers': 'ワーカー:',
'rate_limit': 'レート制限 (s):',
'timeout': 'タイムアウト (s):',
'max_retries': '最大再試行:',
'bandwidth': '帯域幅 (KB/s):',
'use_https': 'XboxUnity HTTP endpoints (required)',
'verify_checksums': 'チェックサムを確認',
'dry_run': 'ドライラン (ダウンロードなし)',
'not_connected': '未接続',
'start_download': 'ダウンロード開始',
'stop': '停止',
'test_connection': '接続テスト',
'retry_failed': '失敗を再試行',
'save_config': '設定を保存',
'load_config': '設定を読み込む',
'export_db': 'DB をエクスポート',
'show_stats': '統計を表示',
'clear_log': 'ログをクリア',
'log_output': 'ログ出力',
'verify_integrity': 'ファイルの整合性を確認',
'download_speed': '速度: {} MB/s',
'filter_status': 'ステータスでフィルタ:',
'filter_date': '日付でフィルタ:',
}
}
TRANSLATIONS['it'] = {
**TRANSLATIONS['en'],
'title': 'UnityScraper',
'titleids': 'TitleID:',
'output_dir': 'Cartella di output:',
'browse': 'Sfoglia',
'settings': 'Impostazioni',
'start_download': 'Avvia download',
'stop': 'Ferma',
'test_connection': 'Verifica connessione',
'verify_integrity': 'Verifica integrita file',
}
TRANSLATIONS['pt'] = {
**TRANSLATIONS['en'],
'title': 'UnityScraper',
'titleids': 'TitleIDs:',
'output_dir': 'Pasta de saida:',
'browse': 'Procurar',
'settings': 'Configuracoes',
'start_download': 'Iniciar download',
'stop': 'Parar',
'test_connection': 'Testar conexao',
'verify_integrity': 'Verificar integridade dos arquivos',
}
def _repair_legacy_text(value: str) -> str:
"""Repair translations that were historically saved with the wrong encoding."""
if not any(marker in value for marker in ("Ã", "Â", "â", "ã", "æ", "ç", "é")):
return value
for encoding in ("cp1252", "latin-1"):
try:
repaired = value.encode(encoding).decode("utf-8")
except (UnicodeEncodeError, UnicodeDecodeError):
continue
if repaired != value:
return repaired
return value
for _language, _strings in TRANSLATIONS.items():
TRANSLATIONS[_language] = {
key: _repair_legacy_text(value) for key, value in _strings.items()
}
class Translator:
"""Language translator for GUI"""
def __init__(self, language: str = 'en'):
if language not in SUPPORTED_LANGUAGES:
logger.warning(f"Language '{language}' not supported, using English")
language = 'en'
self.language = language
self.strings = {**TRANSLATIONS['en'], **TRANSLATIONS.get(language, {})}
def get(self, key: str, *args) -> str:
"""Get translated string with optional formatting"""
text = self.strings.get(key, key)
if args:
return text.format(*args)
return text
def set_language(self, language: str):
"""Change language"""
if language not in SUPPORTED_LANGUAGES:
logger.warning(f"Language '{language}' not supported")
return False
self.language = language
self.strings = {**TRANSLATIONS['en'], **TRANSLATIONS.get(language, {})}
return True
@staticmethod
def get_supported_languages() -> list:
"""Get list of supported languages"""
return SUPPORTED_LANGUAGES
# Global translator instance
_translator: Optional[Translator] = None
def load_language_packs(directory: str | Path) -> list[str]:
"""Load bounded user language packs without executing code."""
root = Path(directory)
loaded: list[str] = []
if not root.is_dir():
return loaded
for path in sorted(root.glob("*.json")):
if path.stat().st_size > 1024 * 1024:
logger.warning("Ignoring oversized language pack: %s", path)
continue
try:
payload = json.loads(path.read_text(encoding="utf-8"))
code = str(payload["language"])
strings = payload["strings"]
if not LANGUAGE_CODE_RE.fullmatch(code) or not isinstance(strings, dict):
raise ValueError("invalid language-pack schema")
validated = {
str(key): value for key, value in strings.items()
if isinstance(key, str) and isinstance(value, str) and len(value) <= 2000
}
except (OSError, json.JSONDecodeError, KeyError, ValueError) as exc:
logger.warning("Ignoring invalid language pack %s: %s", path, exc)
continue
TRANSLATIONS[code] = {**TRANSLATIONS["en"], **validated}
if code not in SUPPORTED_LANGUAGES:
SUPPORTED_LANGUAGES.append(code)
loaded.append(code)
return loaded
def init_translator(language: str = 'en', language_pack_dir: str | Path | None = None) -> Translator:
"""Initialize global translator"""
global _translator
if language_pack_dir is not None:
load_language_packs(language_pack_dir)
_translator = Translator(language)
return _translator
def get_translator() -> Translator:
"""Get global translator instance"""
global _translator
if _translator is None:
_translator = Translator('en')
return _translator
def t(key: str, *args) -> str:
"""Shorthand for get_translator().get()"""
return get_translator().get(key, *args)