code-switch-mtp / src /data /itrans_transliterate.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
9.6 kB
"""Devanagari <-> extended ITRANS romanization via aksharamukha.
indic-nlp-library's ITRANS implementation was tried first and rejected:
nukta consonants, independent-vs-dependent-vowel sequences (गई becomes
गैइ), and ITRANS string-level collisions (e.g. "ld" is both an alternate
spelling of the letter La and the literal transliteration of the
conjunct la+halant+da, so "ld" cannot be de-romanized unambiguously) all
corrupt on round trip, well below the reversibility bar this project
needs. aksharamukha resolves those. The remaining gap is that it does
not leave embedded Latin-script text (English words, acronyms, proper
nouns -- common in Wikipedia-sourced Hindi) alone; it tries to
transliterate them as phonetic content and corrupts them. romanize()
and deromanize() below route around aksharamukha for Latin-alphabet runs
instead of feeding them through it.
"""
import random
import re
import unicodedata
from dataclasses import dataclass
from aksharamukha import transliterate as aksharamukha_transliterate
LATIN_SPAN_PATTERN = re.compile(r"[A-Za-z][A-Za-z0-9]*(?:[-'][A-Za-z0-9]+)*")
# characters treated as equivalent to their counterpart in normalize_for_comparison:
# both Latin and Devanagari digits appear in the source corpus for the same numbers,
# and '.', the Devanagari danda '।', the double danda '॥', and a bare ASCII '|' all
# appear in Wikipedia-derived text as sentence-final markers interchangeably.
DEVANAGARI_DIGITS = str.maketrans("0123456789", "०१२३४५६७८९")
SENTENCE_PUNCT_PATTERN = re.compile(r"[.।॥|]")
ZERO_WIDTH_CHARS = ("‌", "‍") # ZWNJ, ZWJ -- affect rendering, not content
def _split_on_latin_spans(text: str) -> list:
"""Split text into (is_latin, segment) pieces at maximal Latin-alphanumeric runs.
Used by both romanize() and deromanize() so that Latin-script content
(embedded English words, acronyms) is routed around aksharamukha's
Devanagari<->ITRANS conversion rather than through it.
"""
parts = []
last_end = 0
for m in LATIN_SPAN_PATTERN.finditer(text):
if m.start() > last_end:
parts.append((False, text[last_end : m.start()]))
parts.append((True, m.group(0)))
last_end = m.end()
if last_end < len(text):
parts.append((False, text[last_end:]))
return parts
def romanize(text: str, lang_code: str = "hi") -> str:
"""Devanagari -> extended ITRANS, leaving embedded Latin-script spans untouched.
Splitting on Latin-alphanumeric runs is unambiguous here because the
input is Devanagari: anything Latin is unmistakably foreign content
(an English word, an acronym), not phonetic material to convert.
lang_code is accepted for interface stability (the prior
indic-nlp-library-backed version took one) but is currently unused:
aksharamukha is invoked with a fixed Devanagari/ITRANS scheme pair.
"""
out = []
for is_latin, seg in _split_on_latin_spans(text):
if is_latin or not seg:
out.append(seg)
else:
out.append(aksharamukha_transliterate.process("Devanagari", "ITRANS", seg))
return "".join(out)
def deromanize(text: str, lang_code: str = "hi") -> str:
"""Extended ITRANS -> Devanagari.
Does not attempt to protect embedded Latin-script spans: ITRANS is
itself Latin-alphabet, so unlike romanize()'s direction there is no
unambiguous way to tell "genuine ITRANS syllables" apart from
"foreign text romanize() left untouched" once markers are gone --
splitting on Latin runs here would match the entire string and
convert nothing. See _deromanize_marked for the internal, marker-
aware variant that reversibility checking actually uses.
"""
return aksharamukha_transliterate.process("ITRANS", "Devanagari", text) if text else text
# private-use-area sentinels: only ever manipulated by this module's own string
# splitting/joining, never passed into aksharamukha -- so their round trip through
# Devanagari<->ITRANS conversion is irrelevant (they never enter it).
_MARK_START = ""
_MARK_END = ""
_MARKER_PATTERN = re.compile(re.escape(_MARK_START) + "(.*?)" + re.escape(_MARK_END), re.DOTALL)
def _romanize_marked(text: str) -> str:
"""Devanagari -> ITRANS, wrapping embedded Latin spans in internal markers.
Markers let _deromanize_marked identify exactly which spans were
protected -- information a plain ITRANS string cannot carry, since
ITRANS is itself Latin-alphabet. Internal only: markers must never
reach anything that touches real experiment data.
"""
out = []
for is_latin, seg in _split_on_latin_spans(text):
if is_latin:
out.append(_MARK_START + seg + _MARK_END)
elif seg:
out.append(aksharamukha_transliterate.process("Devanagari", "ITRANS", seg))
return "".join(out)
def _deromanize_marked(marked_text: str) -> str:
"""Inverse of _romanize_marked: ITRANS-with-markers -> Devanagari, markers stripped."""
out = []
last_end = 0
for m in _MARKER_PATTERN.finditer(marked_text):
if m.start() > last_end:
chunk = marked_text[last_end : m.start()]
out.append(aksharamukha_transliterate.process("ITRANS", "Devanagari", chunk) if chunk else chunk)
out.append(m.group(1))
last_end = m.end()
if last_end < len(marked_text):
chunk = marked_text[last_end:]
out.append(aksharamukha_transliterate.process("ITRANS", "Devanagari", chunk) if chunk else chunk)
return "".join(out)
def _roundtrip_for_check(text: str, lang_code: str = "hi") -> str:
"""Devanagari -> ITRANS -> Devanagari via the marker-aware pair, for reversibility checking.
Uses _romanize_marked/_deromanize_marked rather than the public
romanize()/deromanize() pair because only the marked pair can
correctly restore embedded Latin spans -- deromanize() alone cannot,
for the reason documented on it. lang_code is accepted for interface
stability but currently unused, same as romanize()/deromanize().
"""
return _deromanize_marked(_romanize_marked(text))
def normalize_for_comparison(text: str) -> str:
"""Canonicalize renderings that are the same content, different formatting.
Applied to both sides of a reversibility comparison. Each step is a
principled equivalence grounded in how the source corpus itself
writes things inconsistently, not a loosened bar to force a pass:
- NFC normalization: a nukta consonant can be one precomposed
codepoint or base-consonant + combining nukta mark; these are
canonically the same character.
- digit script: the corpus mixes Latin and Devanagari digits for
the same numbers (both "18" and "१८" appear).
- sentence-final punctuation: '.', the Devanagari danda '।',
the double danda '॥', and a bare ASCII '|' (an old typing
convention some Wikipedia-derived text still uses as a danda
stand-in) all mark the same thing here.
- ZWNJ/ZWJ: zero-width joiners affect glyph rendering, not content.
Whitespace is collapsed afterward since removing punctuation can
leave spurious spacing differences that were never a content
difference.
"""
normalized = unicodedata.normalize("NFC", text)
normalized = normalized.translate(DEVANAGARI_DIGITS)
for zw in ZERO_WIDTH_CHARS:
normalized = normalized.replace(zw, "")
normalized = SENTENCE_PUNCT_PATTERN.sub("", normalized)
normalized = re.sub(r"\s+", " ", normalized).strip()
return normalized
@dataclass
class ReversibilityResult:
"""Outcome of a round-trip reversibility check over a sample of sentences.
Attributes:
n: number of sentences checked.
exact_matches: number where romanize-then-deromanize reproduced the
input exactly, after normalize_for_comparison on both sides.
rate: exact_matches / n.
failures: up to 20 (original, roundtripped) pairs that did not
match even after normalization, for inspection.
"""
n: int
exact_matches: int
rate: float
failures: list
def check_reversibility(sentences: list, lang_code: str = "hi", sample_size: int = 1000, seed: int = 0) -> ReversibilityResult:
"""Sample sentences, round-trip each through ITRANS, report the exact-match rate.
Comparison is via normalize_for_comparison, not raw string equality --
see that function's docstring for why byte-exact is the wrong bar here.
"""
rng = random.Random(seed)
pool = sentences if len(sentences) <= sample_size else rng.sample(sentences, sample_size)
exact_matches = 0
failures = []
for s in pool:
roundtripped = _roundtrip_for_check(s, lang_code)
if normalize_for_comparison(roundtripped) == normalize_for_comparison(s):
exact_matches += 1
elif len(failures) < 20:
failures.append((s, roundtripped))
n = len(pool)
return ReversibilityResult(n=n, exact_matches=exact_matches, rate=exact_matches / n if n else 0.0, failures=failures)
def sentence_passes_reversibility(sentence: str, lang_code: str = "hi") -> bool:
"""True if a single sentence round-trips exactly (after normalize_for_comparison).
Used to filter the full Dakshina sentence pool down to a verified-
reversible subset, rather than only sampling for a rate estimate.
"""
roundtripped = _roundtrip_for_check(sentence, lang_code)
return normalize_for_comparison(roundtripped) == normalize_for_comparison(sentence)