"""Translate cached English descriptions into Russian. Uses the public Google Translate endpoint (no key). Translations are stored in ``game_translations`` and preferred by the web UI over the original text. python tools/translate_details.py --stats python tools/translate_details.py --limit 200 python tools/translate_details.py --all --about """ import argparse import html import json import os import re import sys import time import urllib.error import urllib.parse import urllib.request from datetime import datetime, timezone for stream in (sys.stdout, sys.stderr): try: stream.reconfigure(encoding="utf-8") except Exception: pass sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import db ENDPOINT = "https://translate.googleapis.com/translate_a/single" MAX_CHUNK = 3800 def clean_html(text): if not text: return "" text = re.sub(r"", "\n", text, flags=re.I) text = re.sub(r"

", "\n", text, flags=re.I) text = re.sub(r"<[^>]+>", " ", text) text = html.unescape(text) return " ".join(text.split()) def looks_english(text): if not text: return False letters = [c for c in text if c.isalpha()] if len(letters) < 8: return False latin = sum(1 for c in letters if "a" <= c.lower() <= "z") cyrillic = sum(1 for c in letters if "а" <= c.lower() <= "я" or c.lower() == "ё") return latin / len(letters) > 0.6 and cyrillic / len(letters) < 0.1 def split_chunks(text, size=MAX_CHUNK): chunks, current = [], "" for part in re.split(r"(?<=[.!?])\s+|\n+", text): if not part: continue if len(current) + len(part) + 1 > size and current: chunks.append(current.strip()) current = part else: current = f"{current} {part}".strip() if current: chunks.append(current.strip()) return chunks or [text[:size]] def translate_chunk(text, delay=0.25, retries=3): params = urllib.parse.urlencode({ "client": "gtx", "sl": "auto", "tl": "ru", "dt": "t", "q": text, }) req = urllib.request.Request(f"{ENDPOINT}?{params}", headers={"User-Agent": "Mozilla/5.0"}) for attempt in range(retries): try: with urllib.request.urlopen(req, timeout=40) as resp: data = json.load(resp) time.sleep(delay) return "".join(part[0] for part in data[0] if part and part[0]) except urllib.error.HTTPError as exc: if exc.code in (429, 403): time.sleep(30 * (attempt + 1)) continue time.sleep(2) except Exception: time.sleep(2) return None def translate_text(text, delay=0.25): if not text: return None parts = [] for chunk in split_chunks(text): translated = translate_chunk(chunk, delay=delay) if translated is None: return None parts.append(translated) return " ".join(parts) def pending_rows(con, limit=None, about=False): if about: sql = """ SELECT d.appid, d.short_description, d.about, t.short_description AS short_existing FROM game_details d JOIN games g ON g.appid = d.appid LEFT JOIN game_translations t ON t.appid = d.appid WHERE d.status = 'ok' AND LOWER(g.type) = 'game' AND COALESCE(d.about, '') <> '' AND t.about IS NULL ORDER BY COALESCE(g.review_pct, 0) DESC, g.name """ rows = [r for r in con.execute(sql) if looks_english(r["about"])] else: sql = """ SELECT d.appid, d.short_description, d.about FROM game_details d JOIN games g ON g.appid = d.appid LEFT JOIN game_translations t ON t.appid = d.appid WHERE d.status = 'ok' AND LOWER(g.type) = 'game' AND t.appid IS NULL AND (COALESCE(d.short_description, '') <> '' OR COALESCE(d.about, '') <> '') ORDER BY COALESCE(g.review_pct, 0) DESC, g.name """ rows = [r for r in con.execute(sql) if looks_english(r["short_description"]) or (not r["short_description"] and looks_english(r["about"]))] return rows[:limit] if limit else rows def save_translation(con, appid, short_ru, about_ru): now = datetime.now(timezone.utc).isoformat(timespec="seconds") con.execute( """INSERT INTO game_translations (appid, lang, short_description, about, provider, translated_at) VALUES (?, 'ru', ?, ?, 'google', ?) ON CONFLICT(appid) DO UPDATE SET lang = 'ru', short_description = COALESCE(excluded.short_description, game_translations.short_description), about = COALESCE(excluded.about, game_translations.about), provider = excluded.provider, translated_at = excluded.translated_at""", (appid, short_ru, about_ru, now), ) con.commit() def main(): ap = argparse.ArgumentParser(description="Translate descriptions to Russian") ap.add_argument("--db", default=db.DEFAULT_DB) ap.add_argument("--limit", type=int) ap.add_argument("--all", action="store_true") ap.add_argument("--about", action="store_true", help="translate full descriptions too") ap.add_argument("--delay", type=float, default=0.3) ap.add_argument("--dry-run", action="store_true") ap.add_argument("--stats", action="store_true") args = ap.parse_args() con = db.connect(args.db) db.init(con) if args.stats: rows = con.execute("""SELECT d.short_description, d.about FROM game_details d JOIN games g ON g.appid=d.appid WHERE d.status='ok' AND LOWER(g.type)='game'""").fetchall() total = sum(1 for r in rows if looks_english(r["short_description"]) or (not r["short_description"] and looks_english(r["about"]))) done = con.execute("""SELECT COUNT(*) FROM game_translations t JOIN games g ON g.appid=t.appid WHERE LOWER(g.type)='game'""").fetchone()[0] print(f"english details: {total} | translated: {done} | pending: {len(pending_rows(con))}" f" | full pending: {len(pending_rows(con, about=True))}") return limit = None if args.all else (args.limit or 100) rows = pending_rows(con, limit, about=args.about) print(f"To translate: {len(rows)}" + (" (with full descriptions)" if args.about else "")) ok = failed = 0 for i, row in enumerate(rows, 1): existing_short = row["short_existing"] if args.about and "short_existing" in row.keys() else None short_ru = None if not existing_short and row["short_description"]: short_ru = translate_text(clean_html(row["short_description"]), args.delay) about_ru = None if args.about and row["about"]: about_ru = translate_text(clean_html(row["about"]), args.delay) if not short_ru and not about_ru and not existing_short: failed += 1 continue ok += 1 if not args.dry_run: save_translation(con, row["appid"], short_ru or existing_short, about_ru) if i % 10 == 0 or i == len(rows): print(f" {i}/{len(rows)} ok={ok} failed={failed}") print(f"Done. translated={ok} failed={failed}") if __name__ == "__main__": main()