Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-translate/blob/main/scripts/translate_readme.py # aien-translate aien-dev/aien-translate Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-translate / scripts / translate_readme.py` 154 lines · 5352 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Translate README.md into other languages with a running aien-translate. 3 4 Usage: python3 scripts/translate_readme.py [--server URL] [lang ...] 5 6 Code blocks are copied unchanged. Each other line is translated, and a line 7 whose markdown (links, bold, code spans) does not survive is kept in English. 8 Output goes to docs/i18n/README..md. 9 """ 10 import json 11 import re 12 import sys 13 import urllib.parse 14 import urllib.request 15 from pathlib import Path 16 17 ROOT = Path(__file__).resolve().parent.parent 18 OUT = ROOT / "docs" / "i18n" 19 20 # file code, translate.js id, name shown in the language bar 21 LANGS = [ 22 ("zh-CN", "chinese_simplified", "简体中文"), 23 ("zh-TW", "chinese_traditional", "繁體中文"), 24 ("ja", "japanese", "日本語"), 25 ("ko", "korean", "한국어"), 26 ("es", "spanish", "Español"), 27 ("fr", "french", "Français"), 28 ("de", "deutsch", "Deutsch"), 29 ("pt", "portuguese", "Português"), 30 ("ru", "russian", "Русский"), 31 ] 32 33 NOTE = ("This page was translated automatically by aien-translate, running on AIEN's own model. " 34 "The [English version](../../README.md) is the original.") 35 36 PREFIX = re.compile(r"^(\s*(?:#{1,6} |[-*] |\d+\. |> )?)(.*)$") 37 LINK_TARGET = re.compile(r"\]\(([^)]+)\)") 38 39 40 def markers(s): 41 """Markdown that must survive translation unchanged.""" 42 return (sorted(LINK_TARGET.findall(s)), s.count("**"), s.count("`"), s.count("[")) 43 44 45 def lang_bar(current): 46 parts = [] 47 english = "**English**" if current is None else "[English](../../README.md)" 48 parts.append(english) 49 for code, _, name in LANGS: 50 if code == current: 51 parts.append(f"**{name}**") 52 elif current is None: 53 parts.append(f"[{name}](docs/i18n/README.{code}.md)") 54 else: 55 parts.append(f"[{name}](README.{code}.md)") 56 return " · ".join(parts) 57 58 59 def fix_links(line): 60 """Relative links in the README point from the repo root; the copies live two folders down.""" 61 def repl(m): 62 target = m.group(1) 63 if re.match(r"^(https?:|mailto:|#|\.\./|README\.)", target): 64 return m.group(0) 65 return f"]({'../../' + target})" 66 return LINK_TARGET.sub(repl, line) 67 68 69 def translate(server, to, texts): 70 body = urllib.parse.urlencode({"from": "english", "to": to, "text": json.dumps(texts)}).encode() 71 req = urllib.request.Request(server.rstrip("/") + "/translate.json", body, 72 {"content-type": "application/x-www-form-urlencoded"}) 73 with urllib.request.urlopen(req, timeout=1800) as r: 74 d = json.load(r) 75 if d.get("result") != 1: 76 raise SystemExit(f"{to}: server refused: {d.get('info')}") 77 return d["text"], d.get("aien", {}) 78 79 80 def main(): 81 args = sys.argv[1:] 82 server = "http://127.0.0.1:18097" 83 if args[:1] == ["--server"]: 84 server, args = args[1], args[2:] 85 wanted = [l for l in LANGS if not args or l[0] in args] 86 87 lines = (ROOT / "README.md").read_text(encoding="utf-8").split("\n") 88 OUT.mkdir(parents=True, exist_ok=True) 89 90 # Work out which lines get translated. 91 jobs = [] # (line index, prefix, text) 92 in_code = in_bar = False 93 for i, line in enumerate(lines): 94 if line.startswith("```"): 95 in_code = not in_code 96 continue 97 if line.strip() == "": 98 in_bar = True 99 continue 100 if line.strip() == "": 101 in_bar = False 102 continue 103 if in_code or in_bar or not line.strip(): 104 continue 105 m = PREFIX.match(line) 106 assert m 107 prefix, text = m.groups() 108 if text.strip(): 109 jobs.append((i, prefix, text)) 110 111 for code, lang_id, name in wanted: 112 texts = [t for _, _, t in jobs] + [NOTE] 113 out, stats = translate(server, lang_id, texts) 114 note = out[-1] 115 if markers(note) != markers(NOTE): 116 note = NOTE 117 result = list(lines) 118 english = [] 119 for (i, prefix, src), tr in zip(jobs, out): 120 if markers(tr) != markers(src): 121 tr = src 122 if tr == src and re.search(r"[A-Za-z]{3}", src): 123 english.append(src[:60]) 124 result[i] = prefix + tr 125 126 # Language bar for this copy, then the note under the title. 127 final = [] 128 in_code = in_bar = False 129 for line in result: 130 if line.startswith("```"): 131 in_code = not in_code 132 if not in_code and line.strip() == "": 133 in_bar = True 134 final.append(line) 135 final.append(lang_bar(code)) 136 continue 137 if not in_code and line.strip() == "": 138 in_bar = False 139 final.append(line) 140 final.append("") 141 final.append(f"> {note}") 142 continue 143 if in_bar: 144 continue 145 final.append(line if in_code else fix_links(line)) 146 147 path = OUT / f"README.{code}.md" 148 path.write_text("\n".join(final), encoding="utf-8") 149 print(f"{code}: wrote {path.relative_to(ROOT)}; server {stats}; " 150 f"{len(english)} line(s) kept in English" + (f": {english}" if english else "")) 151 152 153 if __name__ == "__main__": 154 main()