File size: 2,162 Bytes
f9adcbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from pathlib import Path
from typing import Dict, Any
from app.config import settings
from app.storage.logger import get_logger

logger = get_logger(__name__)

_translations: Dict[str, str] = {}


def load_translations():
    """
    Loads the translation file corresponding to the language specified in the settings.
    """
    global _translations
    lang = settings.language
    locales_dir = Path(__file__).parent.parent / "locales"
    file_path = locales_dir / f"{lang}.json"

    if not file_path.exists():
        logger.warning(
            f"Translation file not found for language '{lang}'. Falling back to 'en'."
        )
        file_path = locales_dir / "en.json"
        if not file_path.exists():
            logger.error(
                "Default translation file 'en.json' not found. Localization will not work."
            )
            _translations = {}
            return

    try:
        with open(file_path, "r", encoding="utf-8") as f:
            _translations = json.load(f)
        logger.info(f"Successfully loaded translations for language: '{lang}'")
    except (json.JSONDecodeError, IOError) as e:
        logger.error(f"Failed to load or parse translation file {file_path}: {e}")
        _translations = {}


def get_string(key: str, **kwargs: Any) -> str:
    """
    Retrieves a translated string by its key and formats it with the given arguments.

    Args:
        key: The key of the string to retrieve (e.g., "cli_ready").
        **kwargs: Keyword arguments to format the string with.

    Returns:
        The translated and formatted string, or the key itself if not found.
    """
    if not _translations:
        # This might happen if loading failed. We return the key as a fallback.
        return key

    template = _translations.get(key, key)
    try:
        return template.format(**kwargs)
    except KeyError as e:
        logger.warning(
            f"Placeholder {{{e.args[0]}}} missing for localization key '{key}'"
        )
        return template


# Load translations when the module is imported.
# In a FastAPI context, this will happen at application startup.
load_translations()