anki/pylib/tools/genfluent.py
Damien Elmes 0a0d17ff98 Update Python deps
- Black's formatting has changed
- Pylint has introduced a new lint
2023-03-31 14:04:05 +10:00

107 lines
2.6 KiB
Python

# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
# pylint: disable=unbalanced-tuple-unpacking
import json
import sys
from typing import Literal, TypedDict
sys.path.append("pylib/anki/_vendor")
import stringcase
strings_json, outfile = sys.argv[1:]
with open(strings_json, encoding="utf8") as f:
modules = json.load(f)
class Variable(TypedDict):
name: str
kind: Literal["Any", "Int", "String", "Float"]
def legacy_enum() -> str:
out = ["class LegacyTranslationEnum:"]
for module in modules:
for translation in module["translations"]:
key = stringcase.constcase(translation["key"])
value = f'({module["index"]}, {translation["index"]})'
out.append(f" {key} = {value}")
return "\n".join(out) + "\n"
def methods() -> str:
out = [
"class GeneratedTranslations:",
" def _translate(self, module: int, translation: int, args: Dict) -> str:",
" raise Exception('not implemented')",
]
for module in modules:
for translation in module["translations"]:
key = translation["key"].replace("-", "_")
arg_types = get_arg_types(translation["variables"])
args = get_args(translation["variables"])
doc = translation["text"]
out.append(
f"""
def {key}(self, {arg_types}) -> str:
r''' {doc} '''
return self._translate({module["index"]}, {translation["index"]}, {{{args}}})
"""
)
return "\n".join(out) + "\n"
def get_arg_types(args: list[Variable]) -> str:
return ", ".join(
[f"{stringcase.snakecase(arg['name'])}: {arg_kind(arg)}" for arg in args]
)
def arg_kind(arg: Variable) -> str:
if arg["kind"] == "Int":
return "int"
elif arg["kind"] == "Any":
return "FluentVariable"
elif arg["kind"] == "Float":
return "float"
else:
return "str"
def get_args(args: list[Variable]) -> str:
return ", ".join(
[f'"{arg["name"]}": {stringcase.snakecase(arg["name"])}' for arg in args]
)
out = ""
out += legacy_enum()
out += methods()
with open(outfile, "w", encoding="utf8") as f:
f.write(
'''# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
# pylint: skip-file
from __future__ import annotations
"""
This file is automatically generated from the *.ftl files.
"""
import enum
from typing import Dict, Union
FluentVariable = Union[str, int, float]
'''
+ out
)