diff --git a/cli/build/i18n/__main__.py b/cli/build/i18n/__main__.py index 2d8686d677..c570e60cb7 100644 --- a/cli/build/i18n/__main__.py +++ b/cli/build/i18n/__main__.py @@ -12,12 +12,14 @@ Usage: from __future__ import annotations import argparse +import fcntl import json import os import sys import tempfile from collections import Counter from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor +from contextlib import contextmanager from pathlib import Path from utils.cache.files import PROJECT_ROOT @@ -48,6 +50,7 @@ from utils.i18n.translate import ( apply, damaged, discard, + over_shared, pending, retry, taken_translations, @@ -110,13 +113,18 @@ def prune(domains: list[str], requested: list[str]) -> int: if not path.is_file(): continue catalog = read_catalog(path) + shared = over_shared(catalog) + discard(shared) broken = damaged(catalog) - if not broken: - continue discard(broken) + if not shared and not broken: + continue write_catalog(path, catalog) - cleared += len(broken) - print(f"{domain}/{code}: {len(broken)} damaged translations cleared") + cleared += len(shared) + len(broken) + print( + f"{domain}/{code}: {len(broken)} damaged and {len(shared)} " + "collapsed translations cleared" + ) print(f"{domain}: {cleared} translations cleared") return 0 @@ -149,6 +157,31 @@ def usable_cpus() -> int: return os.cpu_count() or 1 +@contextmanager +def exclusive(domain: str, code: str): + """Hold the one lock that admits a writer to a catalog. + + ``one_catalog`` reads the catalog once, keeps the translations it has + already spent in memory, and writes the whole file back after every chunk. + Two runs over the same catalog therefore each hold a private view of what + is taken and overwrite each other's entries, which is how distinct sources + end up sharing one translation with every per-entry predicate passing. + + Args: + domain: catalog domain. + code: ISO 639-1 code of the catalog. + """ + lock = PROJECT_ROOT / "build" / "i18n" / f"{domain}-{code}.lock" + lock.parent.mkdir(parents=True, exist_ok=True) + with lock.open("w") as handle: + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + print(f"{domain}/{code}: another run holds it, waiting", flush=True) + fcntl.flock(handle, fcntl.LOCK_EX) + yield + + def one_catalog(client: LibreTranslate, domain: str, code: str) -> None: """Translate every pending entry of one catalog and write it back. @@ -158,24 +191,25 @@ def one_catalog(client: LibreTranslate, domain: str, code: str) -> None: code: ISO 639-1 code of the catalog. """ path = catalog_path(PROJECT_ROOT, code, domain) - catalog = read_catalog(path) - todo = pending(catalog) - taken = taken_translations(catalog) - discarded = refused = damaged = 0 - criteria: Counter[str] = Counter() - refusal = "" - for start in range(0, len(todo), CHUNK_SIZE): - chunk = todo[start : start + CHUNK_SIZE] - outcome = client.translate([m.id for m in chunk], code) - criteria.update( - value.reason for value in outcome.values if isinstance(value, Rejected) - ) - discarded += apply(chunk, outcome.values, taken, criteria) - refused += outcome.refused - damaged += outcome.damaged - refusal = outcome.refusal or refusal - write_catalog(path, catalog) - print(f"{domain}/{code}: {start + len(chunk)}/{len(todo)}", flush=True) + with exclusive(domain, code): + catalog = read_catalog(path) + todo = pending(catalog) + taken = taken_translations(catalog) + discarded = refused = damaged = 0 + criteria: Counter[str] = Counter() + refusal = "" + for start in range(0, len(todo), CHUNK_SIZE): + chunk = todo[start : start + CHUNK_SIZE] + outcome = client.translate([m.id for m in chunk], code) + criteria.update( + value.reason for value in outcome.values if isinstance(value, Rejected) + ) + discarded += apply(chunk, outcome.values, taken, criteria) + refused += outcome.refused + damaged += outcome.damaged + refusal = outcome.refusal or refusal + write_catalog(path, catalog) + print(f"{domain}/{code}: {start + len(chunk)}/{len(todo)}", flush=True) tail = f", last refusal {refusal}" if refused else "" broke = ", ".join(f"{count} {name}" for name, count in criteria.most_common()) print( diff --git a/tests/integration/i18n/__init__.py b/tests/integration/i18n/__init__.py index 6a7bffac57..b3486c2dff 100644 --- a/tests/integration/i18n/__init__.py +++ b/tests/integration/i18n/__init__.py @@ -40,6 +40,8 @@ from pathlib import Path from tests.utils.services import progress as _progress from utils.i18n.catalog import MACHINE_TRANSLATION, catalog_path, read_catalog +from utils.i18n.damage import COLLAPSE_FLOOR as MIN_SOURCE_CHARS +from utils.i18n.damage import MAX_SHARING_SOURCES as MAX_SHARING_SOURCES from utils.i18n.languages import DOMAINS, load_languages, translatable from utils.i18n.spans import prose from utils.i18n.untranslatable import untranslatable @@ -48,8 +50,6 @@ PROJECT_ROOT = Path(__file__).resolve().parents[3] SUITE = "catalog-scan" CACHE_FILE = PROJECT_ROOT / "build" / "catalog-scan-cache.json" RULES_VERSION = 5 -MIN_SOURCE_CHARS = 40 -MAX_SHARING_SOURCES = 2 EXAMPLES_PER_TRANSLATION = 3 MEMINFO = Path("/proc/meminfo") BYTES_PER_WORKER = 512 * 1024**2 diff --git a/tests/unit/python/utils/i18n/test_translate.py b/tests/unit/python/utils/i18n/test_translate.py index d62224fa4f..3085434a7f 100644 --- a/tests/unit/python/utils/i18n/test_translate.py +++ b/tests/unit/python/utils/i18n/test_translate.py @@ -24,6 +24,7 @@ from utils.i18n.translate import ( URL_SUPPRESSION, apply, damaged, + over_shared, pending, retry, taken_translations, @@ -370,5 +371,55 @@ class TestDuplicateTranslation(unittest.TestCase): self.assertEqual(taken_translations(catalog), {"Schon vergeben"}) +class TestOverSharedTranslation(unittest.TestCase): + LONG_A = "Central identity provider issuing tokens for every service" + LONG_B = "Issue and project tracking platform for software teams today" + LONG_C = "Reverse proxy routing and balancing traffic to the backends" + SHORT_A = "Save the file" + SHORT_B = "Open the file" + SHORT_C = "Close the file" + SHARED = "Beschreibung eines Dienstes" + + def _catalog(self, sources: list, translation: str, *, machine: bool = True): + catalog = Catalog(locale="de") + for source in sources: + catalog.add(source, translation) + for message in catalog: + if message.id and machine: + message.user_comments = [MACHINE_TRANSLATION] + return catalog + + def _ids(self, catalog) -> list: + return sorted(str(message.id) for message in over_shared(catalog)) + + def test_every_sharer_beyond_the_limit_is_returned(self) -> None: + catalog = self._catalog( + [self.LONG_A, self.LONG_B, self.LONG_C], self.SHARED + ) + + self.assertEqual( + self._ids(catalog), sorted([self.LONG_A, self.LONG_B, self.LONG_C]) + ) + + def test_two_sharers_stay(self) -> None: + catalog = self._catalog([self.LONG_A, self.LONG_B], self.SHARED) + + self.assertEqual(over_shared(catalog), []) + + def test_short_sources_may_share_one(self) -> None: + catalog = self._catalog( + [self.SHORT_A, self.SHORT_B, self.SHORT_C], "Datei" + ) + + self.assertEqual(over_shared(catalog), []) + + def test_a_hand_translation_is_left_alone(self) -> None: + catalog = self._catalog( + [self.LONG_A, self.LONG_B, self.LONG_C], self.SHARED, machine=False + ) + + self.assertEqual(over_shared(catalog), []) + + if __name__ == "__main__": unittest.main() diff --git a/utils/i18n/damage.py b/utils/i18n/damage.py index 16cf084f74..713af636f2 100644 --- a/utils/i18n/damage.py +++ b/utils/i18n/damage.py @@ -21,6 +21,7 @@ TRUNCATION_FLOOR = 120 TRUNCATION_RATIO = 0.5 COLLAPSE_FLOOR = 40 COLLAPSE_RATIO = 0.15 +MAX_SHARING_SOURCES = 2 ECHO_FLOOR = 30 STUTTER = re.compile(r"\b(\w+)(?:\s+\1\b){2,}", re.IGNORECASE | re.UNICODE) WORDS = re.compile(r"[^\W\d_]{2,}", re.UNICODE) diff --git a/utils/i18n/placeholders.py b/utils/i18n/placeholders.py index 646dc0f43d..fc16160ee9 100644 --- a/utils/i18n/placeholders.py +++ b/utils/i18n/placeholders.py @@ -17,6 +17,7 @@ from utils.i18n.damage import ECHO_FLOOR as ECHO_FLOOR from utils.i18n.damage import LATIN_FLOOR as LATIN_FLOOR from utils.i18n.damage import LATIN_SHARE as LATIN_SHARE from utils.i18n.damage import MARKUP as MARKUP +from utils.i18n.damage import MAX_SHARING_SOURCES as MAX_SHARING_SOURCES from utils.i18n.damage import NON_LATIN_SCRIPTS as NON_LATIN_SCRIPTS from utils.i18n.damage import STRUCTURE as STRUCTURE from utils.i18n.damage import STUTTER as STUTTER diff --git a/utils/i18n/translate.py b/utils/i18n/translate.py index 04af41deba..b9eb60b62b 100644 --- a/utils/i18n/translate.py +++ b/utils/i18n/translate.py @@ -13,6 +13,7 @@ from utils.i18n.catalog import ( ) from utils.i18n.placeholders import ( COLLAPSE_FLOOR, + MAX_SHARING_SOURCES, Rejected, harms, protected_spans, @@ -125,6 +126,37 @@ def damaged(catalog: Catalog) -> list[Message]: ] +def over_shared(catalog: Catalog) -> list[Message]: + """Return the entries too many distinct sources translate the same way. + + :func:`damaged` reads one entry at a time and cannot see this: each entry + is individually sound, and what is gone is the distinction between them. + :func:`apply` turns a repeat down through ``taken``, so a catalog reaches + this state only when two runs translated it at once, each holding its own + view of what was already spent. Every sharer is cleared rather than all + but one: the run that produced them gave no reason to believe any one of + them belongs to the source it landed on. + + Args: + catalog: a language catalog. + """ + sharers: dict[str, list[Message]] = {} + for message in catalog: + if not message.id or not message.string: + continue + if MACHINE_TRANSLATION not in (message.user_comments or []): + continue + if not _own_translation_due(str(message.id)): + continue + sharers.setdefault(str(message.string), []).append(message) + return [ + message + for shared in sharers.values() + if len(shared) > MAX_SHARING_SOURCES + for message in shared + ] + + def discard(messages: list[Message]) -> None: """Empty the translation of every entry, so it becomes pending again.