File size: 4,807 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
"""Parse the Dakshina Hindi subset into the fertility-ladder's controlled test set.

Dakshina is not on the Hugging Face Hub despite its GitHub-org-style name;
it is distributed as a tar from a Google Cloud Storage bucket, linked from
https://github.com/google-research-datasets/dakshina. This module only
parses an already-extracted hi/ subdirectory (see docs/hardware-notes.md
and configs/phase1.yaml for the expected local path); it does not fetch it.
"""

from collections import Counter, defaultdict
from dataclasses import dataclass
from pathlib import Path

from src.data.itrans_transliterate import romanize

ROMANIZED_PAIRS_RELPATH = "romanized/hi.romanized.rejoined.tsv"
LEXICON_RELPATHS = (
    "lexicons/hi.translit.sampled.train.tsv",
    "lexicons/hi.translit.sampled.dev.tsv",
    "lexicons/hi.translit.sampled.test.tsv",
)


@dataclass
class FertilityTriple:
    """One sentence in three tokenization-relevant forms, all same content and morphology.

    Attributes:
        devanagari: original native-script sentence (L1/L4/L5 content).
        itrans_roman: devanagari romanized via extended ITRANS (L2 content).
        natural_roman: the human-written romanization from Dakshina (L3 content).
    """

    devanagari: str
    itrans_roman: str
    natural_roman: str


def load_native_sentences(dakshina_hi_root: str) -> list:
    """Return the Devanagari half of the aligned pairs, one sentence per line."""
    path = Path(dakshina_hi_root) / ROMANIZED_PAIRS_RELPATH
    sentences = []
    with path.open(encoding="utf-8") as f:
        for line in f:
            native, _, *_ = line.rstrip("\n").split("\t")
            sentences.append(native)
    return sentences


def build_fertility_triples(dakshina_hi_root: str, lang_code: str = "hi", allowed_sentences: set = None) -> list:
    """Build (Devanagari, ITRANS-roman, natural-roman) triples for every aligned pair.

    ITRANS-roman is derived here via extended ITRANS transliteration of the
    Devanagari column.

    Args:
        dakshina_hi_root: path to the extracted Dakshina hi/ subdirectory.
        lang_code: passed through to romanize(); see its docstring.
        allowed_sentences: if given, only pairs whose Devanagari sentence is
            in this set are included. Used to restrict L2 construction to
            the verified-reversible subset (see
            src.data.itrans_transliterate.sentence_passes_reversibility) --
            a lossy romanization would otherwise silently violate the
            fertility ladder's "identical content" premise for L2.
    """
    path = Path(dakshina_hi_root) / ROMANIZED_PAIRS_RELPATH
    triples = []
    with path.open(encoding="utf-8") as f:
        for line in f:
            native, natural_roman, *_ = line.rstrip("\n").split("\t")
            if allowed_sentences is not None and native not in allowed_sentences:
                continue
            itrans_roman = romanize(native, lang_code)
            triples.append(FertilityTriple(devanagari=native, itrans_roman=itrans_roman, natural_roman=natural_roman))
    return triples


@dataclass
class AmbiguityStats:
    """Distribution of distinct attested romanizations per native type (H3's mechanism).

    Attributes:
        n_types: number of distinct native words with at least one attested romanization.
        mean_variants: mean number of distinct romanizations per type.
        histogram: Counter mapping (number of distinct romanizations) -> (number of types with that count).
    """

    n_types: int
    mean_variants: float
    histogram: Counter


def compute_romanization_ambiguity(dakshina_hi_root: str) -> AmbiguityStats:
    """Compute, per native type, how many distinct attested romanizations the lexicon records.

    Each lexicon row is (native_word, romanization, annotator_count); a
    native word with several rows has several attested romanizations. This
    counts distinct romanization strings per native word across all three
    lexicon splits (train/dev/test), since the split is an eval-protocol
    artifact, not a property of the language.
    """
    variants_by_type = defaultdict(set)
    root = Path(dakshina_hi_root)
    for relpath in LEXICON_RELPATHS:
        path = root / relpath
        with path.open(encoding="utf-8") as f:
            for line in f:
                fields = line.rstrip("\n").split("\t")
                if len(fields) < 2:
                    continue
                native, romanized = fields[0], fields[1]
                variants_by_type[native].add(romanized)

    counts = [len(v) for v in variants_by_type.values()]
    histogram = Counter(counts)
    n_types = len(counts)
    mean_variants = sum(counts) / n_types if n_types else 0.0
    return AmbiguityStats(n_types=n_types, mean_variants=mean_variants, histogram=histogram)