okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-i18n: French as the ninth app language and the Polish README52ba0b781

main
6.5 KiB156 linesraw
1"""French (fr) catalog tooling for the desktop app (#3970).
2
3The French texts live in src/locales/fr.json, fix-fr.json, tune-fr.json and tools-fr.json, next to the other languages.
4They are edited by hand (they are the translations, not generated), so a string added to an English catalog later has no
5French yet. This script lists and merges those. From apps/host:
6
7    python scripts/fr_sync.py missing [out.tsv]        write every English string that has no French yet
8    python scripts/fr_sync.py apply done.tsv           merge translations, rewrite the four fr files in English key order
9    python scripts/fr_sync.py check                    exit 1 if a French string is missing, empty or breaks a placeholder / tag
10
11The TSV has one string per line:  <id><TAB><text>.  In the text, a newline is written \\n and a backslash \\\\.
12In the "done" file a lone  =  means "keep the English text as it is" (class names, product names, file names).
13The id prefix picks the file:  s0001 -> fr.json, fx01 -> fix-fr.json, tune01 -> tune-fr.json, tl01 -> tools-fr.json.
14Use "vous", plain short words, a next step, and a no-break space (U+00A0) before : ; ? ! and inside guillemets.
15"""
16import json
17import re
18import sys
19from pathlib import Path
20
21LOCALES = Path(__file__).resolve().parent.parent / "src" / "locales"
22PAIRS = [("en.json", "fr.json"), ("fix-en.json", "fix-fr.json"), ("tune-en.json", "tune-fr.json"), ("tools-en.json", "tools-fr.json")]
23SLOT = re.compile(r"\{\d+\}")
24TAG = re.compile(r"</?[A-Za-z][^>]*>")
25
26
27def load(name):
28    path = LOCALES / name
29    return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
30
31
32def file_of(identifier):
33    for en_name, fr_name in PAIRS:
34        if identifier in load(en_name):
35            return fr_name
36    raise SystemExit(f"unknown id {identifier}: it is in no English catalog")
37
38
39def escape(text):
40    return text.replace("\\", "\\\\").replace("\n", "\\n")
41
42
43def unescape(text):
44    out, i = [], 0
45    while i < len(text):
46        if text[i] == "\\" and i + 1 < len(text):
47            out.append({"n": "\n", "\\": "\\"}.get(text[i + 1], text[i + 1]))
48            i += 2
49        else:
50            out.append(text[i])
51            i += 1
52    return "".join(out)
53
54
55NBSP = " "
56
57
58def typography(text):
59    """French spacing and apostrophes, applied to every translated (not kept) string.
60    l'image -> l'image with a typographic apostrophe (also before a {0} slot); a no-break space before : ; ? ! % and inside the guillemets."""
61    text = re.sub(r"(?<=[A-Za-zÀ-ſ])'(?=[A-Za-zÀ-ſ{])", "’", text)
62    text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text)
63    text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text)
64    text = re.sub("« ?", "«" + NBSP, text)
65    text = re.sub(" ?»", NBSP + "»", text)
66    return text
67
68
69def problems(identifier, source, text):
70    found = []
71    if not text.strip():
72        found.append("empty")
73    expected = [slot for slot in SLOT.findall(source) if not (identifier == "s2463" and slot == "{1}")]  # the tests allow this one to drop {1} (the plural suffix)
74    if sorted(expected) != sorted(SLOT.findall(text)):
75        found.append("placeholders differ")
76    if sorted(TAG.findall(source)) != sorted(TAG.findall(text)):
77        found.append("markup differs")
78    return found
79
80
81def missing():
82    todo = {}
83    for en_name, fr_name in PAIRS:
84        en, fr = load(en_name), load(fr_name)
85        for identifier, text in en.items():
86            if identifier not in fr:
87                todo[identifier] = text
88    return todo
89
90
91def main(argv):
92    command = argv[1] if len(argv) > 1 else ""
93    if command == "missing":
94        todo = missing()
95        lines = [f"{identifier}\t{escape(text)}" for identifier, text in todo.items()]
96        if len(argv) > 2:
97            Path(argv[2]).write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
98            print(f"{len(lines)} strings without French written to {argv[2]}")
99        else:
100            print("\n".join(lines))
101            print(f"{len(lines)} strings without French", file=sys.stderr)
102        return 0
103    if command == "apply" and len(argv) > 2:
104        incoming = {}
105        for number, line in enumerate(Path(argv[2]).read_text(encoding="utf-8").splitlines(), 1):
106            if not line.strip():
107                continue
108            if "\t" not in line:
109                raise SystemExit(f"{argv[2]}:{number}: no tab")
110            identifier, text = line.split("\t", 1)
111            incoming[identifier.strip()] = text
112        bad = 0
113        for en_name, fr_name in PAIRS:
114            en, fr = load(en_name), load(fr_name)
115            changed = False
116            for identifier, source in en.items():
117                if identifier in incoming:
118                    text = source if incoming[identifier] == "=" else typography(unescape(incoming[identifier]))
119                    for why in problems(identifier, source, text):
120                        print(f"{identifier}: {why}: {source!r} -> {text!r}")
121                        bad += 1
122                    fr[identifier] = text
123                    changed = True
124            if changed:
125                ordered = {identifier: fr[identifier] for identifier in en if identifier in fr}
126                (LOCALES / fr_name).write_text(json.dumps(ordered, ensure_ascii=False, indent=1 if en_name != "en.json" else 2) + "\n", encoding="utf-8")
127        unknown = [identifier for identifier in incoming if not any(identifier in load(en_name) for en_name, _ in PAIRS)]
128        for identifier in unknown:
129            print(f"{identifier}: not in any English catalog")
130            bad += 1
131        print(f"applied {len(incoming)} strings, {bad} problems")
132        return 1 if bad else 0
133    if command == "check":
134        bad = 0
135        for en_name, fr_name in PAIRS:
136            en, fr = load(en_name), load(fr_name)
137            for identifier, source in en.items():
138                if identifier not in fr:
139                    print(f"{fr_name}: {identifier} has no French yet: {source!r}")
140                    bad += 1
141                    continue
142                for why in problems(identifier, source, fr[identifier]):
143                    print(f"{fr_name}: {identifier}: {why}")
144                    bad += 1
145            for identifier in fr:
146                if identifier not in en:
147                    print(f"{fr_name}: {identifier} is not in {en_name}")
148                    bad += 1
149        print("French catalogs complete" if not bad else f"{bad} problems")
150        return 1 if bad else 0
151    print(__doc__)
152    return 2
153
154
155if __name__ == "__main__":
156    raise SystemExit(main(sys.argv))