Spaces:
Sleeping
Sleeping
| 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() | |