diff --git a/cli/build/i18n/__main__.py b/cli/build/i18n/__main__.py index 3ea7ed8367..6fdcbff285 100644 --- a/cli/build/i18n/__main__.py +++ b/cli/build/i18n/__main__.py @@ -3,7 +3,7 @@ Usage: python -m cli.build.i18n extract [--domain core|docs] python -m cli.build.i18n translate --domain core|docs [--languages de,fr] - python -m cli.build.i18n languages [--domain core|docs] + python -m cli.build.i18n languages python -m cli.build.i18n prune [--domain core|docs] [--languages de,fr] python -m cli.build.i18n retry [--domain core|docs] [--languages de,fr] python -m cli.build.i18n tune [--language de] @@ -37,7 +37,6 @@ from utils.i18n.languages import ( DOMAINS, domain_languages, load_languages, - translatable, ) from utils.i18n.gateway import ( READY_TIMEOUT_SECONDS, @@ -45,6 +44,7 @@ from utils.i18n.gateway import ( download_status, server, ) +from utils.i18n.libretranslate import served_languages from utils.i18n.placeholders import Rejected from utils.i18n.translate import ( apply, @@ -97,8 +97,17 @@ def extract(domains: list[str]) -> int: def languages(domains: list[str]) -> int: + """Print every language carrying a catalog, as a JSON array. + + The caller is the CI matrix of ``entry-pr-translate.yml``, which opens one + branch and one pull request per code. Every language the repository names + is translated, so every one of them belongs in the matrix: the gateway + offers each backend that serves the pair and falls through to its chat + backend, which declares no catalogue and therefore answers for the pairs + the dedicated engines do not cover. + """ loaded = load_languages(PROJECT_ROOT) - codes = sorted({code for d in domains for code in translatable(loaded, d)}) + codes = sorted({code for d in domains for code in domain_languages(loaded, d)}) print(json.dumps(codes)) return 0 @@ -223,15 +232,16 @@ def translate(domains: list[str], requested: list[str], redeploy: bool = False) loaded = load_languages(PROJECT_ROOT) work: list[tuple[str, str]] = [] for domain in domains: - supported = translatable(loaded, domain) + supported = domain_languages(loaded, domain) unsupported = sorted(set(requested) - set(supported)) if unsupported: - print(f"the translation gateway does not serve {unsupported}", file=sys.stderr) + print(f"{', '.join(unsupported)} is not a language this repository names", file=sys.stderr) return 2 work += [ (domain, code) for code in (sorted(requested) if requested else supported) - if pending(read_catalog(catalog_path(PROJECT_ROOT, code, domain))) + if catalog_path(PROJECT_ROOT, code, domain).is_file() + and pending(read_catalog(catalog_path(PROJECT_ROOT, code, domain))) ] if not work: print(f"{', '.join(domains)}: nothing to translate") diff --git a/cli/build/i18n/tune.py b/cli/build/i18n/tune.py index 92c3744576..9ba93a47e5 100644 --- a/cli/build/i18n/tune.py +++ b/cli/build/i18n/tune.py @@ -16,11 +16,11 @@ from statistics import median from utils.cache.files import PROJECT_ROOT from utils.i18n.catalog import catalog_path, read_catalog -from utils.i18n.languages import load_languages, translatable from utils.i18n.libretranslate import ( READY_TIMEOUT_SECONDS, LibreTranslate, download_status, + served_languages, server, ) from utils.i18n.translate import pending @@ -144,7 +144,7 @@ def main(code: str, cpus: int) -> int: Returns: 0 on success, 2 when no catalog offers the language. """ - if code not in translatable(load_languages(PROJECT_ROOT), "docs"): + if code not in served_languages(PROJECT_ROOT): print(f"LibreTranslate does not support {code}") return 2 outcome = tune(cpus, code) diff --git a/meta/languages.yml b/meta/languages.yml index dfbf439278..c695dab7da 100644 --- a/meta/languages.yml +++ b/meta/languages.yml @@ -3,919 +3,735 @@ aa: name: "Afar" native: "Qafaraf" direction: ltr - libretranslate: false ab: name: "Abkhazian" native: "Аԥсшәа" direction: ltr - libretranslate: false ae: name: "Avestan" native: "Avesta" direction: ltr - libretranslate: false af: name: "Afrikaans" native: "Afrikaans" direction: ltr - libretranslate: false ak: name: "Akan" native: "Akan" direction: ltr - libretranslate: false am: name: "Amharic" native: "አማርኛ" direction: ltr - libretranslate: false an: name: "Aragonese" native: "Aragonés" direction: ltr - libretranslate: false ar: name: "Arabic" native: "العربية" direction: rtl - libretranslate: true as: name: "Assamese" native: "অসমীয়া" direction: ltr - libretranslate: false av: name: "Avaric" native: "Авар мацӀ" direction: ltr - libretranslate: false ay: name: "Aymara" native: "Aymar aru" direction: ltr - libretranslate: false az: name: "Azerbaijani" native: "Azərbaycan" direction: ltr - libretranslate: true ba: name: "Bashkir" native: "Башҡорт" direction: ltr - libretranslate: false be: name: "Belarusian" native: "Беларуская" direction: ltr - libretranslate: false bg: name: "Bulgarian" native: "Български" direction: ltr - libretranslate: true bh: name: "Bihari" native: "भोजपुरी" direction: ltr - libretranslate: false bi: name: "Bislama" native: "Bislama" direction: ltr - libretranslate: false bm: name: "Bambara" native: "Bamanakan" direction: ltr - libretranslate: false bn: name: "Bangla" native: "বাংলা" direction: ltr - libretranslate: true bo: name: "Tibetan" native: "བོད་སྐད་" direction: ltr - libretranslate: false br: name: "Breton" native: "Brezhoneg" direction: ltr - libretranslate: false bs: name: "Bosnian" native: "Bosanski" direction: ltr - libretranslate: false ca: name: "Catalan" native: "Català" direction: ltr - libretranslate: true ce: name: "Chechen" native: "Нохчийн" direction: ltr - libretranslate: false ch: name: "Chamorro" native: "Chamoru" direction: ltr - libretranslate: false co: name: "Corsican" native: "Corsu" direction: ltr - libretranslate: false cr: name: "Cree" native: "ᓀᐦᐃᔭᐍᐏᐣ" direction: ltr - libretranslate: false cs: name: "Czech" native: "Čeština" direction: ltr - libretranslate: true cu: name: "Church Slavic" native: "Словѣньскъ" direction: ltr - libretranslate: false cv: name: "Chuvash" native: "Чӑваш чӗлхи" direction: ltr - libretranslate: false cy: name: "Welsh" native: "Cymraeg" direction: ltr - libretranslate: false da: name: "Danish" native: "Dansk" direction: ltr - libretranslate: true de: name: "German" native: "Deutsch" direction: ltr - libretranslate: true dv: name: "Divehi" native: "ދިވެހި" direction: rtl - libretranslate: false dz: name: "Dzongkha" native: "རྫོང་ཁ" direction: ltr - libretranslate: false ee: name: "Ewe" native: "Eʋegbe" direction: ltr - libretranslate: false el: name: "Greek" native: "Ελληνικά" direction: ltr - libretranslate: true en: name: "English" native: "English" direction: ltr - libretranslate: false eo: name: "Esperanto" native: "Esperanto" direction: ltr - libretranslate: true es: name: "Spanish" native: "Español" direction: ltr - libretranslate: true et: name: "Estonian" native: "Eesti" direction: ltr - libretranslate: true eu: name: "Basque" native: "Euskara" direction: ltr - libretranslate: true fa: name: "Persian" native: "فارسی" direction: rtl - libretranslate: true ff: name: "Fula" native: "Pulaar" direction: ltr - libretranslate: false fi: name: "Finnish" native: "Suomi" direction: ltr - libretranslate: true fj: name: "Fijian" native: "Vosa Vakaviti" direction: ltr - libretranslate: false fo: name: "Faroese" native: "Føroyskt" direction: ltr - libretranslate: false fr: name: "French" native: "Français" direction: ltr - libretranslate: true fy: name: "Western Frisian" native: "Frysk" direction: ltr - libretranslate: false ga: name: "Irish" native: "Gaeilge" direction: ltr - libretranslate: true gd: name: "Scottish Gaelic" native: "Gàidhlig" direction: ltr - libretranslate: false gl: name: "Galician" native: "Galego" direction: ltr - libretranslate: true gn: name: "Guarani" native: "Avañeʼẽ" direction: ltr - libretranslate: false gu: name: "Gujarati" native: "ગુજરાતી" direction: ltr - libretranslate: false gv: name: "Manx" native: "Gaelg" direction: ltr - libretranslate: false ha: name: "Hausa" native: "Hausa" direction: ltr - libretranslate: false he: name: "Hebrew" native: "עברית" direction: rtl - libretranslate: true hi: name: "Hindi" native: "हिन्दी" direction: ltr - libretranslate: true ho: name: "Hiri Motu" native: "Hiri Motu" direction: ltr - libretranslate: false hr: name: "Croatian" native: "Hrvatski" direction: ltr - libretranslate: false ht: name: "Haitian Creole" native: "Kreyòl ayisyen" direction: ltr - libretranslate: false hu: name: "Hungarian" native: "Magyar" direction: ltr - libretranslate: true hy: name: "Armenian" native: "Հայերեն" direction: ltr - libretranslate: false hz: name: "Herero" native: "Otjiherero" direction: ltr - libretranslate: false ia: name: "Interlingua" native: "Interlingua" direction: ltr - libretranslate: false id: name: "Indonesian" native: "Indonesia" direction: ltr - libretranslate: true ie: name: "Interlingue" native: "Interlingue" direction: ltr - libretranslate: false ig: name: "Igbo" native: "Igbo" direction: ltr - libretranslate: false ii: name: "Sichuan Yi" native: "ꆈꌠꉙ" direction: ltr - libretranslate: false ik: name: "Inupiaq" native: "Iñupiaq" direction: ltr - libretranslate: false io: name: "Ido" native: "Ido" direction: ltr - libretranslate: false is: name: "Icelandic" native: "Íslenska" direction: ltr - libretranslate: false it: name: "Italian" native: "Italiano" direction: ltr - libretranslate: true iu: name: "Inuktitut" native: "ᐃᓄᒃᑎᑐᑦ" direction: ltr - libretranslate: false ja: name: "Japanese" native: "日本語" direction: ltr - libretranslate: true jv: name: "Javanese" native: "Jawa" direction: ltr - libretranslate: false ka: name: "Georgian" native: "Ქართული" direction: ltr - libretranslate: false kg: name: "Kongo" native: "Kikongo" direction: ltr - libretranslate: false ki: name: "Kikuyu" native: "Gikuyu" direction: ltr - libretranslate: false kj: name: "Kuanyama" native: "Oshikwanyama" direction: ltr - libretranslate: false kk: name: "Kazakh" native: "Қазақ тілі" direction: ltr - libretranslate: false kl: name: "Kalaallisut" native: "Kalaallisut" direction: ltr - libretranslate: false km: name: "Khmer" native: "ខ្មែរ" direction: ltr - libretranslate: false kn: name: "Kannada" native: "ಕನ್ನಡ" direction: ltr - libretranslate: false ko: name: "Korean" native: "한국어" direction: ltr - libretranslate: true kr: name: "Kanuri" native: "Kanuri" direction: ltr - libretranslate: false ks: name: "Kashmiri" native: "کٲشُر" direction: rtl - libretranslate: false ku: name: "Kurdish" native: "Kurdî (kurmancî)" direction: ltr - libretranslate: false kv: name: "Komi" native: "Коми кыв" direction: ltr - libretranslate: false kw: name: "Cornish" native: "Kernewek" direction: ltr - libretranslate: false ky: name: "Kyrgyz" native: "Кыргызча" direction: ltr - libretranslate: true la: name: "Latin" native: "Latina" direction: ltr - libretranslate: false lb: name: "Luxembourgish" native: "Lëtzebuergesch" direction: ltr - libretranslate: false lg: name: "Ganda" native: "Luganda" direction: ltr - libretranslate: false li: name: "Limburgish" native: "Limburgs" direction: ltr - libretranslate: false ln: name: "Lingala" native: "Lingála" direction: ltr - libretranslate: false lo: name: "Lao" native: "ລາວ" direction: ltr - libretranslate: false lt: name: "Lithuanian" native: "Lietuvių" direction: ltr - libretranslate: true lu: name: "Luba-Katanga" native: "Tshiluba" direction: ltr - libretranslate: false lv: name: "Latvian" native: "Latviešu" direction: ltr - libretranslate: true mg: name: "Malagasy" native: "Malagasy" direction: ltr - libretranslate: false mh: name: "Marshallese" native: "Kajin M̧ajeļ" direction: ltr - libretranslate: false mi: name: "Māori" native: "Māori" direction: ltr - libretranslate: false mk: name: "Macedonian" native: "Македонски" direction: ltr - libretranslate: false ml: name: "Malayalam" native: "മലയാളം" direction: ltr - libretranslate: false mn: name: "Mongolian" native: "Монгол" direction: ltr - libretranslate: false mr: name: "Marathi" native: "मराठी" direction: ltr - libretranslate: false ms: name: "Malay" native: "Melayu" direction: ltr - libretranslate: true mt: name: "Maltese" native: "Malti" direction: ltr - libretranslate: false my: name: "Burmese" native: "မြန်မာ" direction: ltr - libretranslate: false na: name: "Nauru" native: "Dorerin Naoero" direction: ltr - libretranslate: false nb: name: "Norwegian Bokmål" native: "Norsk bokmål" direction: ltr - libretranslate: true nd: name: "North Ndebele" native: "IsiNdebele" direction: ltr - libretranslate: false ne: name: "Nepali" native: "नेपाली" direction: ltr - libretranslate: false ng: name: "Ndonga" native: "Oshindonga" direction: ltr - libretranslate: false nl: name: "Dutch" native: "Nederlands" direction: ltr - libretranslate: true nn: name: "Norwegian Nynorsk" native: "Norsk nynorsk" direction: ltr - libretranslate: false "no": name: "Norwegian" native: "Norsk" direction: ltr - libretranslate: false nr: name: "South Ndebele" native: "IsiNdebele" direction: ltr - libretranslate: false nv: name: "Navajo" native: "Diné bizaad" direction: ltr - libretranslate: false ny: name: "Nyanja" native: "Chichewa" direction: ltr - libretranslate: false oc: name: "Occitan" native: "Occitan" direction: ltr - libretranslate: false oj: name: "Ojibwa" native: "Anishinaabemowin" direction: ltr - libretranslate: false om: name: "Oromo" native: "Oromoo" direction: ltr - libretranslate: false or: name: "Odia" native: "ଓଡ଼ିଆ" direction: ltr - libretranslate: false os: name: "Ossetic" native: "Ирон" direction: ltr - libretranslate: false pa: name: "Punjabi" native: "ਪੰਜਾਬੀ" direction: ltr - libretranslate: false pi: name: "Pali" native: "पाळि" direction: ltr - libretranslate: false pl: name: "Polish" native: "Polski" direction: ltr - libretranslate: true ps: name: "Pashto" native: "پښتو" direction: rtl - libretranslate: false pt: name: "Portuguese" native: "Português" direction: ltr - libretranslate: true qu: name: "Quechua" native: "Runasimi" direction: ltr - libretranslate: false rm: name: "Romansh" native: "Rumantsch" direction: ltr - libretranslate: false rn: name: "Rundi" native: "Ikirundi" direction: ltr - libretranslate: false ro: name: "Romanian" native: "Română" direction: ltr - libretranslate: true ru: name: "Russian" native: "Русский" direction: ltr - libretranslate: true rw: name: "Kinyarwanda" native: "Ikinyarwanda" direction: ltr - libretranslate: false sa: name: "Sanskrit" native: "संस्कृत भाषा" direction: ltr - libretranslate: false sc: name: "Sardinian" native: "Sardu" direction: ltr - libretranslate: false sd: name: "Sindhi" native: "سنڌي" direction: rtl - libretranslate: false se: name: "Northern Sami" native: "Davvisámegiella" direction: ltr - libretranslate: false sg: name: "Sango" native: "Sängö" direction: ltr - libretranslate: false si: name: "Sinhala" native: "සිංහල" direction: ltr - libretranslate: false sk: name: "Slovak" native: "Slovenčina" direction: ltr - libretranslate: true sl: name: "Slovenian" native: "Slovenščina" direction: ltr - libretranslate: true sm: name: "Samoan" native: "Gagana Samoa" direction: ltr - libretranslate: false sn: name: "Shona" native: "ChiShona" direction: ltr - libretranslate: false so: name: "Somali" native: "Soomaali" direction: ltr - libretranslate: false sq: name: "Albanian" native: "Shqip" direction: ltr - libretranslate: true sr: name: "Serbian" native: "Српски" direction: ltr - libretranslate: false ss: name: "Swati" native: "SiSwati" direction: ltr - libretranslate: false st: name: "Southern Sotho" native: "Sesotho" direction: ltr - libretranslate: false su: name: "Sundanese" native: "Basa Sunda" direction: ltr - libretranslate: false sv: name: "Swedish" native: "Svenska" direction: ltr - libretranslate: true sw: name: "Swahili" native: "Kiswahili" direction: ltr - libretranslate: true ta: name: "Tamil" native: "தமிழ்" direction: ltr - libretranslate: false te: name: "Telugu" native: "తెలుగు" direction: ltr - libretranslate: false tg: name: "Tajik" native: "Тоҷикӣ" direction: ltr - libretranslate: false th: name: "Thai" native: "ไทย" direction: ltr - libretranslate: true ti: name: "Tigrinya" native: "ትግርኛ" direction: ltr - libretranslate: false tk: name: "Turkmen" native: "Türkmen dili" direction: ltr - libretranslate: false tl: name: "Tagalog" native: "Filipino" direction: ltr - libretranslate: true tn: name: "Tswana" native: "Setswana" direction: ltr - libretranslate: false to: name: "Tongan" native: "Lea fakatonga" direction: ltr - libretranslate: false tr: name: "Turkish" native: "Türkçe" direction: ltr - libretranslate: true ts: name: "Tsonga" native: "Xitsonga" direction: ltr - libretranslate: false tt: name: "Tatar" native: "Татар" direction: ltr - libretranslate: false tw: name: "Twi" native: "Twi" direction: ltr - libretranslate: false ty: name: "Tahitian" native: "Reo Tahiti" direction: ltr - libretranslate: false ug: name: "Uyghur" native: "ئۇيغۇرچە" direction: rtl - libretranslate: false uk: name: "Ukrainian" native: "Українська" direction: ltr - libretranslate: true ur: name: "Urdu" native: "اردو" direction: rtl - libretranslate: true uz: name: "Uzbek" native: "O‘zbek" direction: ltr - libretranslate: false ve: name: "Venda" native: "Tshivenḓa" direction: ltr - libretranslate: false vi: name: "Vietnamese" native: "Tiếng Việt" direction: ltr - libretranslate: true vo: name: "Volapük" native: "Volapük" direction: ltr - libretranslate: false wa: name: "Walloon" native: "Walon" direction: ltr - libretranslate: false wo: name: "Wolof" native: "Wolof" direction: ltr - libretranslate: false xh: name: "Xhosa" native: "IsiXhosa" direction: ltr - libretranslate: false yi: name: "Yiddish" native: "ייִדיש" direction: rtl - libretranslate: false yo: name: "Yoruba" native: "Èdè Yorùbá" direction: ltr - libretranslate: false za: name: "Zhuang" native: "Vahcuengh" direction: ltr - libretranslate: false zh: name: "Chinese" native: "中文" direction: ltr - libretranslate: true zu: name: "Zulu" native: "IsiZulu" direction: ltr - libretranslate: false diff --git a/roles/svc-ai-libretranslate-engine/meta/services.yml b/roles/svc-ai-libretranslate-engine/meta/services.yml index ab22a9222f..7f883b8bb3 100644 --- a/roles/svc-ai-libretranslate-engine/meta/services.yml +++ b/roles/svc-ai-libretranslate-engine/meta/services.yml @@ -21,6 +21,54 @@ libretranslate-engine: custom: true min_storage: 402MB load_only: [] + serves: + - ar + - az + - bg + - bn + - ca + - cs + - da + - de + - el + - eo + - es + - et + - eu + - fa + - fi + - fr + - ga + - gl + - he + - hi + - hu + - id + - it + - ja + - ko + - ky + - lt + - lv + - ms + - nb + - nl + - pl + - pt + - ro + - ru + - sk + - sl + - sq + - sv + - sw + - th + - tl + - tr + - uk + - ur + - vi + - zh loading_model: lazy models_dir: "{{ [DIR_CACHE, 'models', 'libretranslate'] | path_join }}" directions: both diff --git a/tests/external/i18n/test_back_translation.py b/tests/external/i18n/test_back_translation.py index a535627732..5dc1fb668f 100644 --- a/tests/external/i18n/test_back_translation.py +++ b/tests/external/i18n/test_back_translation.py @@ -27,8 +27,7 @@ import unittest from tests.utils.services import answers as serves from tests.utils.services import progress as _progress from utils.i18n.catalog import MACHINE_TRANSLATION, catalog_path, read_catalog -from utils.i18n.languages import load_languages, translatable -from utils.i18n.libretranslate import PIVOT_LANGUAGE, SERVICE_KEY +from utils.i18n.libretranslate import PIVOT_LANGUAGE, SERVICE_KEY, served_languages from utils.i18n.untranslatable import untranslatable from utils.inventory.tools import LIBRETRANSLATE_ROLE, lane_url @@ -76,11 +75,10 @@ class TestBackTranslation(unittest.TestCase): client = LibreTranslate(self.url, WORKERS) available = client.targets() - languages = load_languages(PROJECT_ROOT) offenders: list[str] = [] echoed = 0 - for code in translatable(languages, DOMAIN): + for code in served_languages(PROJECT_ROOT): if client.server_code(code) not in available: continue path = catalog_path(PROJECT_ROOT, code, DOMAIN) diff --git a/tests/integration/i18n/__init__.py b/tests/integration/i18n/__init__.py index b3486c2dff..18cb57f0d5 100644 --- a/tests/integration/i18n/__init__.py +++ b/tests/integration/i18n/__init__.py @@ -42,7 +42,7 @@ 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.languages import DOMAINS, domain_languages, load_languages from utils.i18n.spans import prose from utils.i18n.untranslatable import untranslatable @@ -203,7 +203,7 @@ def scan() -> Findings: pending: list[tuple[str, str]] = [] for domain in DOMAINS: - for code in translatable(languages, domain): + for code in domain_languages(languages, domain): path = catalog_path(PROJECT_ROOT, code, domain) if not path.is_file(): continue diff --git a/tests/integration/i18n/test_catalogs_complete_on_gpu.py b/tests/integration/i18n/test_catalogs_complete_on_gpu.py index 605d6d2ae1..0a7a2e061b 100644 --- a/tests/integration/i18n/test_catalogs_complete_on_gpu.py +++ b/tests/integration/i18n/test_catalogs_complete_on_gpu.py @@ -4,6 +4,12 @@ Translating the full language set is only affordable where LibreTranslate can use a GPU, so this runs nowhere else. It reads the catalogs on disk, which is what a release ships, not what a translation run reported. +The set is the language table, every entry of it. Narrowing it to one engine's +declared coverage would hide the languages that engine does not render into, +and those are exactly the ones worth watching: the gateway reaches them +through its chat backend, so a gap there means that backend is absent or +failing, not that the language is unreachable. + Parsing a catalog dominates the runtime and there are two questions to ask of each one, so a worker parses its catalog once, answers both, and sends back two counts instead of the catalog. @@ -19,7 +25,7 @@ from typing import ClassVar, NamedTuple from utils import PROJECT_ROOT from utils.i18n.catalog import catalog_path, read_catalog -from utils.i18n.languages import DOMAINS, load_languages, translatable +from utils.i18n.languages import DOMAINS, domain_languages, load_languages from utils.i18n.libretranslate import accelerated from utils.i18n.translate import damaged, pending @@ -44,15 +50,15 @@ def measure(task: tuple[str, str]) -> Counts: @unittest.skipUnless(accelerated(), "no NVIDIA runtime on this host") class TestCatalogsCompleteOnGpu(unittest.TestCase): root: ClassVar[Path] = Path(PROJECT_ROOT) - languages: ClassVar[dict] = load_languages(Path(PROJECT_ROOT)) missing: ClassVar[list[str]] = [] counts: ClassVar[list[Counts]] = [] @classmethod def setUpClass(cls) -> None: + languages = load_languages(cls.root) tasks: list[tuple[str, str]] = [] for domain in DOMAINS: - for code in translatable(cls.languages, domain): + for code in domain_languages(languages, domain): path = catalog_path(cls.root, code, domain) if path.is_file(): tasks.append((f"{domain}/{code}", str(path))) diff --git a/tests/oracle/test_translation_score.py b/tests/oracle/test_translation_score.py new file mode 100644 index 0000000000..3236836d0f --- /dev/null +++ b/tests/oracle/test_translation_score.py @@ -0,0 +1,206 @@ +"""Score every sampled translation against its source on a named scale. + +``test_system_one.py`` asks one yes-or-no question about one language and +reads the answer as an ordering against two controls, because a bare ``noul`` +probability carries this deployment's calibration and a fixed threshold on it +would encode that calibration into the suite. + +A ``score`` question does not have that problem: the levels are written out, +the judge answers with an index over them, and "below the middle level" means +what the middle level says it means rather than what this deployment's +probabilities happen to look like. That is what lets this check cover every +language instead of one, and fail on a named level instead of on a spread. + +The judge is a chat model reached through the model gateway, not ``laya``. +Measured against the fixture below, ``laya``'s ``english`` checkpoint +separates a faithful rendering from an unrelated text in 17 of 47 languages +and its ``multilingual`` checkpoint in none, answering around 1.5 either way. +Routing a checkpoint per language was the previous answer and it is gone: +``meta/languages.yml`` carries identity only, and one judge covers every +language the catalogs hold. + +The control is a known-answer fixture, not two catalog entries. The engine +renders one fixed English sentence and one unrelated English sentence into +the target language, and the language is judged only when the rendering +scores at or above the middle level while the unrelated text scores below it. +Both legs are required: a catalog-derived mismatch is one-sided, so a judge +answering at the bottom of the scale for everything passes it and then +reports every sample as an offender, and in a language the judge cannot read +at all the two entries pass it on the technical tokens they share. A language +whose control does not separate is reported as unjudged rather than as an +offender, which is what ``tests/oracle/__init__.py`` means by declaring a run +inconclusive instead of letting it return green. + +Context is thin on purpose for now: an entry's catalog and domain identify it, +but the file it was extracted from does not reach here, because +``utils/i18n/catalog.py`` builds the template without locations and the +catalogs therefore carry none. Naming the source file in the question would +mean changing extraction and rewriting every catalog, which is its own change. +""" + +from __future__ import annotations + +import unittest + +from tests.utils.services import answers as serves +from tests.utils.services import progress as _progress +from utils.cache.yaml import load_yaml +from utils.i18n.catalog import MACHINE_TRANSLATION, catalog_path, read_catalog +from utils.i18n.judge import MIDDLE, ChatJudge +from utils.i18n.languages import DOMAINS, domain_languages, load_languages +from utils.i18n.libretranslate import SERVICE_KEY +from utils.i18n.spans import prose +from utils.inventory.tools import LIBRETRANSLATE_ROLE, lane_url +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT, SUITE + +JUDGE_ROLE = "svc-ai-litellm" +JUDGE_SERVICE_KEY = "litellm" +JUDGE_SERVICES_FILE = PROJECT_ROOT / "roles" / JUDGE_ROLE / ROLE_FILE_META_SERVICES +SAMPLES_PER_LANGUAGE = 4 +MIN_SOURCE_CHARS = 40 +ENGINE_WORKERS = 1 +FIXTURE_SOURCE = ( + "The nightly backup keeps seven daily copies and runs at two o'clock in " + "the morning." +) +FIXTURE_UNRELATED = ( + "The small bakery near the station closes early on Saturday afternoon." +) + + +def _model() -> str: + """Return the alias the model gateway resolves the judge's prompt with.""" + return load_yaml(JUDGE_SERVICES_FILE)[JUDGE_SERVICE_KEY]["router"]["alias"] + + +def _pairs(code: str, domain: str) -> list[tuple[str, str]]: + """Return machine-translated (source, translation) pairs worth judging. + + Args: + code: ISO 639-1 code of the catalog. + domain: catalog domain. + """ + path = catalog_path(PROJECT_ROOT, code, domain) + if not path.is_file(): + return [] + return [ + (str(m.id), str(m.string)) + for m in read_catalog(path) + if m.id + and m.string + and MACHINE_TRANSLATION in (m.user_comments or []) + and len(prose(str(m.id)).strip()) >= MIN_SOURCE_CHARS + ] + + +class TestTranslationScore(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.base = lane_url(PROJECT_ROOT, JUDGE_ROLE, JUDGE_SERVICE_KEY) + cls.engine = lane_url(PROJECT_ROOT, LIBRETRANSLATE_ROLE, SERVICE_KEY) + for url in (f"{cls.base}/health", f"{cls.engine}/languages"): + if not serves(url): + raise unittest.SkipTest( + f"nothing answers on {url}. `make test-oracle` brings the " + "tools lane up before the suite runs, and this check cannot " + f"deploy it from inside the stack's container. The lane's " + f"default roles are the translation engine and System One " + f"(utils/inventory/tools.py, default_roles), so {JUDGE_ROLE} " + "and the model server behind it are not among them and this " + "check stays skipped until they are." + ) + _progress(SUITE, f"the judge answers on {cls.base}") + + def _unreadable(self, client, judge, available: set[str], code: str) -> str: + """Return why the judge cannot be trusted on this language. + + Args: + client: the engine the fixture is rendered with. + judge: the model asked to place a pair on the levels. + available: the target codes that engine serves. + code: ISO 639-1 code of the language to judge. + + Returns: + Empty when the judge separates the fixture from an unrelated text, + so its verdicts on this language's samples carry information. + """ + if client.server_code(code) not in available: + return "the engine does not render the fixture into this language" + values = client.translate([FIXTURE_SOURCE, FIXTURE_UNRELATED], code).values + if not all(isinstance(value, str) and value for value in values): + return f"the engine rendered no usable fixture: {values!r}" + faithful, unrelated = values + kept = judge.score(FIXTURE_SOURCE, faithful) + other = judge.score(FIXTURE_SOURCE, unrelated) + if kept < MIDDLE: + return ( + f"a faithful rendering of the fixture scored {kept}, below the " + f"middle level {MIDDLE}" + ) + if other >= MIDDLE: + return ( + f"an unrelated text scored {other}, at or above the middle " + f"level {MIDDLE}" + ) + return "" + + def test_every_sampled_translation_carries_its_source(self): + from utils.i18n.client import LibreTranslate + + client = LibreTranslate(self.engine, ENGINE_WORKERS) + available = client.targets() + judge = ChatJudge(self.base, _model()) + languages = load_languages(PROJECT_ROOT) + verdicts: dict[str, str] = {} + offenders: list[str] = [] + judged = 0 + + for domain in DOMAINS: + for code in domain_languages(languages, domain): + pairs = _pairs(code, domain) + if not pairs: + continue + where = f"{domain}/{code}" + if code not in verdicts: + verdicts[code] = self._unreadable(client, judge, available, code) + _progress( + SUITE, + f"{code}: {verdicts[code] or 'the judge separates the fixture'}", + ) + if verdicts[code]: + continue + + stride = max(1, len(pairs) // SAMPLES_PER_LANGUAGE) + sample = pairs[::stride][:SAMPLES_PER_LANGUAGE] + _progress(SUITE, f"scoring {len(sample)} samples of {where}") + for source, translation in sample: + judged += 1 + level = judge.score(source, translation) + if level < MIDDLE: + offenders.append( + f"{where}: {level} below the middle level {MIDDLE}: " + f"{source[:60]!r} -> {translation[:60]!r}" + ) + + unjudged = {code: why for code, why in sorted(verdicts.items()) if why} + if not judged: + self.fail( + f"no sample reached a verdict: the judge read none of the " + f"{len(verdicts)} language(s) the catalogs hold machine " + "translations for, so a green result would mean nothing:\n" + + "\n".join(f" - {code}: {why}" for code, why in unjudged.items()) + ) + if offenders: + self.fail( + f"{len(offenders)} of {judged} sampled translations state " + "something other than their source:\n" + + "\n".join(f" - {o}" for o in offenders) + ) + _progress( + SUITE, + f"{judged} sampled translations carry their source in " + f"{len(verdicts) - len(unjudged)} language(s) the judge reads, " + f"{len(unjudged)} it does not", + ) diff --git a/tests/unit/python/cli/build/i18n/test_main.py b/tests/unit/python/cli/build/i18n/test_main.py index b2650b6ea7..8c73c7494f 100644 --- a/tests/unit/python/cli/build/i18n/test_main.py +++ b/tests/unit/python/cli/build/i18n/test_main.py @@ -2,6 +2,8 @@ from __future__ import annotations import contextlib import importlib +import io +import json import unittest import unittest.mock as mock from pathlib import Path @@ -9,14 +11,19 @@ from tempfile import TemporaryDirectory from utils.i18n.catalog import catalog_path, new_catalog, write_catalog from utils.i18n.languages import LANGUAGES_FILE -from utils.i18n.libretranslate import Outcome +from utils.i18n.libretranslate import SERVICE_KEY, SERVICES_FILE, Outcome cli = importlib.import_module("cli.build.i18n.__main__") LANGUAGES = """\ -en: {name: English, native: English, direction: ltr, libretranslate: true} -de: {name: German, native: Deutsch, direction: ltr, libretranslate: true} -fr: {name: French, native: Français, direction: ltr, libretranslate: true} +en: {name: English, native: English, direction: ltr} +de: {name: German, native: Deutsch, direction: ltr} +fr: {name: French, native: Français, direction: ltr} +zu: {name: Zulu, native: isiZulu, direction: ltr} +""" +SERVES = f"""\ +{SERVICE_KEY}: + serves: [de, fr] """ @@ -28,16 +35,46 @@ def _catalog(root: Path, code: str, translation: str) -> None: write_catalog(path, catalog) +def _checkout(case: unittest.TestCase) -> Path: + """Return a checkout holding the language table and the engine's own coverage. + + Args: + case: the test whose lifetime the temporary directory follows. + """ + tmp = TemporaryDirectory() + case.addCleanup(tmp.cleanup) + root = Path(tmp.name) + (root / LANGUAGES_FILE).parent.mkdir() + (root / LANGUAGES_FILE).write_text(LANGUAGES, encoding="utf-8") + (root / SERVICES_FILE).parent.mkdir(parents=True) + (root / SERVICES_FILE).write_text(SERVES, encoding="utf-8") + return root + + +class TestLanguages(unittest.TestCase): + def setUp(self) -> None: + self.root = _checkout(self) + + def test_the_matrix_gets_every_language_the_table_names(self) -> None: + """Not the one engine's coverage: the gateway falls through to a chat + backend that declares no catalogue, so a language outside + ``serves`` is translated rather than skipped.""" + with ( + mock.patch.object(cli, "PROJECT_ROOT", self.root), + mock.patch("sys.stdout", new_callable=io.StringIO) as out, + ): + status = cli.languages(["core"]) + + self.assertEqual(status, 0) + self.assertEqual(json.loads(out.getvalue()), ["de", "fr", "zu"]) + + class TestTranslate(unittest.TestCase): def setUp(self) -> None: - self._tmp = TemporaryDirectory() - self.addCleanup(self._tmp.cleanup) - self.root = Path(self._tmp.name) - (self.root / LANGUAGES_FILE).parent.mkdir() - (self.root / LANGUAGES_FILE).write_text(LANGUAGES, encoding="utf-8") + self.root = _checkout(self) _catalog(self.root, "de", "Hallo") - def _run(self) -> tuple[int, mock.Mock, mock.Mock]: + def _run(self, requested: list[str] | None = None) -> tuple[int, mock.Mock, mock.Mock]: started = mock.Mock(return_value=contextlib.nullcontext("http://lt")) client = mock.Mock() client.return_value.translate.side_effect = lambda texts, code: Outcome( @@ -48,7 +85,22 @@ class TestTranslate(unittest.TestCase): mock.patch.object(cli, "server", started), mock.patch.object(cli, "LibreTranslate", client), ): - return cli.translate(["core"], []), started, client + return cli.translate(["core"], requested or []), started, client + + def test_a_code_the_table_does_not_name_is_refused_before_any_deploy(self) -> None: + status, started, _client = self._run(["xx"]) + + self.assertEqual(status, 2) + started.assert_not_called() + + def test_a_language_whose_catalog_is_not_extracted_yet_starts_nothing(self) -> None: + """``zu`` is in the table and has no catalog on disk. Reading one would + raise, and refusing the language would drop it from the set the + repository promises to translate; it simply has nothing pending.""" + status, started, _client = self._run() + + self.assertEqual(status, 0) + started.assert_not_called() def test_only_languages_with_pending_entries_are_awaited(self) -> None: _catalog(self.root, "fr", "") diff --git a/tests/unit/python/utils/i18n/test_judge.py b/tests/unit/python/utils/i18n/test_judge.py index c7be3e7819..07a81eccde 100644 --- a/tests/unit/python/utils/i18n/test_judge.py +++ b/tests/unit/python/utils/i18n/test_judge.py @@ -7,7 +7,7 @@ import json import unittest import unittest.mock -from utils.i18n import judge as JUDGE +from utils.i18n import judge from utils.i18n.judge import LEVELS, MIDDLE, ChatJudge, parse_level, question @@ -61,7 +61,7 @@ class ScoreTestCase(unittest.TestCase): self.judge = ChatJudge("http://gateway:4000/", "chat", api_key="k") def _call(self, content): - with unittest.mock.patch.object(JUDGE.urllib.request, "urlopen") as urlopen: + with unittest.mock.patch.object(judge.urllib.request, "urlopen") as urlopen: urlopen.return_value.__enter__.return_value = _answer(content) result = self.judge.score("source", "translation") self.request = urlopen.call_args[0][0] diff --git a/tests/unit/python/utils/i18n/test_languages.py b/tests/unit/python/utils/i18n/test_languages.py new file mode 100644 index 0000000000..5305db766b --- /dev/null +++ b/tests/unit/python/utils/i18n/test_languages.py @@ -0,0 +1,87 @@ +import unittest + +from utils import PROJECT_ROOT +from utils.i18n.languages import ( + DOMAINS, + SOURCE_LANGUAGE, + domain_languages, + load_languages, +) +from utils.i18n.libretranslate import PIVOT_LANGUAGE, baked_languages, served_languages + +FIELDS = {"name", "native", "direction"} +DIRECTIONS = {"ltr", "rtl"} + + +class TestDomainLanguages(unittest.TestCase): + def test_a_domain_the_file_does_not_name_is_refused(self) -> None: + with self.assertRaises(ValueError): + domain_languages({"de": {}}, "handbook") + + def test_the_source_language_carries_no_catalog_of_its_own(self) -> None: + self.assertNotIn( + SOURCE_LANGUAGE, domain_languages({"de": {}, SOURCE_LANGUAGE: {}}, "core") + ) + + +class TestTheLanguageTable(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.languages = load_languages(PROJECT_ROOT) + + def test_every_entry_carries_the_three_identity_fields(self) -> None: + self.assertEqual( + sorted( + code for code, entry in self.languages.items() if set(entry) != FIELDS + ), + [], + ) + + def test_no_entry_names_an_engine_or_a_scorer(self) -> None: + """The gateway learns the engine per language and the oracle asks one + judge for all of them, so a route written here would be a second + opinion that goes stale as soon as either learns something.""" + self.assertEqual( + sorted( + code + for code, entry in self.languages.items() + if {"engine", "oracle", "libretranslate"} & set(entry) + ), + [], + ) + + def test_every_direction_is_one_of_the_two_writing_directions(self) -> None: + self.assertEqual( + sorted( + code + for code, entry in self.languages.items() + if entry["direction"] not in DIRECTIONS + ), + [], + ) + + def test_every_language_but_the_source_carries_a_catalog(self) -> None: + expected = sorted(code for code in self.languages if code != SOURCE_LANGUAGE) + for domain in DOMAINS: + with self.subTest(domain=domain): + self.assertEqual(domain_languages(self.languages, domain), expected) + + +class TestTheEnginesOwnCoverage(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.languages = load_languages(PROJECT_ROOT) + cls.served = served_languages(PROJECT_ROOT) + + def test_every_served_code_is_a_language_the_repository_names(self) -> None: + self.assertEqual(sorted(set(self.served) - set(self.languages)), []) + + def test_the_lane_bakes_the_pivot_beside_every_served_model(self) -> None: + self.assertEqual( + baked_languages(PROJECT_ROOT), + sorted({PIVOT_LANGUAGE, *self.served}), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/i18n/languages.py b/utils/i18n/languages.py index 16f9b9da3b..a4737647ce 100644 --- a/utils/i18n/languages.py +++ b/utils/i18n/languages.py @@ -1,4 +1,19 @@ -"""The language list of ``meta/languages.yml``.""" +"""The language list of ``meta/languages.yml``. + +The file is the one place that names the languages this repository supports, +and it carries nothing but their identity: name, endonym and writing +direction. Every language it names gets a catalog in every domain. + +Which engine renders into a language is deliberately not written here. The +translation gateway offers each backend that serves the pair, falls through to +the next one when an engine refuses or mangles the answer, drops an engine +whose failures pile up, and settles a language on the engine that wins its +comparisons. A static table beside that would be a second opinion that goes +stale the moment the router learns something. What a single engine can do is +declared with that engine instead: ``services.libretranslate-engine.serves`` +of ``roles/svc-ai-libretranslate-engine`` states the codes its models cover, +because the lane prefetches those models before any engine can be asked. +""" from __future__ import annotations @@ -25,27 +40,8 @@ def domain_languages(languages: dict[str, dict], domain: str) -> list[str]: Args: languages: the mapping returned by ``load_languages``. - domain: ``core`` for every language but the source language, ``docs`` - for the languages LibreTranslate supports. + domain: a name of :data:`DOMAINS`. """ - if domain == "core": - return sorted(code for code in languages if code != SOURCE_LANGUAGE) - if domain == "docs": - return sorted( - code for code, entry in languages.items() if entry["libretranslate"] - ) - raise ValueError(f"unknown domain: {domain}") - - -def translatable(languages: dict[str, dict], domain: str) -> list[str]: - """Return the codes of ``domain`` LibreTranslate can machine-translate. - - Args: - languages: the mapping returned by ``load_languages``. - domain: gettext domain. - """ - return [ - code - for code in domain_languages(languages, domain) - if languages[code]["libretranslate"] - ] + if domain not in DOMAINS: + raise ValueError(f"unknown domain: {domain}") + return sorted(code for code in languages if code != SOURCE_LANGUAGE) diff --git a/utils/i18n/libretranslate.py b/utils/i18n/libretranslate.py index 0442017b08..78a000d974 100644 --- a/utils/i18n/libretranslate.py +++ b/utils/i18n/libretranslate.py @@ -196,19 +196,29 @@ def await_runner(name: str, env: dict[str, str]) -> None: raise RuntimeError(f"The tools runner {name} did not reach the running state.") +def served_languages(root: Path) -> list[str]: + """Return the codes this engine's models cover. + + Args: + root: repository root. + + Returns: + ``services..serves`` of the engine's own role. The set is + declared there rather than read back from ``/languages`` because both + callers run before any engine answers: one pins the models the image + prefetches, the other is the readiness probe itself. + """ + service = load_yaml(root / SERVICES_FILE)[SERVICE_KEY] + return sorted(service["serves"]) + + def baked_languages(root: Path) -> list[str]: """Return every code the lane's image prefetches models for. Args: root: repository root. """ - from utils.i18n.languages import DOMAINS, load_languages, translatable - - languages = load_languages(root) - codes = {PIVOT_LANGUAGE} - for domain in DOMAINS: - codes.update(translatable(languages, domain)) - return sorted(codes) + return sorted({PIVOT_LANGUAGE, *served_languages(root)}) def _vars_file(root: Path) -> Path: