-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslator.py
More file actions
49 lines (42 loc) · 1.42 KB
/
translator.py
File metadata and controls
49 lines (42 loc) · 1.42 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
"""
Translator module for managing translations across the application.
"""
import json
import logging
from pathlib import Path
class Translator:
"""Class for managing translations"""
def __init__(self, lang_dir=None):
self.lang_dir = lang_dir or Path(__file__).parent / 'resources' / 'translations'
self.current_lang = 'ru'
self.translations = {}
self.load_language(self.current_lang)
def load_language(self, lang_code):
"""Load language file"""
lang_file = self.lang_dir / f'{lang_code}.json'
if not lang_file.exists():
logging.warning(f"Language file not found: {lang_file}")
return False
try:
with open(lang_file, 'r', encoding='utf-8') as f:
self.translations = json.load(f)
self.current_lang = lang_code
return True
except Exception as e:
logging.error(f"Error loading language file: {e}")
return False
def get(self, key, **kwargs):
keys = key.split('.')
value = self.translations
try:
for k in keys:
value = value[k]
if kwargs:
return value.format(**kwargs)
return value
except (KeyError, TypeError):
return key
def __call__(self, key, **kwargs):
return self.get(key, **kwargs)
# Global translator instance
tr = Translator()