import json import os from pathlib import Path import click from flask import Flask, session, current_app LanguageMapping = dict[str, str] def load_language(lang_code: str) -> LanguageMapping: with open(Path("kanken_online/static/lang", f"{lang_code}.json")) as f: return json.load(f) LANGUAGES = {} def update_languages(): ENGLISH = load_language("en") JAPANESE = load_language("ja") global LANGUAGES LANGUAGES = { "en": ENGLISH, "ja": JAPANESE } update_languages() # assert all(all(key in lang for key in EXISTING_STRINGS) for lang in LANGUAGES) # Ensure all strings are mapped for all existing languages # assert not [key for lang in LANGUAGES for key in lang if ((key in lang) and (key not in EXISTING_STRINGS))] # assert not any((((key in lang) and (key not in EXISTING_STRINGS)) for key in lang) for lang in LANGUAGES) # Ensure no languages have strings not specified by the main index def localize(text_id: str, language: dict[str, str] = None) -> str: if language is None: preference = session.get("language", "ja") language = LANGUAGES.get(preference) return language[text_id] @click.command("add-string") @click.argument("string") def add_string(string): """Add a new string to the translations.""" for path in Path("kanken_online/static/lang").glob("*.json"): with open(path) as f: data = json.load(f) data[string] = "" with open(path, mode="w") as f: json.dump(data, f, ensure_ascii=False, indent=0) @click.command("set-string") @click.argument("lang") @click.argument("string") @click.argument("value") def set_string(lang, string, value): """Set the value of a string for a particular language's translation file.""" path = Path("kanken_online/static/lang", f"{lang}.json") with open(path) as f: data = json.load(f) data[string] = value with open(path, mode="w") as f: json.dump(data, f, ensure_ascii=False, indent=0) @click.command("rename-string") @click.argument("string") @click.argument("new_name") def rename_string(string, new_name): """Rename a string in the translations files.""" for path in Path("kanken_online/static/lang").glob("*.json"): with open(path) as f: data = json.load(f) data[new_name] = data[string] del data[string] with open(path, mode="w") as f: json.dump(data, f, ensure_ascii=False, indent=0) def add_translation_commands(app: Flask): app.cli.add_command(add_string) app.cli.add_command(set_string) app.cli.add_command(rename_string)