Files
SteamBase/tools/translate_details.py
2026-11-06 20:05:59 +03:00

219 lines
8.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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 os
import re
import sys
import time
import urllib.error
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
import glossary
import translate_providers as providers
MAX_CHUNK = 3800
def clean_html(text):
if not text:
return ""
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.I)
text = re.sub(r"</p>", "\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, provider=None):
for attempt in range(retries):
try:
translated, used = providers.translate(text, preferred=provider)
time.sleep(delay)
return translated, used
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, None
def translate_text(text, delay=0.25, provider=None, terms=None):
if not text:
return None, None
protected, tokens = glossary.protect(text, terms or {})
parts = []
used = None
for chunk in split_chunks(protected):
translated, name = translate_chunk(chunk, delay=delay, provider=provider)
if translated is None:
return None, None
parts.append(translated)
used = used or name
return glossary.restore(" ".join(parts), tokens), used
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, provider="google"):
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
con.execute(
"""INSERT INTO game_translations
(appid, lang, short_description, about, provider, translated_at)
VALUES (?, 'ru', ?, ?, ?, ?)
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, provider, 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")
ap.add_argument("--provider", choices=providers.PROVIDERS,
help="google, libretranslate or deepl (default from env)")
ap.add_argument("--glossary", default=glossary.DEFAULT_PATH,
help="JSON glossary path (default: data/glossary.json)")
ap.add_argument("--no-glossary", 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
terms = {} if args.no_glossary else glossary.load(args.glossary)
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 ""))
print(f"Provider: {args.provider or providers.default_provider()} | "
f"glossary: {len(terms)} terms")
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
provider_used = None
if not existing_short and row["short_description"]:
short_ru, provider_used = translate_text(
clean_html(row["short_description"]), args.delay,
provider=args.provider, terms=terms)
about_ru = None
if args.about and row["about"]:
about_ru, used = translate_text(
clean_html(row["about"]), args.delay,
provider=args.provider, terms=terms)
provider_used = provider_used or used
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,
provider=provider_used or providers.default_provider())
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()