check-site-i18n.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. #!/usr/bin/env python3
  2. """Check the website translations (website/i18n/) against the English strings of the built site.
  3. scripts/check-site-i18n.py check every language; lists the missing keys per language; exit 1 on an error
  4. scripts/check-site-i18n.py --todo ID FILE write what language ID still lacks: {"ui": {key: English}, "updates": {...}, "catalog": {...}, "insp": {...}}
  5. scripts/check-site-i18n.py --merge ID FILE merge a translated --todo file into the language's files and drop keys the site no longer uses
  6. scripts/check-site-i18n.py --bodies ID DIR take translated wiki bodies from DIR: <page>.md (the article's body, no front matter),
  7. learn.<slug>.md (a tutorial page's written steps) and
  8. *.json ({plugin id: {"intro", "does": [one per control], "tips"}}); see "Wiki bodies" below
  9. The site speaks the same 15 languages as the app (src/ui/I18n.cpp: ids and native names must match). English lives in
  10. the pages; website/_src/build.py collects it into website/i18n/en.json {"ui", "featured", "insp"} and
  11. website/i18n/updates/en.json (the Updates page, keys "u.<version>...") and website/i18n/catalog/en.json (the plugin cards, keys "c.<plugin>").
  12. Every other language has the same three files.
  13. Errors: a stale build, a missing file or key (no key may fall back to English), an empty text, {0}-style placeholders
  14. or HTML tags that differ from English, a page without the language's hreflang link. Unused keys are warnings.
  15. Wiki bodies (the articles of website/_src/wiki and the plugin pages made from website/_src/catalog.json): a language has
  16. all of them or none. They live in website/_src/wiki/<id>/<page>.md and website/_src/catalog-wiki/<id>.json, each with
  17. the digest of the English text it was made from ("source"). Errors: a body that is missing or made from an older English
  18. text, one whose blocks, links, pictures or headings differ from the English page, a paragraph left in English.
  19. Program labels in `code` (menu paths, buttons, options) and the control names of the plugin tables are never translated
  20. by hand: --bodies writes them as the app shows them in that language (resources/i18n/<id>.txt), and English where the
  21. app has no translation. A label that no longer matches the app's translation is a warning.
  22. """
  23. import json
  24. import re
  25. import subprocess
  26. import sys
  27. from collections import Counter
  28. from pathlib import Path
  29. ROOT = Path(__file__).resolve().parent.parent
  30. SITE = ROOT / "website"
  31. DIR = SITE / "i18n"
  32. BUILD = SITE / "_src/build.py"
  33. APP = ROOT / "src/ui/I18n.cpp"
  34. SECTS = ("ui", "featured", "insp")
  35. PARTS = ("updates", "catalog") # strings kept in their own files: website/i18n/<part>/<id>.json
  36. def load(path):
  37. return json.loads(path.read_text(encoding="utf-8"))
  38. def english():
  39. en = load(DIR / "en.json")
  40. for part in PARTS:
  41. en[part] = load(DIR / part / "en.json")
  42. return en
  43. def translation(lid):
  44. tr = load(DIR / f"{lid}.json") if (DIR / f"{lid}.json").exists() else {}
  45. for part in PARTS:
  46. f = DIR / part / f"{lid}.json"
  47. tr[part] = load(f) if f.exists() else {}
  48. return tr
  49. def site_build():
  50. """website/_src/build.py as a module: its markdown and the digests of the English bodies."""
  51. import importlib.util
  52. spec = importlib.util.spec_from_file_location("lynx_site_build", BUILD)
  53. mod = importlib.util.module_from_spec(spec)
  54. spec.loader.exec_module(mod)
  55. return mod
  56. def app_dict(lid):
  57. """The app's translation: "English" = "Translation" lines of resources/i18n/<id>.txt."""
  58. out, f = {}, ROOT / "resources/i18n" / f"{lid}.txt"
  59. un = lambda x: re.sub(r"\\(.)", lambda m: {"n": "\n", "t": "\t"}.get(m.group(1), m.group(1)), x)
  60. for m in re.finditer(r'^"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)"', f.read_text(encoding="utf-8") if f.exists() else "", re.M):
  61. out[un(m.group(1))] = un(m.group(2))
  62. # English shows a few keys differently (its display table, resources/i18n/en/display.txt): a page quoting the English
  63. # label ("Simple layout") gets the translation of its key ("Simple workflow")
  64. en = ROOT / "resources/i18n/en/display.txt"
  65. for m in re.finditer(r'^"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)"', en.read_text(encoding="utf-8") if en.exists() and out else "", re.M):
  66. if un(m.group(1)) in out:
  67. out.setdefault(un(m.group(2)), out[un(m.group(1))])
  68. return out
  69. HEADS = 0 # app_dict key of the index label() builds: head of a label -> the labels that start with it
  70. KEYNAME = re.compile(r"(Ctrl|Shift|Alt|Cmd|Win|Enter|Return|Space|Tab|Esc|Del|Delete|Backspace|Home|End|Up|Down|Left|Right|PgUp|PgDn|Page Up|Page Down|"
  71. r"Ins|Insert|F\d{1,2}|Num \S+|[A-Za-z0-9]|[^\w\s])(\s*\+.*)?$")
  72. def label(text, app):
  73. """A program label as the app shows it in a language: whole, or each part of a `Menu › Item...` path. Keys, file names and
  74. anything the app does not translate stay as they are."""
  75. def one(x):
  76. if x in app:
  77. return app[x]
  78. # a page writes the app's {0} placeholder as a <name> ("Always run <plugin> in a separate process")
  79. ph = re.findall(r"<[^<>\s]+>", x)
  80. if len(ph) == 1 and x.replace(ph[0], "{0}") in app:
  81. return app[x.replace(ph[0], "{0}")].replace("{0}", ph[0])
  82. for suf in ("...", ":"):
  83. if x.endswith(suf) and x[:-len(suf)] in app:
  84. return app[x[:-len(suf)]] + suf
  85. if x + suf in app:
  86. return re.sub(r"\s*(\.\.\.|…|:|:)$", "", app[x + suf])
  87. # the page names the head of a longer label ("Capture MIDI" of "Capture MIDI: the notes just played..."): the same head
  88. for sep, seps in ((" (", (" (", "(", "(")), (": ", (": ", ":", ":")), (". ", (". ", "。"))):
  89. longer = sorted((k for k in heads.get(x, ()) if k.startswith(x + sep)), key=len)
  90. for k in longer:
  91. cut = [app[k].find(t) for t in seps if app[k].find(t) > 0]
  92. if cut:
  93. return app[k][:min(cut)].strip()
  94. return x
  95. heads = app.setdefault(HEADS, {}) if app else {}
  96. if app and not heads:
  97. for k in list(app):
  98. if isinstance(k, str):
  99. m = re.match(r"(.{3,}?)( \(|: |\. )", k)
  100. if m:
  101. heads.setdefault(m.group(1), []).append(k)
  102. for mm in re.finditer(r" \(|: |\. ", k):
  103. heads.setdefault(k[:mm.start()], []).append(k)
  104. if KEYNAME.fullmatch(text) or text.startswith((".", "-", "/", "~", "<")) or "\\" in text:
  105. return text
  106. return " › ".join(one(x) for x in text.split(" › ")) if " › " in text else one(text)
  107. BLOCK = re.compile(r"(</?(?:p|ul|ol|li|table|thead|tbody|tr|td|th|h2|h3|pre|blockquote|figure|div)\b[^>]*>)")
  108. def body_shape(page, app=None):
  109. """What a translated body keeps: the blocks in order (headings with their ids) and, inside each, the links, pictures
  110. and emphasis; and the labels in `code`, as the app shows them when app is given."""
  111. cells, blocks, codes = [], [], []
  112. for n, part in enumerate(BLOCK.split(page)):
  113. if n % 2:
  114. blocks.append(re.sub(r'\s(?:class|data-i18n|alt|width|height|loading)="[^"]*"', "", part))
  115. continue
  116. codes.append(Counter(label(html_text(c), app) if app is not None else html_text(c) for c in re.findall(r"<code>(.*?)</code>", part, re.S)))
  117. part = re.sub(r"<code>.*?</code>", "<code>", part, flags=re.S)
  118. cells.append(Counter((t, h) for t, h in re.findall(r'<(/?\w+)(?:[^>]*?(?:href|src)="([^"]*)")?[^>]*>', part)))
  119. return blocks, cells, codes
  120. def html_text(s):
  121. return s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"').replace("&amp;", "&")
  122. def code_labels(text, app):
  123. """Markdown with every `code` span written as the app shows it."""
  124. out = []
  125. for n, part in enumerate(re.split(r"(```.*?```)", text, flags=re.S)):
  126. out.append(part if n % 2 else re.sub(r"`([^`\n]+)`", lambda m: "`%s`" % label(m.group(1), app), part))
  127. return "".join(out)
  128. def plain(page):
  129. """The text blocks of a body, without tags and labels (to spot a paragraph left in English)."""
  130. out = []
  131. for part in BLOCK.split(page)[::2]:
  132. t = re.sub(r"<[^>]+>", "", re.sub(r"<code>.*?</code>", "", part, flags=re.S)).strip()
  133. out.append(t)
  134. return out
  135. def english_prose(text):
  136. """A block of English sentences (a list of product names is the same in every language)."""
  137. words = text.lower().split()
  138. return len(words) >= 6 and len({w.strip(".,:;()") for w in words} & {"the", "and", "of", "to", "is", "a", "in", "with", "for", "that", "it", "on", "are", "or"}) >= 3
  139. def body_sources(b):
  140. """The English bodies: {page: (digest, html)} for the articles, {plugin id: (digest, html, entry)} for the plugin pages."""
  141. index, pages = b.wiki_pages()
  142. cat = b.catalog()
  143. arts = {s: (b.digest(p["body"]), p["prose"]) for s, p in pages.items()}
  144. plugs = {p["id"]: (b.digest(b.plugin_source(p["wiki"])), b.plugin_prose(p, cat, p["wiki"])[0], p) for p in cat if p.get("wiki")}
  145. return arts, plugs, cat
  146. def learn_sources(b):
  147. """The English written steps of the tutorial pages: {slug: (digest, html)}."""
  148. _, pages = b.learn_data()
  149. return {s: (b.digest(p["body"]), p["prose"]) for s, p in pages.items()}
  150. def check_bodies(b, langs, errors, warnings):
  151. """Returns {language: words of English it has bodies for}."""
  152. arts, plugs, cat = body_sources(b)
  153. learn = learn_sources(b)
  154. done = {}
  155. for lid, _ in langs:
  156. if lid == "en":
  157. continue
  158. app = app_dict(lid)
  159. d = SITE / "_src/wiki" / lid
  160. f = SITE / "_src/catalog-wiki" / f"{lid}.json"
  161. mine = load(f) if f.exists() else {}
  162. have = {p.stem for p in d.glob("*.md")} if d.is_dir() else set()
  163. if not have and not mine:
  164. continue # a language without wiki bodies: the pages say so
  165. for extra in sorted(have - set(arts)) + sorted(set(mine) - set(plugs)):
  166. warnings.append(f"{lid}: wiki body '{extra}' has no English page")
  167. lack = sorted(set(arts) - have) + sorted(set(plugs) - set(mine))
  168. if lack:
  169. errors.append(f"{lid}: {len(lack)} wiki bodies missing: " + ", ".join(lack[:12]) + (" ..." if len(lack) > 12 else ""))
  170. pairs = []
  171. for s in sorted(have & set(arts)):
  172. meta, body = b.front(d / f"{s}.md")
  173. if meta.get("source") != arts[s][0]:
  174. errors.append(f"{lid}: wiki body '{s}' was made from an older English text")
  175. continue
  176. ids = re.findall(r'<h[23] id="([^"]+)"', arts[s][1])
  177. pairs.append((s, arts[s][1], b.markdown(body, iter(ids))))
  178. for pid in sorted(set(mine) & set(plugs)):
  179. w = mine[pid]
  180. if w.get("source") != plugs[pid][0]:
  181. errors.append(f"{lid}: plugin page '{pid}' was made from an older English text")
  182. continue
  183. en = plugs[pid][2]["wiki"]
  184. if [label(a, app) for a, _ in en.get("controls", [])] != [a for a, _ in w.get("controls", [])]:
  185. warnings.append(f"{lid}: plugin page '{pid}': control names differ from the app's")
  186. pairs.append((pid, plugs[pid][1], b.plugin_prose(plugs[pid][2], cat, w)[0]))
  187. # the written steps of the tutorial pages (_src/learn/<id>/<slug>.md, round 190nt): the same rules
  188. ld = SITE / "_src/learn" / lid
  189. lhave = {p.stem for p in ld.glob("*.md")} if ld.is_dir() else set()
  190. for extra in sorted(lhave - set(learn)):
  191. warnings.append(f"{lid}: tutorial body '{extra}' has no English page")
  192. if sorted(set(learn) - lhave):
  193. errors.append(f"{lid}: {len(set(learn) - lhave)} tutorial bodies missing: " + ", ".join(sorted(set(learn) - lhave)))
  194. for s in sorted(lhave & set(learn)):
  195. meta, body = b.front(ld / f"{s}.md")
  196. if meta.get("source") != learn[s][0]:
  197. errors.append(f"{lid}: tutorial body '{s}' was made from an older English text")
  198. continue
  199. ids = re.findall(r'<h[23] id="([^"]+)"', learn[s][1])
  200. pairs.append(("learn/" + s, learn[s][1], b.markdown(body, iter(ids))))
  201. words = 0
  202. for name, en, tr in pairs:
  203. eb, ec, ecode = body_shape(en, app)
  204. tb, tc, tcode = body_shape(tr)
  205. if eb != tb:
  206. errors.append(f"{lid}: wiki body '{name}': blocks or headings differ from English")
  207. elif ec != tc:
  208. n = next(i for i, (x, y) in enumerate(zip(ec, tc)) if x != y)
  209. errors.append(f"{lid}: wiki body '{name}': links, pictures or emphasis differ from English near \"{plain(en)[n][:50]}\"")
  210. elif ecode != tcode:
  211. n = next(i for i, (x, y) in enumerate(zip(ecode, tcode)) if x != y)
  212. warnings.append(f"{lid}: wiki body '{name}': labels differ from the app's: {sorted((tcode[n] - ecode[n]).keys())[:3]}")
  213. same = [x for x, y in zip(plain(en), plain(tr)) if x == y and english_prose(x)]
  214. if same and eb == tb:
  215. errors.append(f"{lid}: wiki body '{name}': left in English: \"{same[0][:60]}\"")
  216. words += len(re.sub(r"<[^>]+>", " ", en).split())
  217. done[lid] = words
  218. return done
  219. def bodies(lid, src):
  220. """Take translated bodies from a folder: labels as the app shows them, the digest of the English source, into website/_src."""
  221. b = site_build()
  222. arts, plugs, _ = body_sources(b)
  223. app = app_dict(lid)
  224. n = 0
  225. learn = learn_sources(b)
  226. for f in sorted(Path(src).glob("learn.*.md")):
  227. slug = f.stem[len("learn."):]
  228. if slug not in learn:
  229. print(f"check-site-i18n: {f.name}: no such tutorial, skipped")
  230. continue
  231. text = re.sub(r"\A---\n.*?\n---\n", "", f.read_text(encoding="utf-8"), flags=re.S).strip("\n")
  232. out = SITE / "_src/learn" / lid / f"{slug}.md"
  233. out.parent.mkdir(parents=True, exist_ok=True)
  234. out.write_text("---\nsource: %s\n---\n%s\n" % (learn[slug][0], code_labels(text, app)), encoding="utf-8")
  235. n += 1
  236. for f in sorted(Path(src).glob("*.md")):
  237. if f.stem.startswith("learn."):
  238. continue
  239. if f.stem not in arts:
  240. print(f"check-site-i18n: {f.name}: no such wiki page, skipped")
  241. continue
  242. text = f.read_text(encoding="utf-8")
  243. text = re.sub(r"\A---\n.*?\n---\n", "", text, flags=re.S).strip("\n")
  244. out = SITE / "_src/wiki" / lid / f.name
  245. out.parent.mkdir(parents=True, exist_ok=True)
  246. out.write_text("---\nsource: %s\n---\n%s\n" % (arts[f.stem][0], code_labels(text, app)), encoding="utf-8")
  247. n += 1
  248. f = SITE / "_src/catalog-wiki" / f"{lid}.json"
  249. mine = load(f) if f.exists() else {}
  250. for g in sorted(Path(src).glob("*.json")):
  251. for pid, t in load(g).items():
  252. if pid not in plugs:
  253. print(f"check-site-i18n: {g.name}: no plugin page '{pid}', skipped")
  254. continue
  255. en = plugs[pid][2]["wiki"]
  256. does = t.get("does", [])
  257. if len(does) != len(en.get("controls", [])) or len(t.get("tips", [])) != len(en.get("tips", [])):
  258. print(f"check-site-i18n: {g.name}: '{pid}' has another number of controls or tips than English, skipped")
  259. continue
  260. mine[pid] = {"source": plugs[pid][0], "intro": code_labels(t["intro"], app),
  261. "controls": [[label(a, app), code_labels(d, app)] for (a, _), d in zip(en.get("controls", []), does)],
  262. "tips": [code_labels(x, app) for x in t.get("tips", [])]}
  263. n += 1
  264. if mine:
  265. f.parent.mkdir(parents=True, exist_ok=True)
  266. f.write_text(json.dumps({k: mine[k] for k in plugs if k in mine}, ensure_ascii=False, indent=0) + "\n", encoding="utf-8")
  267. print(f"check-site-i18n: {lid}: {n} wiki bodies taken from {src}; now run website/_src/build.py")
  268. return 0
  269. def page_langs():
  270. m = re.search(r"LANGS = (\[\[.*?\]\])\n", BUILD.read_text(encoding="utf-8"), re.S)
  271. return [tuple(x) for x in json.loads(m.group(1))]
  272. def app_langs():
  273. src = APP.read_text(encoding="utf-8")
  274. block = re.search(r"static const std::vector<Language> list \{(.*?)\};", src, re.S).group(1)
  275. out = []
  276. for lid, name in re.findall(r'\{ "([^"]+)", ((?:"[^"]*"\s*)+)\}', block):
  277. raw = "".join(re.findall(r'"([^"]*)"', name))
  278. out.append((lid, raw.encode("latin-1", "backslashreplace").decode("unicode_escape").encode("latin-1").decode("utf-8")))
  279. return out
  280. def shape(s):
  281. """What a translation must keep: placeholders, tags (with their href), entities such as &lt;user&gt;."""
  282. tags = re.findall(r"<(/?\w+)(?:[^>]*?href=\"([^\"]*)\")?[^>]*>", s)
  283. return Counter(re.findall(r"\{\d+\}", s)), Counter(tags), Counter(re.findall(r"&lt;|&gt;", s)), s.count("|")
  284. def missing(en, tr):
  285. return {sect: {k: v for k, v in en[sect].items() if not str(tr.get(sect, {}).get(k, "")).strip()}
  286. for sect in SECTS + PARTS}
  287. def dump(path, data):
  288. path.parent.mkdir(parents=True, exist_ok=True)
  289. path.write_text(json.dumps(data, ensure_ascii=False, indent=0) + "\n", encoding="utf-8")
  290. def todo(lid, out):
  291. todo = {k: v for k, v in missing(english(), translation(lid)).items() if v}
  292. dump(Path(out), todo)
  293. print(f"check-site-i18n: {lid}: {sum(len(v) for v in todo.values())} strings to translate -> {out}")
  294. return 0
  295. def merge(lid, src):
  296. en, tr, new = english(), translation(lid), load(Path(src))
  297. for sect in SECTS + PARTS:
  298. have = tr.setdefault(sect, {})
  299. have.update({k: v for k, v in new.get(sect, {}).items() if k in en[sect]})
  300. tr[sect] = {k: have[k] for k in en[sect] if k in have} # English order, unused keys dropped
  301. for part in PARTS:
  302. dump(DIR / part / f"{lid}.json", tr.pop(part))
  303. dump(DIR / f"{lid}.json", {s: tr[s] for s in SECTS})
  304. print(f"check-site-i18n: {lid}: merged {src}; now run website/_src/build.py")
  305. return 0
  306. def main():
  307. if len(sys.argv) == 4 and sys.argv[1] == "--todo":
  308. return todo(sys.argv[2], sys.argv[3])
  309. if len(sys.argv) == 4 and sys.argv[1] == "--merge":
  310. return merge(sys.argv[2], sys.argv[3])
  311. if len(sys.argv) == 4 and sys.argv[1] == "--bodies":
  312. return bodies(sys.argv[2], sys.argv[3])
  313. errors, warnings = [], []
  314. if subprocess.run([sys.executable, str(BUILD), "--check"]).returncode:
  315. errors.append("the built pages are out of date: run website/_src/build.py")
  316. en = english()
  317. langs = page_langs()
  318. if APP.exists() and langs != app_langs():
  319. errors.append(f"site languages {langs} differ from the app's {app_langs()}")
  320. pages = sorted(SITE.glob("**/index.html"))
  321. for lid, _ in langs:
  322. if lid == "en":
  323. continue
  324. for p in pages:
  325. if f'hreflang="{lid}"' not in p.read_text(encoding="utf-8"):
  326. errors.append(f"{lid}: no hreflang link in {p.relative_to(SITE)}")
  327. known = {lid for lid, _ in langs}
  328. for f in list(DIR.glob("*.json")) + [f for part in PARTS for f in DIR.glob(part + "/*.json")]:
  329. if f.stem not in known:
  330. errors.append(f"{f.relative_to(DIR)}: not a site language")
  331. for lid, _ in langs:
  332. if lid == "en":
  333. continue
  334. tr = translation(lid)
  335. for sect, keys in missing(en, tr).items():
  336. if keys:
  337. errors.append(f"{lid}: {len(keys)} missing in {sect}: " + ", ".join(list(keys)[:12]) + (" ..." if len(keys) > 12 else ""))
  338. for sect in SECTS + PARTS:
  339. have = tr.get(sect, {})
  340. for k, v in have.items():
  341. if k not in en[sect]:
  342. warnings.append(f"{lid}: unused {sect} '{k}'")
  343. elif isinstance(v, str) and v.strip() and shape(v) != shape(en[sect][k]):
  344. errors.append(f"{lid}: {sect} '{k}' placeholders/tags differ from English")
  345. done = check_bodies(site_build(), langs, errors, warnings)
  346. for w in warnings:
  347. print("warning:", w)
  348. for e in errors:
  349. print("error:", e)
  350. words = sum(len(re.sub(r"^---.*?---", "", f.read_text(encoding="utf-8"), flags=re.S).split()) for f in (SITE / "_src/wiki").glob("*.md"))
  351. pwords = 0 # the generated plugin pages: intro, controls, tips
  352. for p in load(SITE / "_src/catalog.json"):
  353. w = p.get("wiki") or {}
  354. pwords += len(" ".join([w.get("intro", "")] + [x for r in w.get("controls", []) for x in r] + w.get("tips", [])).split())
  355. none = [lid for lid, _ in langs if lid != "en" and lid not in done]
  356. print(f"check-site-i18n: {len(langs)} languages, {len(en['ui'])} strings + {len(en['updates'])} update strings + "
  357. f"{len(en['catalog'])} catalogue strings, {len(errors)} errors, {len(warnings)} warnings; "
  358. f"wiki bodies ({words} words in articles + {pwords} in plugin pages): translated in {len(done)} languages"
  359. + (", English only in " + " ".join(none) if none else ""))
  360. return 1 if errors else 0
  361. if __name__ == "__main__":
  362. sys.exit(main())