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

55 lines
1.6 KiB
Python

"""Glossary protection for machine translation.
Terms are replaced with placeholders before translation and restored after it,
so names like "Souls-like" or "Roguelike" stay consistent.
Default file: data/glossary.json (not committed). Example:
tools/glossary.example.json.
"""
import json
import os
import re
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEFAULT_PATH = os.path.join(BASE_DIR, "data", "glossary.json")
def load(path=None):
path = path or DEFAULT_PATH
if not os.path.isfile(path):
return {}
try:
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
except (OSError, ValueError):
return {}
if not isinstance(data, dict):
return {}
return {str(key): str(value) for key, value in data.items()
if str(key).strip() and str(value).strip()}
def protect(text, terms):
"""Return (text_with_placeholders, tokens) for the given glossary."""
if not text or not terms:
return text, {}
lookup = {key.lower(): value for key, value in terms.items()}
keys = sorted(lookup, key=len, reverse=True)
pattern = re.compile(r"(?<!\w)(" + "|".join(re.escape(key) for key in keys) + r")(?!\w)",
re.IGNORECASE)
tokens = {}
def replace(match):
token = f"[[SB{len(tokens)}]]"
tokens[token] = lookup[match.group(0).lower()]
return token
return pattern.sub(replace, text), tokens
def restore(text, tokens):
for token, value in tokens.items():
text = text.replace(token, value)
return text