"""Convert Kirat Rai legacy ``kiratraifont`` (AKRS) text to Unicode Kirat Rai. The Sikkim Herald Kirat Rai edition is typeset in a legacy TrueType font named ``kiratraifont`` with a WinAnsi (byte) encoding and no ToUnicode CMap. Each glyph is addressed by a single Latin byte; the visible text stream is therefore the raw AKRS byte sequence rather than Unicode. SIL publishes a TECkit mapping (``silnrsi/wsresources`` -> ``scripts/Krai/legacy/kiratraifontnew/mappings/ kiratraifontnew.map``) that maps these legacy bytes to the Kirat Rai Unicode block (U+16D40-U+16D7F, Unicode 16.0). That map is expressed with TECkit ``ByteClass``/``UniClass`` declarations plus a handful of explicit multi-byte ligature rules. A ``[class] > [class]`` rule maps the byte at position *n* of the byte class to the codepoint at position *n* of the paired Unicode class. This module parses that map natively (no ``teckit_compile`` dependency, which is unavailable on this machine) and applies the forward Legacy->Unicode pass. The SIL map fills all 58 Kirat Rai block codepoints (U+16D40..U+16D79) but leaves SEVEN AKRS bytes UNMAPPED -- see ``UNMAPPED_LEGACY_BYTES``. These render genuine, distinct Kirat Rai glyph outlines in the legacy ``kiratraifont``, so they are real script characters, not stray Latin. They could NOT be resolved by glyph-shape identity (the method that decoded the Sunuwar and Lepcha-Herald fonts from scratch): unlike those cases -- where the legacy embedded font WAS the printed ink and a Noto font reproduced it -- the legacy ``kiratraifont`` and the Unicode font Kanchenjunga are *independent typefaces* with substantially divergent letterforms. Method validation made this conclusive: re-identifying the 40 already-mapped single bytes by matching their legacy glyphs to Kanchenjunga's 58 codepoint glyphs scored only 20% top-1 / 30% top-3, and a round-trip of a KNOWN-CORRECT SIL mapping (``udzdle`` -> ``U+16D65 U+16D54 U+16D6B U+16D54 U+16D5E U+16D67``) rendered in Kanchenjunga looks nothing like the printed legacy ink. So the round-trip gate cannot certify ANY Kirat Rai byte against Kanchenjunga, and -- per the no-guessing discipline -- none of the 7 is committed. Resolving them needs the AKRS source keyboard table or a native reader. Evidence + contact sheets: ``outputs/kiratrai-gap-resolution/``. Conversion leaves an unmapped byte as its raw Latin character. Downstream faithful floors (``tools/convert_sikkim_herald_kiratrai.py``, ``tools/build_sikkim_herald_extra.py``) DROP any line containing one of these bytes rather than emit corrupt inline-Latin text. """ from __future__ import annotations import re import unicodedata from dataclasses import dataclass from pathlib import Path from typing import Any from .errors import DataValidationError DEFAULT_KIRATRAI_LEGACY_MAP = Path("data/mappings/kiratrai-legacy/kiratraifontnew.map") # AKRS bytes that SIL's kiratraifontnew.map does NOT cover. Each renders a distinct, # genuine Kirat Rai glyph in the legacy font (verified: unique outline, no exact twin # among the mapped bytes). They are flagged, NOT mapped -- glyph-shape identity against # Kanchenjunga is invalid for this font pair (20% re-identification of known-mapped # bytes; a known-correct mapping does not visually round-trip), so committing any guess # would violate the shape-identity-only / no-round-trip-failure rule. # # Per-byte evidence (frequency over all 7 Sikkim Herald editions; distribution; # best legacy-self shape neighbour -- still ambiguous, NOT a confirmed mapping): # 'f' 0x66 n=3449 vowel-sign profile (medial/final, follows consonants, esp. BA); # glyph is a '3'-with-curl; shape neighbours are the digit family -- contradicts # its vowel-like distribution. UNRESOLVED. # 'R' 0x52 n=278 word-initial/medial consonant, often after VIRAMA; clean 'Ʒ' shape # ~ digit-3 / LETTER JA. UNRESOLVED. # 'F' 0x46 n=229 word-initial (masthead 'FbozDbrab'); hook+vertical. UNRESOLVED. # 'I' 0x49 n=228 almost always 'h I u' (HA _ VOWEL-U); medial consonant. UNRESOLVED. # 'x' 0x78 n=201 word-initial consonant, followed by VOWEL-U/BA; complex (ligature?). # UNRESOLVED. # 'L' 0x4C n=14 word-final only, masthead date separator ('GrfwbvufL 23'); tiny ring; # best legacy-self match VOWEL SIGN U/UE (0.94) but role is a separator, so the # shape match conflicts with usage. UNRESOLVED. # '\\' 0x5C n=2 no glyph in the kiratraifont cmap at all; 2 occurrences. UNRESOLVED. UNMAPPED_LEGACY_BYTES: frozenset[str] = frozenset("fRxFIL\\") _KIRATRAI_CODEPOINT_RE = re.compile(r"[\U00016D40-\U00016D7F]") _BYTE_TOKEN_RE = re.compile(r"0x([0-9A-Fa-f]{2})") _UNI_TOKEN_RE = re.compile(r"U\+([0-9A-Fa-f]{4,6})") _BYTECLASS_RE = re.compile(r"^ByteClass\s*\[([^\]]+)\]\s*=\s*\((.*)\)\s*$") _UNICLASS_RE = re.compile(r"^UniClass\s*\[([^\]]+)\]\s*=\s*\((.*)\)\s*$") _CLASS_RULE_RE = re.compile(r"^\[([^\]]+)\]\s*\s*\[([^\]]+)\]\s*$") def _expand_byte_tokens(body: str) -> tuple[int, ...]: """Expand a TECkit byte-class body into an ordered list of byte values. Supports both explicit ``0xNN`` tokens and ``0xNN .. 0xMM`` ranges. """ values: list[int] = [] tokens = re.split(r"\s+", body.strip()) index = 0 while index < len(tokens): token = tokens[index] if not token: index += 1 continue if index + 2 < len(tokens) and tokens[index + 1] == "..": start = int(token, 16) end = int(tokens[index + 2], 16) if end < start: raise DataValidationError(f"invalid byte range in map: {token}..{tokens[index + 2]}") values.extend(range(start, end + 1)) index += 3 continue values.append(int(token, 16)) index += 1 return tuple(values) def _expand_uni_tokens(body: str) -> tuple[int, ...]: """Expand a TECkit Unicode-class body into an ordered list of codepoints.""" values: list[int] = [] tokens = re.split(r"\s+", body.strip()) index = 0 while index < len(tokens): token = tokens[index] if not token: index += 1 continue if index + 2 < len(tokens) and tokens[index + 1] == "..": start = int(_UNI_TOKEN_RE.match(token).group(1), 16) end = int(_UNI_TOKEN_RE.match(tokens[index + 2]).group(1), 16) if end < start: raise DataValidationError(f"invalid unicode range in map: {token}..{tokens[index + 2]}") values.extend(range(start, end + 1)) index += 3 continue match = _UNI_TOKEN_RE.match(token) if match is None: raise DataValidationError(f"unparseable unicode token in map: {token!r}") values.append(int(match.group(1), 16)) index += 1 return tuple(values) @dataclass(frozen=True, slots=True) class KiratRaiLegacyConversion: legacy_text: str unicode_text: str kiratrai_char_count: int replacement_count: int unmapped_codepoints: list[str] def to_dict(self) -> dict[str, Any]: return { "legacy_text": self.legacy_text, "unicode_text": self.unicode_text, "kiratrai_char_count": self.kiratrai_char_count, "replacement_count": self.replacement_count, "unmapped_codepoints": self.unmapped_codepoints, } class KiratRaiLegacyConverter: """Native reader/applier for SIL's ``kiratraifontnew.map`` TECkit mapping. Rules are flattened to ``(source_bytes, target_codepoints)`` pairs and applied longest-match-first so that explicit multi-byte ligature rules (e.g. ``//`` -> double danda) take precedence over the single-byte class rules. """ def __init__(self, rules: list[tuple[tuple[int, ...], tuple[int, ...]]]) -> None: if not rules: raise DataValidationError("Kirat Rai legacy converter requires at least one mapping rule") # De-duplicate while preserving the longest-source-first ordering. seen: set[tuple[int, ...]] = set() ordered: list[tuple[tuple[int, ...], tuple[int, ...]]] = [] for source, target in sorted(rules, key=lambda item: len(item[0]), reverse=True): if source in seen: continue seen.add(source) ordered.append((source, target)) self._rules = ordered @classmethod def from_map_file( cls, path: str | Path = DEFAULT_KIRATRAI_LEGACY_MAP ) -> "KiratRaiLegacyConverter": map_path = Path(path) if not map_path.is_file(): raise DataValidationError(f"Kirat Rai legacy map does not exist: {map_path}") byte_classes: dict[str, tuple[int, ...]] = {} uni_classes: dict[str, tuple[int, ...]] = {} rules: list[tuple[tuple[int, ...], tuple[int, ...]]] = [] in_byte_pass = False # First parse class declarations; collect rule lines for a second pass so # class rules can reference classes regardless of declaration order. rule_lines: list[str] = [] for raw_line in map_path.read_text(encoding="utf-8-sig").splitlines(): line = raw_line.split(";", 1)[0].strip() if not line: continue lowered = line.lower() if lowered.startswith("pass("): in_byte_pass = lowered == "pass(byte_unicode)" continue if not in_byte_pass: continue byte_match = _BYTECLASS_RE.match(line) if byte_match: byte_classes[byte_match.group(1).strip()] = _expand_byte_tokens(byte_match.group(2)) continue uni_match = _UNICLASS_RE.match(line) if uni_match: uni_classes[uni_match.group(1).strip()] = _expand_uni_tokens(uni_match.group(2)) continue rule_lines.append(line) for line in rule_lines: class_rule = _CLASS_RULE_RE.match(line) if class_rule: left_name = class_rule.group(1).strip() right_name = class_rule.group(2).strip() left = byte_classes.get(left_name) right = uni_classes.get(right_name) if left is None: raise DataValidationError(f"class rule references unknown byte class: {left_name!r}") if right is None: raise DataValidationError(f"class rule references unknown unicode class: {right_name!r}") if len(left) != len(right): raise DataValidationError( f"class rule length mismatch for [{left_name}]>[{right_name}]: " f"{len(left)} bytes vs {len(right)} codepoints" ) for byte_value, codepoint in zip(left, right): rules.append(((byte_value,), (codepoint,))) continue if "<>" in line or ">" in line: left_text, right_text = line.split("<>", 1) if "<>" in line else line.split(">", 1) source = _BYTE_TOKEN_RE.findall(left_text) target = _UNI_TOKEN_RE.findall(right_text) if source and target: rules.append( ( tuple(int(value, 16) for value in source), tuple(int(value, 16) for value in target), ) ) return cls(rules) def convert(self, text: str) -> KiratRaiLegacyConversion: output: list[str] = [] unmapped: list[str] = [] replacements = 0 index = 0 length = len(text) while index < length: matched = False for source, target in self._rules: if self._matches(text, index, source): output.extend(chr(value) for value in target) replacements += 1 index += len(source) matched = True break if matched: continue char = text[index] output.append(char) code = ord(char) if code > 0x7F and not (0x16D40 <= code <= 0x16D7F): unmapped.append(f"U+{code:04X}") index += 1 converted = unicodedata.normalize("NFC", "".join(output)) return KiratRaiLegacyConversion( legacy_text=text, unicode_text=converted, kiratrai_char_count=len(_KIRATRAI_CODEPOINT_RE.findall(converted)), replacement_count=replacements, unmapped_codepoints=sorted(set(unmapped)), ) @staticmethod def _matches(text: str, index: int, source: tuple[int, ...]) -> bool: if index + len(source) > len(text): return False return all(ord(text[index + offset]) == code for offset, code in enumerate(source)) def convert_kiratrai_legacy_text( text: str, map_path: str | Path = DEFAULT_KIRATRAI_LEGACY_MAP ) -> KiratRaiLegacyConversion: return KiratRaiLegacyConverter.from_map_file(map_path).convert(text)