File size: 6,468 Bytes
3bbd5dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""Devanagari -> IAST / ISO 15919 romanization for the within-model fertility sweep.

The Phase 3 comparison of Devanagari against ITRANS held the model, the
language and the content fixed, but Llama-3.2 cuts both scripts into almost
the same number of pieces per word (3.05 vs 3.06), so it could not tell
whether the MTP cost follows tokens-per-word. IAST and ISO 15919 write the
same Hindi with diacritics (ā, ṭ, ṃ, ...) that Llama's vocabulary covers
less well, which raises tokens-per-word without touching the content.

Everything here mirrors src/data/itrans_transliterate.py so the three
schemes are held to one bar: embedded Latin-script spans (English words,
acronyms) are routed around aksharamukha in the forward direction, and the
reversibility check uses the same marker-aware round trip and the same
normalize_for_comparison equivalences as the Phase 1 ITRANS gate.
"""

import random
import re
from typing import Iterator, Optional

from aksharamukha import transliterate as aksharamukha_transliterate

from src.data.itrans_transliterate import (
    _MARK_END,
    _MARK_START,
    _MARKER_PATTERN,
    ReversibilityResult,
    _split_on_latin_spans,
    normalize_for_comparison,
)

# aksharamukha scheme names; ITRANS is included so the generic path can be
# checked against the Phase 1 implementation it generalizes.
SCHEMES = ("ITRANS", "IAST", "ISO")

# Quotation glyphs a scheme also uses as its avagraha (ऽ) letter. Going to
# the scheme, aksharamukha leaves a quotation mark untouched; coming back,
# it cannot tell that mark from the avagraha it writes with the same glyph,
# so 'वो' returns as ऽवोऽ. Like an embedded English word, a quotation mark
# is not phonetic content, so the marker-aware round trip routes it around
# the converter. Forward romanization is unchanged by this (the mark passes
# through either way). What remains genuinely ambiguous is a real avagraha,
# which these schemes write with the same glyph: 4,577 occurrences in the
# 50M-word corpus, about one per 11,000 words.
PROTECTED_PUNCTUATION = {"ITRANS": "", "IAST": "'", "ISO": "’"}


def _split_protected(text: str, scheme: str) -> list:
    """(is_protected, segment) pieces: Latin spans and the scheme's colliding quotation glyph."""
    glyphs = PROTECTED_PUNCTUATION[scheme]
    if not glyphs:
        return _split_on_latin_spans(text)
    glyph_pattern = re.compile("([" + re.escape(glyphs) + "])")
    parts = []
    for is_latin, seg in _split_on_latin_spans(text):
        if is_latin:
            parts.append((True, seg))
            continue
        for piece in glyph_pattern.split(seg):
            if piece:
                parts.append((piece in glyphs, piece))
    return parts


def romanize_scheme(text: str, scheme: str) -> str:
    """Devanagari -> scheme, leaving embedded Latin-script spans and protected punctuation untouched."""
    out = []
    for is_protected, seg in _split_protected(text, scheme):
        if is_protected or not seg:
            out.append(seg)
        else:
            out.append(aksharamukha_transliterate.process("Devanagari", scheme, seg))
    return "".join(out)


def _romanize_marked_scheme(text: str, scheme: str) -> str:
    """Devanagari -> scheme with protected spans wrapped in internal markers."""
    out = []
    for is_protected, seg in _split_protected(text, scheme):
        if is_protected:
            out.append(_MARK_START + seg + _MARK_END)
        elif seg:
            out.append(aksharamukha_transliterate.process("Devanagari", scheme, seg))
    return "".join(out)


def _deromanize_marked_scheme(marked_text: str, scheme: str) -> str:
    """Inverse of _romanize_marked_scheme: scheme-with-markers -> Devanagari."""
    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(scheme, "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(scheme, "Devanagari", chunk) if chunk else chunk)
    return "".join(out)


def roundtrip_scheme(text: str, scheme: str) -> str:
    """Devanagari -> scheme -> Devanagari through the marker-aware pair."""
    return _deromanize_marked_scheme(_romanize_marked_scheme(text, scheme), scheme)


def sentence_round_trips(sentence: str, scheme: str) -> bool:
    return normalize_for_comparison(roundtrip_scheme(sentence, scheme)) == normalize_for_comparison(sentence)


def check_reversibility_scheme(sentences: list, scheme: str, sample_size: int = 1000, seed: int = 0) -> ReversibilityResult:
    """Exact round-trip rate over a sample, sampled exactly as Phase 1's check_reversibility does."""
    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_scheme(s, scheme)
        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 _romanize_for_pool(args: tuple) -> str:
    text, scheme = args
    return romanize_scheme(text, scheme)


def iter_romanized(docs: Iterator[str], scheme: str, pool=None, batch_docs: int = 512) -> Iterator[str]:
    """Romanize documents in order, batch by batch, so a lazy consumer bounds the work.

    prepare_corpus stops pulling once its token budget is met; romanizing in
    fixed batches (in parallel when a multiprocessing pool is given) means at
    most one batch past that point is converted, rather than the whole corpus.
    """
    batch = []
    for text in docs:
        batch.append(text)
        if len(batch) >= batch_docs:
            yield from _convert(batch, scheme, pool)
            batch = []
    if batch:
        yield from _convert(batch, scheme, pool)


def _convert(batch: list, scheme: str, pool: Optional[object]) -> list:
    if pool is None:
        return [romanize_scheme(t, scheme) for t in batch]
    return pool.map(_romanize_for_pool, [(t, scheme) for t in batch], chunksize=8)