i18n_tool.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. # Translation workflow helper for resources/i18n/<lang>.txt (JUCE LocalisedStrings tables).
  2. # English is the source language; resources/i18n/pt-BR.txt is the reference table: every key it has must
  3. # exist in every other language file.
  4. #
  5. # Usage (from the repository root):
  6. # python3 tools/i18n_tool.py status coverage of every language
  7. # python3 tools/i18n_tool.py export <lang> <dir> [N] writes the keys <lang> still lacks to <dir>/src-NN.txt
  8. # (N keys per chunk, default 400), with the pt-BR text as
  9. # a hint; translate into <dir>/out-NN.txt
  10. # python3 tools/i18n_tool.py check <lang> <dir> validates <dir>/out-*.txt (placeholders, escapes...)
  11. # python3 tools/i18n_tool.py merge <lang> <dir> merges <dir>/out-*.txt into resources/i18n/<lang>.txt
  12. # python3 tools/i18n_tool.py lint <lang> validates resources/i18n/<lang>.txt itself
  13. # python3 tools/i18n_tool.py pending rewrites resources/i18n/pending.keys with the pt-BR keys
  14. # some other table still lacks (the tests accept those)
  15. #
  16. # Output chunk format: one line per string, exactly like the tables: "English text" = "Translation"
  17. # (escapes \n \t \" \\; keep {0} {1}... placeholders, % signs, and leading/trailing spaces and punctuation).
  18. import pathlib, re, sys
  19. root = pathlib.Path(__file__).resolve().parent.parent
  20. i18n = root / "resources/i18n"
  21. sys.path.insert(0, str(root / "tools"))
  22. from i18n_keys import unescape, escape, table # noqa: E402
  23. # id, file header "language:" name, JUCE "countries:" codes
  24. LANGUAGES = {
  25. "pt-BR": ("Português (Brasil)", "br"),
  26. "es": ("Español", "es mx ar co cl pe ve"),
  27. "fr": ("Français", "fr be ch ca lu"),
  28. "de": ("Deutsch", "de at ch li lu"),
  29. "it": ("Italiano", "it ch sm"),
  30. "ru": ("Русский", "ru by kz"),
  31. "pl": ("Polski", "pl"),
  32. "tr": ("Türkçe", "tr"),
  33. "ja": ("日本語", "jp"),
  34. "ko": ("한국어", "kr"),
  35. "zh-Hans": ("简体中文", "cn sg"),
  36. "zh-Hant": ("繁體中文", "tw hk mo"),
  37. "id": ("Bahasa Indonesia", "id"),
  38. "nl": ("Nederlands", "nl be"),
  39. }
  40. PAIR = re.compile(r'^"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)"\s*$')
  41. def reference():
  42. return table(i18n / "pt-BR.txt")
  43. def placeholders(s):
  44. return sorted(re.findall(r"\{\d\}", s))
  45. def problems(english, text):
  46. """Reasons a translation is not acceptable (empty list = fine)."""
  47. out = []
  48. if not text.strip():
  49. out.append("empty")
  50. if placeholders(english) != placeholders(text):
  51. out.append("placeholders differ")
  52. if english.count("\n") != text.count("\n"):
  53. out.append("line breaks differ")
  54. if english.count("\t") != text.count("\t"):
  55. out.append("tabs differ")
  56. if english.count("%") != text.count("%"):
  57. out.append("% signs differ")
  58. mice = lambda t: sorted(re.findall(r"\[(?:LMB|2xLMB|RMB|MMB|Wheel)\]", t))
  59. if mice(english) != mice(text):
  60. out.append("[LMB]/[RMB]/[Wheel] mouse tokens differ (keep them in English)")
  61. if english[:1] == " " and text[:1] != " ":
  62. out.append("leading space lost")
  63. if english[-1:] == " " and text[-1:] != " ":
  64. out.append("trailing space lost")
  65. if english.endswith("...") and not (text.endswith("...") or text.endswith("…")):
  66. out.append("trailing ... lost")
  67. return out
  68. def read_chunks(folder):
  69. entries, bad = {}, []
  70. for path in sorted(pathlib.Path(folder).glob("out-*.txt")):
  71. for n, line in enumerate(path.read_text(encoding="utf-8").split("\n"), 1):
  72. s = line.strip()
  73. if not s or s.startswith("#"):
  74. continue
  75. m = PAIR.match(s)
  76. if not m:
  77. bad.append(f"{path.name}:{n}: not a \"key\" = \"value\" line: {s[:80]}")
  78. continue
  79. entries[unescape(m.group(1))] = unescape(m.group(2))
  80. return entries, bad
  81. def cmd_status():
  82. ref = reference()
  83. for lang in LANGUAGES:
  84. path = i18n / f"{lang}.txt"
  85. t = table(path) if path.exists() else {}
  86. have = sum(1 for k in ref if t.get(k))
  87. print(f"{lang:8} {have:5}/{len(ref)}")
  88. def cmd_export(lang, folder, size=400):
  89. ref = reference()
  90. path = i18n / f"{lang}.txt"
  91. t = table(path) if path.exists() else {}
  92. todo = [k for k in ref if not t.get(k)]
  93. folder = pathlib.Path(folder)
  94. folder.mkdir(parents=True, exist_ok=True)
  95. for i in range(0, len(todo), size):
  96. lines = [f"# chunk {i // size + 1:02}: translate each \"English\" into {LANGUAGES[lang][0]} ({lang});",
  97. "# the '# pt-BR:' line is the Brazilian Portuguese translation, only as a hint for the meaning.", ""]
  98. for k in todo[i:i + size]:
  99. lines.append(f"# pt-BR: {escape(ref[k])}")
  100. lines.append(f'"{escape(k)}" = ""')
  101. (folder / f"src-{i // size + 1:02}.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
  102. print(f"{len(todo)} keys -> {(len(todo) + size - 1) // size} chunk(s) in {folder}")
  103. def cmd_check(lang, folder):
  104. ref = reference()
  105. entries, bad = read_chunks(folder)
  106. for b in bad:
  107. print(b)
  108. count = 0
  109. for k, v in entries.items():
  110. if k not in ref:
  111. print(f"unknown key (typo in the English?): \"{escape(k)[:90]}\"")
  112. count += 1
  113. continue
  114. for p in problems(k, v):
  115. print(f"{p}: \"{escape(k)[:90]}\"")
  116. count += 1
  117. path = i18n / f"{lang}.txt"
  118. t = table(path) if path.exists() else {}
  119. missing = [k for k in ref if not entries.get(k) and not t.get(k)]
  120. print(f"{lang}: {len(entries)} translated in chunks, {len(missing)} still missing, {count + len(bad)} problem(s)")
  121. return count + len(bad)
  122. def cmd_merge(lang, folder):
  123. ref = reference()
  124. path = i18n / f"{lang}.txt"
  125. current = table(path) if path.exists() else {}
  126. entries, _ = read_chunks(folder) if folder else ({}, [])
  127. merged = {k: v for k, v in current.items()}
  128. merged.update({k: v for k, v in entries.items() if k in ref and not problems(k, v)})
  129. name, countries = LANGUAGES[lang]
  130. out = [f"language: {name}", f"countries: {countries}", "",
  131. f"# LYNX interface in {name} (JUCE LocalisedStrings format).",
  132. "# One line per string: \"English text\" = \"Translation\" (escapes: \\n \\t \\\" \\\\)",
  133. "# Every key of pt-BR.txt must be here; terms: docs/i18n/" + lang + "-glossary.md; how to help: docs/i18n/README.md",
  134. "# After editing, run: python3 tools/make_i18n.py (embeds the tables in src/ui/I18nData.h)"]
  135. # same order and sections as pt-BR.txt
  136. for line in (i18n / "pt-BR.txt").read_text(encoding="utf-8").split("\n"):
  137. s = line.strip()
  138. if s.startswith("# ---"):
  139. out += ["", s]
  140. continue
  141. m = PAIR.match(s)
  142. if m:
  143. k = unescape(m.group(1))
  144. if merged.get(k):
  145. out.append(f'"{escape(k)}" = "{escape(merged[k])}"')
  146. # entries this language has beyond pt-BR (kept, at the end)
  147. extra = [k for k in merged if k not in ref and merged[k]]
  148. if extra:
  149. out += ["", "# --- Not in pt-BR.txt (yet)"] + [f'"{escape(k)}" = "{escape(merged[k])}"' for k in extra]
  150. path.write_text("\n".join(out) + "\n", encoding="utf-8")
  151. have = sum(1 for k in ref if merged.get(k))
  152. print(f"{path.name}: {have}/{len(ref)} keys")
  153. def cmd_lint(lang):
  154. ref = reference()
  155. t = table(i18n / f"{lang}.txt")
  156. n = 0
  157. for k, v in t.items():
  158. for p in problems(k, v):
  159. print(f"{p}: \"{escape(k)[:90]}\"")
  160. n += 1
  161. missing = [k for k in ref if not t.get(k)]
  162. print(f"{lang}: {len(t)} entries, {len(missing)} missing, {n} problem(s)")
  163. return n
  164. def cmd_pending():
  165. ref = reference()
  166. path = i18n / "pending.keys"
  167. head = [l for l in path.read_text(encoding="utf-8").split("\n") if l.startswith("#")] if path.exists() else []
  168. lacking = []
  169. for lang in LANGUAGES:
  170. p = i18n / f"{lang}.txt"
  171. if lang == "pt-BR" or not p.exists():
  172. continue
  173. t = table(p)
  174. lacking += [k for k in ref if not t.get(k) and k not in lacking]
  175. path.write_text("\n".join(head + [f'"{escape(k)}"' for k in lacking]) + "\n", encoding="utf-8")
  176. print(f"{len(lacking)} pending key(s) in {path.name}")
  177. if __name__ == "__main__":
  178. a = sys.argv[1:]
  179. if not a:
  180. print(__doc__ or open(__file__).read().split("import")[0])
  181. elif a[0] == "status":
  182. cmd_status()
  183. elif a[0] == "export":
  184. cmd_export(a[1], a[2], int(a[3]) if len(a) > 3 else 400)
  185. elif a[0] == "check":
  186. sys.exit(1 if cmd_check(a[1], a[2]) else 0)
  187. elif a[0] == "merge":
  188. cmd_merge(a[1], a[2] if len(a) > 2 else None)
  189. elif a[0] == "pending":
  190. cmd_pending()
  191. elif a[0] == "lint":
  192. sys.exit(1 if cmd_lint(a[1]) else 0)