interplane.Get Omega
Read in your language

aien-translate

aien-dev/aien-translate

Brought by drakestapleton

branch main Branches Tags History

aien-translate / scripts / translate_site.py

345 lines · 14899 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Translate a built static website with a running aien-translate.
3
4Usage:
5 translate_site.py DIST OUT --langs zh-CN[,ja,...] [--server URL] [--base-url URL]
6
7For every HTML page in DIST, writes OUT/<code>/<same path> in each language.
8
9How text is cut up: each paragraph-like element (a block holding only text and
10inline tags such as links, bold or code) is translated as one piece, with its
11inline tags turned into numbered markers (<g1>...</g1>, <x1/> for code) so the
12model can move them with the words they belong to. If the markers do not come
13back intact, that piece stays in English. Elements marked translate="no",
14scripts, styles, <pre> and <code> are never translated.
15
16Internal links are pointed at the same language (/zh-CN/...), <html lang> is
17set, and hreflang alternates are added. Needs: beautifulsoup4.
18"""
19import argparse, copy, json, re, sys, time, urllib.parse, urllib.request
20from pathlib import Path
21from bs4 import BeautifulSoup, NavigableString, Comment, Tag
22
23LANGS = { # code -> (translate.js id, name, html lang)
24 "zh-CN": ("chinese_simplified", "简体中文", "zh-CN"),
25 "zh-TW": ("chinese_traditional", "繁體中文", "zh-TW"),
26 "ja": ("japanese", "日本語", "ja"),
27 "ko": ("korean", "한국어", "ko"),
28 "es": ("spanish", "Español", "es"),
29 "fr": ("french", "Français", "fr"),
30 "de": ("deutsch", "Deutsch", "de"),
31 "pt": ("portuguese", "Português", "pt"),
32 "ru": ("russian", "Русский", "ru"),
33}
34SKIP = {"script", "style", "pre", "code", "svg", "noscript", "textarea", "math", "template", "kbd", "samp"}
35ATOMIC = {"code", "kbd", "samp", "var", "br", "img", "svg", "math", "wbr", "input"}
36INLINE = {"a", "strong", "em", "b", "i", "span", "small", "sup", "sub", "abbr", "mark", "u", "s",
37 "q", "cite", "time", "dfn", "bdi", "bdo", "data", "label"} | ATOMIC
38ATTRS = ("title", "alt", "placeholder", "aria-label")
39META = {"description", "og:title", "og:description", "twitter:title", "twitter:description"}
40ASSET = re.compile(r"\.(css|js|mjs|json|txt|xml|svg|png|jpe?g|gif|webp|ico|sh|pdf|woff2?|map)$", re.I)
41LETTERS = re.compile(r"[A-Za-z]{2}")
42
43
44def no_translate(el):
45 while isinstance(el, Tag):
46 if el.get("translate") == "no":
47 return True
48 el = el.parent
49 return False
50
51
52def inline_only(el):
53 for c in el.children:
54 if isinstance(c, Comment):
55 continue
56 if isinstance(c, NavigableString):
57 continue
58 if not isinstance(c, Tag) or c.name not in INLINE:
59 return False
60 if c.name not in ATOMIC and not inline_only(c):
61 return False
62 if c.get("translate") == "no" and c.name not in ATOMIC:
63 return False
64 return True
65
66
67def text_of(el):
68 return "".join(s for s in el.find_all(string=True) if not isinstance(s, Comment)
69 and not any(p.name in SKIP for p in s.parents if isinstance(p, Tag)))
70
71
72class Unit:
73 """One piece of text to translate, with what is needed to put it back."""
74
75 def __init__(self, kind, el, source, tags=None, attr=None):
76 self.kind, self.el, self.source, self.tags, self.attr = kind, el, source, tags or [], attr
77
78
79def encode(el, tags):
80 out = []
81 for c in el.children:
82 if isinstance(c, Comment):
83 continue
84 if isinstance(c, NavigableString):
85 out.append(re.sub(r"\s+", " ", str(c)).replace("<", "&lt;"))
86 elif c.name in ATOMIC:
87 tags.append(c)
88 out.append(f"<x{len(tags)}/>")
89 else:
90 tags.append(c)
91 n = len(tags)
92 out.append(f"<g{n}>{encode(c, tags)}</g{n}>")
93 return "".join(out)
94
95
96TOKEN = re.compile(r"<g(\d+)>|</g(\d+)>|<x(\d+)/>|[^<]+|<")
97
98
99def decode(soup, translated, tags):
100 """Rebuild child nodes from a translated string. None if markers are broken."""
101 root = []
102 stack = [(None, root)]
103 used = set()
104 for m in TOKEN.finditer(translated):
105 g_open, g_close, x = m.group(1), m.group(2), m.group(3)
106 if g_open:
107 n = int(g_open)
108 if n in used or n > len(tags) or tags[n - 1].name in ATOMIC:
109 return None
110 used.add(n)
111 t = tags[n - 1]
112 shell = soup.new_tag(t.name, attrs=dict(t.attrs))
113 stack[-1][1].append(shell)
114 stack.append((n, shell))
115 elif g_close:
116 n = int(g_close)
117 if len(stack) < 2 or stack[-1][0] != n:
118 return None
119 stack.pop()
120 elif x:
121 n = int(x)
122 if n in used or n > len(tags) or tags[n - 1].name not in ATOMIC:
123 return None
124 used.add(n)
125 stack[-1][1].append(copy.copy(tags[n - 1]))
126 else:
127 stack[-1][1].append(NavigableString(m.group(0).replace("&lt;", "<")))
128 if len(stack) != 1 or used != set(range(1, len(tags) + 1)):
129 return None
130 return root
131
132
133def collect(soup):
134 units = []
135
136 def visit(el):
137 if not isinstance(el, Tag) or el.name in SKIP or el.get("translate") == "no":
138 return
139 if el.name not in ("html", "head", "body") and inline_only(el) and LETTERS.search(text_of(el)):
140 tags = []
141 src = encode(el, tags).strip()
142 units.append(Unit("block", el, src, tags))
143 return
144 for c in list(el.children):
145 if isinstance(c, Comment):
146 continue
147 if isinstance(c, NavigableString):
148 if LETTERS.search(str(c)) and el.name not in ("html", "head"):
149 units.append(Unit("text", c, re.sub(r"\s+", " ", str(c)).strip()))
150 else:
151 visit(c)
152
153 visit(soup.html or soup)
154 for el in soup.find_all(True):
155 if no_translate(el) or el.name in SKIP:
156 continue
157 for a in ATTRS:
158 v = el.get(a)
159 if isinstance(v, str) and LETTERS.search(v):
160 units.append(Unit("attr", el, v.strip(), attr=a))
161 if el.name == "meta" and (el.get("name") in META or el.get("property") in META):
162 v = el.get("content")
163 if v and LETTERS.search(v):
164 units.append(Unit("attr", el, v.strip(), attr="content"))
165 return units
166
167
168CHUNK_ITEMS, CHUNK_CHARS = 200, 20000
169
170
171def _ask(server, lang_id, batch):
172 body = urllib.parse.urlencode({"from": "english", "to": lang_id, "text": json.dumps(batch)}).encode()
173 req = urllib.request.Request(server.rstrip("/") + "/translate.json", body,
174 {"content-type": "application/x-www-form-urlencoded"})
175 for attempt in range(73):
176 try:
177 with urllib.request.urlopen(req, timeout=7200) as r:
178 d = json.load(r)
179 except OSError as e: # aien-translate itself down or restarting
180 print(f" translator unreachable ({e}); retrying in 5 minutes", flush=True)
181 time.sleep(300); continue
182 if d.get("result") != 1:
183 raise SystemExit(f"server refused: {d.get('info')}")
184 a = d.get("aien") or {}
185 # A whole batch back untranslated means the model is down or being swapped, not that the
186 # text is untranslatable: wait and ask again instead of writing English into the output.
187 if a.get("kept_original", 0) and not a.get("translated", 0) and not a.get("from_cache", 0) and len(batch) > 1:
188 print(f" {lang_id}: whole batch failed ({a}); model down? retrying in 5 minutes", flush=True)
189 time.sleep(300); continue
190 return d
191 raise SystemExit(f"{lang_id}: the model stayed unavailable for 6 hours; stopping without writing")
192
193
194def translate_all(server, lang_id, texts, chunk_items=None, chunk_chars=None):
195 chunk_items, chunk_chars = chunk_items or CHUNK_ITEMS, chunk_chars or CHUNK_CHARS
196 out, pending, i = {}, list(dict.fromkeys(t for t in texts if t)), 0
197 while i < len(pending):
198 batch, chars = [], 0
199 while i < len(pending) and (not batch or (len(batch) < chunk_items and chars + len(pending[i]) <= chunk_chars)):
200 batch.append(pending[i]); chars += len(pending[i]); i += 1
201 d = _ask(server, lang_id, batch)
202 out.update(zip(batch, d["text"]))
203 print(f" {lang_id}: {i}/{len(pending)} pieces ({d.get('aien')})", flush=True)
204 # One more try for pieces that came back unchanged (a restart can fail part of a batch).
205 again = [t for t in pending if out.get(t) == t and re.search(r"[^\W\d_]{2}", t)]
206 for k in range(0, len(again), 20):
207 batch = again[k:k + 20]
208 d = _ask(server, lang_id, batch)
209 out.update((s, t) for s, t in zip(batch, d["text"]) if t != s)
210 if again:
211 left = sum(1 for t in again if out.get(t) == t)
212 print(f" {lang_id}: retried {len(again)} unchanged pieces, {left} still unchanged", flush=True)
213 return out
214
215
216# Shown at the top of every translated page, then translated with the page. Drake 2026-10-18: make it clear
217# the translation ran on our own local model, to keep AI off data-center power.
218NOTE_CLASS = "aien-translation-note"
219NOTE_HTML = (
220 '<p class="aien-translation-note" style="margin:0;padding:10px 16px;font-size:14px;line-height:1.5;'
221 'color:var(--an-muted,#9aa4b2);border-bottom:1px solid var(--an-border,rgba(127,127,127,.25));'
222 'text-align:center">'
223 "<strong>Translated on our own machine.</strong> "
224 "AIEN's own AI model translated this page on a single computer in our lab, not in a data center. "
225 "AI data centers are putting a heavy load on power grids and adding to the emissions that warm our planet, "
226 "and we would rather not add to it. "
227 'The translation may have mistakes; the <a hreflang="en" href="/">English page</a> is the original.'
228 "</p>"
229)
230
231
232def add_note(soup):
233 """Put the translation note right under the site header (else first in <main> or <body>), once."""
234 if soup.find(class_=NOTE_CLASS):
235 return
236 note = BeautifulSoup(NOTE_HTML, "html.parser").p
237 header = soup.find("header", class_="aien-header")
238 if header is not None:
239 header.insert_after(note)
240 return
241 host = soup.find("main") or soup.body
242 if host is not None:
243 host.insert(0, note)
244
245
246def no_dashes(text, code):
247 """Drake's sites use no em or en dashes; keep translations to the same rule."""
248 if code in ("zh-CN", "zh-TW", "ja"):
249 text = re.sub(r"\s*[\u2014\u2013]+\s*", "," if code != "ja" else "、", text)
250 else:
251 text = re.sub(r"\s+[\u2014\u2013]+\s+", ", ", text)
252 text = text.replace("\u2014", ", ").replace("\u2013", "-")
253 return text
254
255
256def route_of(rel):
257 """URL path for a page file: index.html -> '/', a/index.html -> '/a/'."""
258 p = "/" + rel.as_posix()
259 return p[: -len("index.html")] if p.endswith("index.html") else p
260
261
262def main():
263 ap = argparse.ArgumentParser()
264 ap.add_argument("dist"); ap.add_argument("out")
265 ap.add_argument("--langs", required=True)
266 ap.add_argument("--server", default="http://127.0.0.1:18097")
267 ap.add_argument("--base-url", default="https://www.aienos.com")
268 a = ap.parse_args()
269 dist, out = Path(a.dist), Path(a.out)
270 codes = a.langs.split(",")
271 for c in codes:
272 if c not in LANGS:
273 sys.exit(f"unknown language {c}")
274
275 pages = sorted(p for p in dist.rglob("*.html") if not any(part in LANGS for part in p.relative_to(dist).parts[:1]))
276 routes = {route_of(p.relative_to(dist)) for p in pages}
277 parsed = {p: BeautifulSoup(p.read_text(encoding="utf-8"), "html.parser") for p in pages}
278 all_sources = []
279 for soup in parsed.values():
280 add_note(soup)
281 all_sources += [u.source for u in collect(soup)]
282 unique = list(dict.fromkeys(s for s in all_sources if s))
283 print(f"{len(pages)} pages, {len(unique)} unique pieces, {sum(map(len, unique))} characters")
284
285 for code in codes:
286 lang_id, name, html_lang = LANGS[code]
287 print(f"== {code}")
288 table = translate_all(a.server, lang_id, unique)
289 table = {k: no_dashes(v, code) for k, v in table.items()}
290 kept = 0
291 for page in pages:
292 rel = page.relative_to(dist)
293 soup = BeautifulSoup(page.read_text(encoding="utf-8"), "html.parser")
294 add_note(soup)
295 for u in collect(soup):
296 tr = table.get(u.source)
297 if not tr or tr == u.source:
298 continue
299 if u.kind == "attr":
300 u.el[u.attr] = tr
301 elif u.kind == "text":
302 s = str(u.el)
303 lead = s[: len(s) - len(s.lstrip())]
304 trail = s[len(s.rstrip()):]
305 u.el.replace_with(NavigableString(lead + tr + trail))
306 else:
307 nodes = decode(soup, tr, u.tags)
308 if nodes is None:
309 kept += 1
310 continue
311 u.el.clear()
312 for n in nodes:
313 u.el.append(n)
314 route = route_of(rel)
315 # Language, links, alternates.
316 if soup.html:
317 soup.html["lang"] = html_lang
318 for el in soup.find_all(["a", "link", "form"]):
319 attr = "action" if el.name == "form" else "href"
320 href = el.get(attr)
321 if not href or el.get("hreflang") or (el.name == "link" and el.get("rel") not in (["canonical"], ["alternate"])):
322 continue
323 if href.startswith("/") and not href.startswith("//") and not ASSET.search(href.split("#")[0].split("?")[0]):
324 path = href.split("#")[0].split("?")[0]
325 if path in routes or path.rstrip("/") + "/" in routes or path == "/":
326 el[attr] = f"/{code}{href}"
327 for el in soup.find_all("a", hreflang=True):
328 target = el["hreflang"]
329 el["href"] = route if target == "en" else f"/{target}{route}"
330 if soup.head:
331 for old in soup.head.find_all("link", rel="canonical"):
332 old.decompose()
333 canon = soup.new_tag("link", rel="canonical", href=f"{a.base_url}/{code}{route}")
334 soup.head.append(canon)
335 for c2, (_, _, hl) in [("en", (None, None, "en"))] + [(c, LANGS[c]) for c in codes]:
336 href = f"{a.base_url}{route}" if c2 == "en" else f"{a.base_url}/{c2}{route}"
337 soup.head.append(soup.new_tag("link", rel="alternate", hreflang=hl, href=href))
338 dest = out / code / rel
339 dest.parent.mkdir(parents=True, exist_ok=True)
340 dest.write_text(str(soup), encoding="utf-8")
341 print(f" wrote {len(pages)} pages to {out / code}; {kept} piece(s) kept in English because markers broke")
342
343
344if __name__ == "__main__":
345 main()