"""Preprocess, segment, and score Kabyle multilingual translation inputs and outputs.""" from __future__ import annotations import re import unicodedata from collections import Counter from collections.abc import Callable, Sequence from dataclasses import dataclass from typing import Final SUPPORTED_LANGUAGES: Final[frozenset[str]] = frozenset( {"kab_Latn", "eng_Latn", "fra_Latn", "arb_Arab"} ) LANGUAGE_ALIASES: Final[dict[str, str]] = { "kab": "kab_Latn", "kab-latn": "kab_Latn", "kab_latn": "kab_Latn", "en": "eng_Latn", "eng": "eng_Latn", "en-latn": "eng_Latn", "eng-latn": "eng_Latn", "eng_latn": "eng_Latn", "fr": "fra_Latn", "fra": "fra_Latn", "fre": "fra_Latn", "fr-latn": "fra_Latn", "fra-latn": "fra_Latn", "fra_latn": "fra_Latn", "ar": "arb_Arab", "ara": "arb_Arab", "arb": "arb_Arab", "ar-arab": "arb_Arab", "arb-arab": "arb_Arab", "arb_arab": "arb_Arab", } HOMOGLYPHS: Final[dict[str, str]] = { "ε": "ɛ", "Σ": "Ɛ", "γ": "ɣ", "Γ": "Ɣ", "Ԑ": "Ɛ", "ԑ": "ɛ", "ğ": "ǧ", "ĝ": "ǧ", "ģ": "ǧ", "ġ": "ǧ", "ǵ": "ǧ", "Ğ": "Ǧ", "ć": "č", "ĉ": "č", "Ć": "Č", "ť": "ṭ", "ț": "ṭ", "ṫ": "ṭ", "Ț": "Ṭ", "ď": "ḍ", "đ": "ḍ", "ð": "ḍ", "ḑ": "ḍ", "š": "ṣ", "ś": "ṣ", "ş": "ṣ", "ș": "ṣ", "ṡ": "ṣ", "ž": "ẓ", "ź": "ẓ", "ż": "ẓ", "ƶ": "ẓ", "ř": "ṛ", "ŕ": "ṛ", "ṙ": "ṛ", "ŗ": "ṛ", "ı": "i", "İ": "I", } WHITESPACE: Final[dict[str, str]] = { "\xa0": " ", "\u202f": " ", "\u2007": " ", "\u2009": " ", "\u2002": " ", "\u2003": " ", "\u200b": "", "\u200c": "", "\u200d": "", "\ufeff": "", } _HOMOGLYPH_TABLE: Final = str.maketrans(HOMOGLYPHS) _WHITESPACE_TABLE: Final = str.maketrans(WHITESPACE) # Every key tokenizes to under facebook/nllb-200-*; every ASCII target is in-vocabulary. TYPOGRAPHY_FOLD: Final[dict[str, str]] = { "“": '"', "”": '"', "„": '"', "«": '"', "»": '"', "❝": '"', "❞": '"', "‘": "'", "’": "'", "‚": "'", "—": "-", "–": "-", "⁃": "-", } _TYPOGRAPHY_TABLE: Final = str.maketrans(TYPOGRAPHY_FOLD) EMPHASIS: Final = re.compile(r"(??@[\\]^_`{|}~") class SegmentError(ValueError): """Raised when document segmentation or reassembly invariants are violated.""" @dataclass(frozen=True, slots=True) class Segment: """One translatable text unit paired with its surrounding source whitespace.""" text: str prefix: str = "" suffix: str = "" def restore(self, translation: str) -> str: return f"{self.prefix}{translation}{self.suffix}" def resolve_language(code: str) -> str: """Map shorthand ISO codes or BCP-47 tags to canonical NLLB language identifiers.""" key = code.strip().lower() resolved = LANGUAGE_ALIASES.get(key) if resolved is None: supported = ", ".join(sorted(SUPPORTED_LANGUAGES)) message = f"Unsupported language {code!r}; expected one of {supported}" raise ValueError(message) return resolved def validate_direction( src_lang: str, tgt_lang: str, *, allow_bridge_pivot: bool = False, ) -> tuple[str, str]: """Validate source and target language identifiers against trained Kabyle directions.""" source = resolve_language(src_lang) target = resolve_language(tgt_lang) if source == target: message = f"Source and target languages must differ, got {source!r}" raise ValueError(message) if not allow_bridge_pivot and (source == "kab_Latn") == (target == "kab_Latn"): message = ( f"Direction {source} -> {target} does not involve kab_Latn; pass " "allow_bridge_pivot=True to pivot through kab_Latn" ) raise ValueError(message) return source, target def normalise_kab(text: str) -> str: """Apply lossless NFC, homoglyph, and invisible-whitespace normalisation for Kabyle.""" composed = unicodedata.normalize("NFC", text) return composed.translate(_HOMOGLYPH_TABLE).translate(_WHITESPACE_TABLE) def fold_typography(text: str) -> str: """Replace out-of-vocabulary curly quotes and dashes with ASCII equivalents.""" return text.translate(_TYPOGRAPHY_TABLE) def strip_emphasis(text: str) -> str: """Remove Project Gutenberg underscore emphasis markers.""" return EMPHASIS.sub(r"\1", text) def prepare_source(text: str) -> str: """Fold out-of-vocabulary typography and remove Gutenberg emphasis markers.""" return fold_typography(strip_emphasis(text)) def is_translatable(text: str) -> bool: """Return True when the text contains at least one alphabetic character.""" return LETTER.search(text) is not None def is_shouted(text: str) -> bool: """Return True when multi-word text is set entirely in uppercase letters.""" words = SHOUTED_WORD.findall(text) return len(words) >= MIN_SHOUTED_WORDS and all(word.isupper() for word in words) def _fold_shouted_word(word: str) -> str: stripped = word.strip("\"'()[]“”‘’«»") letters = "".join(ch for ch in word if ch.isalpha()) if not letters or ROMAN_NUMERAL.match(letters) or DOTTED_INITIALISM.match(stripped): return word for position, ch in enumerate(word): if ch.isalpha(): return word[:position] + ch.upper() + word[position + 1 :].lower() return word def soften_shouted(text: str) -> str: """Fold uppercase headings to title case while preserving Roman numerals and initialisms.""" if not is_shouted(text): return text return re.sub(r"\S+", lambda match: _fold_shouted_word(match.group()), text) def restore_shouted(source: str, translation: str) -> str: """Restore uppercase typography when the original source segment was shouted.""" return translation.upper() if is_shouted(source) else translation def _ends_sentence(left: str) -> bool: stripped = left.rstrip(")]\"'»”’") if not stripped.endswith("."): return True if INITIAL.search(stripped): return False word = re.split(r"[\s(\[\"'«“‘]", stripped[:-1])[-1] return word.lower() not in ABBREVIATIONS def _wrap_width(text: str) -> int | None: lengths = sorted(len(line.rstrip()) for line in text.splitlines() if line.strip()) if len(lengths) < MIN_WRAPPED_LINES: return None width = lengths[int(WRAP_PERCENTILE * (len(lengths) - 1))] if not NARROWEST_WRAP <= width <= WIDEST_WRAP: return None filled = sum(1 for length in lengths if length >= width - WRAP_MARGIN) return width if filled * 2 >= len(lengths) else None def unwrap(text: str) -> str: """Join hard-wrapped plain-text lines while keeping structural line breaks intact.""" width = _wrap_width(text) if width is None: return text lines = text.splitlines(keepends=True) pieces: list[str] = [] continuing = False for index, line in enumerate(lines): body = line.rstrip() following = lines[index + 1].split() if index + 1 < len(lines) else [] joined = bool(body) and bool(following) and len(body) + 1 + len(following[0]) > width content = body.lstrip() if continuing else body pieces.append(content + (" " if joined else line[len(body) :])) continuing = joined return "".join(pieces) def _split_keeping_space(text: str, pattern: re.Pattern[str]) -> list[str]: pieces: list[str] = [] start = 0 for match in pattern.finditer(text): cut = match.end() if pattern is SENTENCE_END and not _ends_sentence(text[start:cut]): continue run = re.match(r"\s*", text[cut:]) end = cut + (run.end() if run else 0) pieces.append(text[start:end]) start = end if start < len(text): pieces.append(text[start:]) return [piece for piece in pieces if piece] def _pack(pieces: Sequence[str], count: Callable[[str], int], limit: int) -> list[str]: packed: list[str] = [] current = "" for piece in pieces: candidate = current + piece if current and count(candidate) > limit: packed.append(current) current = piece else: current = candidate if current: packed.append(current) return packed def _by_words(text: str, count: Callable[[str], int], budget: int) -> list[str]: return _pack(re.findall(r"\S+\s*", text), count, budget) def _fit(text: str, count: Callable[[str], int], budget: int, target: int) -> list[str]: if count(text) <= target: return [text] grouped = [text] for pattern in CLAUSE_ENDS: clauses = _split_keeping_space(text, pattern) if len(clauses) > 1: grouped = _pack(clauses, count, target) if all(count(group) <= target for group in grouped): break return [ piece for group in grouped for piece in ([group] if count(group) <= budget else _by_words(group, count, budget)) ] def plan_segments( text: str, count: Callable[[str], int], budget: int = MAX_SOURCE_TOKENS, target: int = SOFT_TARGET_TOKENS, ) -> list[Segment]: """Segment a document into sentence or clause units while recording exact whitespace.""" if budget < 1: message = f"budget must be positive, got {budget}" raise SegmentError(message) target = min(target, budget) if not text.strip(): return [] document = unwrap(text) lead = re.match(r"\s*", document) prefix = lead.group() if lead else "" body = document[len(prefix) :] segments: list[Segment] = [] for block in _split_keeping_space(body, LINE_END): for sentence in _split_keeping_space(block, SENTENCE_END): for piece in _fit(sentence, count, budget, target): stripped = piece.rstrip() segments.append(Segment(text=stripped, suffix=piece[len(stripped) :])) if not segments: return [] first = segments[0] segments[0] = Segment(text=first.text, prefix=prefix, suffix=first.suffix) return segments def assemble_segments(segments: Sequence[Segment], translations: Sequence[str]) -> str: """Reassemble translated segments into the original document whitespace layout.""" if len(segments) != len(translations): message = f"{len(translations)} translations for {len(segments)} segments" raise SegmentError(message) return "".join( segment.restore(translation) for segment, translation in zip(segments, translations, strict=True) ) def _chrf_words(text: str) -> list[str]: tokens: list[str] = [] for word in text.split(): if len(word) == 1: tokens.append(word) elif word[-1] in _CHRF_PUNCTS: tokens.extend((word[:-1], word[-1])) elif word[0] in _CHRF_PUNCTS: tokens.extend((word[0], word[1:])) else: tokens.append(word) return tokens def _extract_chrf_ngrams( text: str, char_order: int = 6, word_order: int = 2, ) -> list[Counter[str]]: compact = "".join(text.split()) counters: list[Counter[str]] = [ Counter(compact[i : i + n] for i in range(len(compact) - n + 1)) for n in range(1, char_order + 1) ] if word_order > 0: words = _chrf_words(text) counters.extend( Counter(" ".join(words[i : i + n]) for i in range(len(words) - n + 1)) for n in range(1, word_order + 1) ) return counters def _chrf_from_counters( hyp_counters: Sequence[Counter[str]], ref_counters: Sequence[Counter[str]], beta: float = 2.0, ) -> float: eps = 1e-16 factor = beta**2 avg_prec = 0.0 avg_rec = 0.0 effective_order = 0 for hyp, ref in zip(hyp_counters, ref_counters, strict=True): n_ref = sum(ref.values()) n_hyp = sum(hyp.values()) if n_ref > 0 else 0 if n_hyp > 0 and n_ref > 0: n_match = sum(min(count, ref[gram]) for gram, count in hyp.items() if gram in ref) prec = n_match / n_hyp rec = n_match / n_ref avg_prec += prec avg_rec += rec effective_order += 1 else: _ = eps if effective_order == 0: return 0.0 avg_prec /= effective_order avg_rec /= effective_order if avg_prec + avg_rec == 0.0: return 0.0 return 100.0 * (1.0 + factor) * avg_prec * avg_rec / (factor * avg_prec + avg_rec) def chrf_pp_score( hypothesis: str, reference: str, *, char_order: int = 6, word_order: int = 2, beta: float = 2.0, ) -> float: """Compute sentence-level chrF++ matching sacrebleu CHRF(word_order=2) effective-order mode.""" hyp_ngrams = _extract_chrf_ngrams(hypothesis, char_order=char_order, word_order=word_order) ref_ngrams = _extract_chrf_ngrams(reference, char_order=char_order, word_order=word_order) return _chrf_from_counters(hyp_ngrams, ref_ngrams, beta=beta) def mbr_utilities( candidates: Sequence[str], *, char_order: int = 6, word_order: int = 2, beta: float = 2.0, ) -> list[float]: """Compute pairwise expected chrF++ utility in [0, 1] for Minimum Bayes Risk selection.""" count = len(candidates) if count == 0: return [] if count == 1: return [1.0] extracted = [ _extract_chrf_ngrams(candidate, char_order=char_order, word_order=word_order) for candidate in candidates ] utilities: list[float] = [] for i in range(count): total = 0.0 for j in range(count): if i == j: continue if candidates[i] == candidates[j]: total += 1.0 else: total += _chrf_from_counters(extracted[i], extracted[j], beta=beta) / 100.0 utilities.append(total / (count - 1)) return utilities def has_loops(text: str) -> bool: """Return True when a short phrase or subword fragment repeats degenerately.""" words = text.split() for size in range(1, LOOP_WORDS + 1): repeats = SHORT_PHRASE_REPEATS if size <= SHORT_PHRASE_WORDS else LONG_PHRASE_REPEATS for start in range(len(words) - size * repeats + 1): phrase = words[start : start + size] if all( words[start + size * n : start + size * (n + 1)] == phrase for n in range(1, repeats) ): return True return bool(SUBWORD_STUTTER.search(text)) def is_empty_output(source: str, hypothesis: str) -> bool: """Return True when an alphabetic source produced an output with no letters.""" return LETTER.search(source) is not None and LETTER.search(hypothesis) is None def has_malformed_length(source: str, hypothesis: str) -> bool: """Return True when output word count falls outside gross translation length bounds.""" source_words = len(source.split()) if source_words < RATIO_MIN_WORDS: return False ratio = len(hypothesis.split()) / source_words return not MIN_LENGTH_RATIO <= ratio <= MAX_LENGTH_RATIO def is_copied_source(source: str, hypothesis: str) -> bool: """Return True when the hypothesis largely copies the source words untranslated.""" words = [word.casefold() for word in WORD_TOKENS.findall(hypothesis)] if len(words) < RATIO_MIN_WORDS: return False present = {word.casefold() for word in WORD_TOKENS.findall(source)} return sum(1 for word in words if word in present) / len(words) >= COPY_OVERLAP def _has_script_mismatch(hypothesis: str, tgt_lang: str) -> bool: if not is_translatable(hypothesis): return False arabic_count = len(ARABIC_LETTER.findall(hypothesis)) latin_count = len(LATIN_LETTER.findall(hypothesis)) if tgt_lang == "arb_Arab": return arabic_count == 0 and latin_count >= RATIO_MIN_WORDS return arabic_count >= MIN_OFF_SCRIPT_LETTERS and arabic_count > latin_count def _has_language_drift(source: str, hypothesis: str, tgt_lang: str) -> bool: if tgt_lang != "kab_Latn": return False words = [word.casefold() for word in WORD_TOKENS.findall(hypothesis)] if len(words) < MIN_DRIFT_WORDS: return False source_words = {word.casefold() for word in WORD_TOKENS.findall(source)} unquoted_foreign = [ word for word in words if word in FOREIGN_FUNCTION_WORDS and word not in source_words ] return len(unquoted_foreign) / len(words) >= DRIFT_WORD_RATIO def detect_failure( source: str, hypothesis: str, *, tgt_lang: str | None = None, ) -> tuple[str, ...]: """Return failure reason codes for a candidate translation, or an empty tuple if valid.""" reasons: list[str] = [] if is_empty_output(source, hypothesis): reasons.append("empty") if has_loops(hypothesis): reasons.append("loop") if has_malformed_length(source, hypothesis): reasons.append("malformed_length") if is_copied_source(source, hypothesis): reasons.append("copied") if tgt_lang is not None: if _has_script_mismatch(hypothesis, tgt_lang): reasons.append("script_mismatch") if _has_language_drift(source, hypothesis, tgt_lang): reasons.append("language_drift") return tuple(reasons)