This commit is contained in:
1 parent
7e1769f134
commit
a3c25c943c
13 files changed
+355
-41
No files matched your search
+36
-26
@@ -10,14 +10,11 @@ Uses the public Google Translate endpoint (no key). Translations are stored in
|
||||
|
||||
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):
|
||||
@@ -29,8 +26,9 @@ for stream in (sys.stdout, sys.stderr):
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
import glossary
|
||||
import translate_providers as providers
|
||||
|
||||
ENDPOINT = "https://translate.googleapis.com/translate_a/single"
|
||||
MAX_CHUNK = 3800
|
||||
|
||||
|
||||
@@ -70,18 +68,12 @@ def split_chunks(text, size=MAX_CHUNK):
|
||||
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"})
|
||||
def translate_chunk(text, delay=0.25, retries=3, provider=None):
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=40) as resp:
|
||||
data = json.load(resp)
|
||||
translated, used = providers.translate(text, preferred=provider)
|
||||
time.sleep(delay)
|
||||
return "".join(part[0] for part in data[0] if part and part[0])
|
||||
return translated, used
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code in (429, 403):
|
||||
time.sleep(30 * (attempt + 1))
|
||||
@@ -89,19 +81,22 @@ def translate_chunk(text, delay=0.25, retries=3):
|
||||
time.sleep(2)
|
||||
except Exception:
|
||||
time.sleep(2)
|
||||
return None
|
||||
return None, None
|
||||
|
||||
|
||||
def translate_text(text, delay=0.25):
|
||||
def translate_text(text, delay=0.25, provider=None, terms=None):
|
||||
if not text:
|
||||
return None
|
||||
return None, None
|
||||
protected, tokens = glossary.protect(text, terms or {})
|
||||
parts = []
|
||||
for chunk in split_chunks(text):
|
||||
translated = translate_chunk(chunk, delay=delay)
|
||||
used = None
|
||||
for chunk in split_chunks(protected):
|
||||
translated, name = translate_chunk(chunk, delay=delay, provider=provider)
|
||||
if translated is None:
|
||||
return None
|
||||
return None, None
|
||||
parts.append(translated)
|
||||
return " ".join(parts)
|
||||
used = used or name
|
||||
return glossary.restore(" ".join(parts), tokens), used
|
||||
|
||||
|
||||
def pending_rows(con, limit=None, about=False):
|
||||
@@ -135,12 +130,12 @@ def pending_rows(con, limit=None, about=False):
|
||||
return rows[:limit] if limit else rows
|
||||
|
||||
|
||||
def save_translation(con, appid, short_ru, about_ru):
|
||||
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', ?, ?, 'google', ?)
|
||||
VALUES (?, 'ru', ?, ?, ?, ?)
|
||||
ON CONFLICT(appid) DO UPDATE SET
|
||||
lang = 'ru',
|
||||
short_description = COALESCE(excluded.short_description,
|
||||
@@ -148,7 +143,7 @@ def save_translation(con, appid, short_ru, about_ru):
|
||||
about = COALESCE(excluded.about, game_translations.about),
|
||||
provider = excluded.provider,
|
||||
translated_at = excluded.translated_at""",
|
||||
(appid, short_ru, about_ru, now),
|
||||
(appid, short_ru, about_ru, provider, now),
|
||||
)
|
||||
con.commit()
|
||||
|
||||
@@ -162,6 +157,11 @@ def main():
|
||||
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)
|
||||
@@ -180,24 +180,34 @@ def main():
|
||||
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 = translate_text(clean_html(row["short_description"]), args.delay)
|
||||
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 = translate_text(clean_html(row["about"]), args.delay)
|
||||
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)
|
||||
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}")
|
||||
|
||||
|
||||
Reference in new issue
Block a user