File size: 7,540 Bytes
26786e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#!/usr/bin/env python3
"""Fix ABVD-sourced lexicon entries where Word == IPA (fake IPA).

Scans all TSV files in data/training/lexicons/ for entries sourced from
ABVD where the Word column is identical to the IPA column. For those
entries, applies G2P conversion (transphone if available, otherwise a
lightweight Austronesian-specific rule-based fallback) and recomputes
the SCA encoding from the new IPA.

TSV format: Word\tIPA\tSCA\tSource\tConcept_ID\tCognate_Set_ID
"""

from __future__ import annotations

import csv
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "cognate_pipeline" / "src"))

from cognate_pipeline.normalise.sound_class import ipa_to_sound_class

LEXICON_DIR = ROOT / "data" / "training" / "lexicons"
HEADER = "Word\tIPA\tSCA\tSource\tConcept_ID\tCognate_Set_ID\n"


# ---------------------------------------------------------------------------
# G2P backend selection
# ---------------------------------------------------------------------------

_USE_TRANSPHONE = False

try:
    from transphone import read_ipa  # type: ignore[import-untyped]

    _USE_TRANSPHONE = True
except ImportError:
    pass


def _transphone_g2p(word: str) -> str:
    """Attempt G2P via transphone."""
    try:
        phones = read_ipa(word, "ind")  # Indonesian as default Austronesian
        if phones:
            return "".join(phones)
    except Exception:
        pass
    return ""


# ---------------------------------------------------------------------------
# Lightweight Austronesian rule-based G2P fallback
# ---------------------------------------------------------------------------

# Ordered list of (regex_pattern, ipa_replacement).
# Longer / multi-char patterns come first so they match before single chars.
_AUSTRONESIAN_RULES: list[tuple[str, str]] = [
    # Trigraphs
    (r"ngg", "ŋɡ"),
    (r"ngk", "ŋk"),

    # Digraphs (order matters: test longer sequences first)
    (r"ng", "ŋ"),
    (r"ny", "ɲ"),
    (r"sy", "ʃ"),
    (r"ch", "tʃ"),
    (r"sh", "ʃ"),
    (r"th", "t"),       # Austronesian <th> is typically /t/
    (r"dj", "dʒ"),
    (r"tj", "tʃ"),
    (r"nj", "ɲ"),
    (r"kh", "x"),
    (r"gh", "ɣ"),
    (r"ph", "p"),       # Austronesian <ph> is typically /p/
    (r"bh", "b"),

    # Single consonants
    (r"c", "tʃ"),
    (r"j", "dʒ"),
    (r"y", "j"),
    (r"q", "ʔ"),
    (r"x", "ks"),
    (r"'", "ʔ"),

    # Vowels — keep most as-is since Latin orthography is close to IPA
    # for Austronesian languages, but handle a few specifics
    (r"aa", "aː"),
    (r"ee", "eː"),
    (r"ii", "iː"),
    (r"oo", "oː"),
    (r"uu", "uː"),
]

# Compile the rules into a single pass-through regex + lookup
_RULE_PATTERNS = [(re.compile(pat, re.IGNORECASE), repl) for pat, repl in _AUSTRONESIAN_RULES]


def _austronesian_g2p(word: str) -> str:
    """Best-effort rule-based orthographic-to-IPA for Austronesian words.

    Applies substitution rules in priority order (longest match first),
    then passes through any remaining characters unchanged.
    """
    text = word.lower().strip()
    if not text:
        return ""

    # Apply rules iteratively: scan left-to-right, try longest match first
    result: list[str] = []
    i = 0
    while i < len(text):
        matched = False
        for pat, repl in _RULE_PATTERNS:
            m = pat.match(text, i)
            if m:
                result.append(repl)
                i = m.end()
                matched = True
                break
        if not matched:
            # Pass through: most Austronesian letters map trivially
            ch = text[i]
            # Skip non-alphabetic (hyphens, spaces, digits, etc.)
            if ch.isalpha():
                result.append(ch)
            i += 1

    return "".join(result)


def g2p(word: str) -> str:
    """Convert an orthographic word to IPA using the best available backend."""
    if _USE_TRANSPHONE:
        ipa = _transphone_g2p(word)
        if ipa:
            return ipa
    # Fall back to rule-based Austronesian G2P
    return _austronesian_g2p(word)


# ---------------------------------------------------------------------------
# Main fix logic
# ---------------------------------------------------------------------------

def fix_file(tsv_path: Path) -> tuple[int, int, int]:
    """Fix fake-IPA entries in a single TSV file.

    Returns (total_abvd_fake, fixed, failed).
    """
    rows: list[dict[str, str]] = []
    total_abvd_fake = 0
    fixed = 0
    failed = 0

    with open(tsv_path, encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f, delimiter="\t")
        if reader.fieldnames is None:
            return 0, 0, 0
        for row in reader:
            source = row.get("Source", "")
            word = row.get("Word", "")
            ipa = row.get("IPA", "")

            if "abvd" in source and word == ipa and word:
                total_abvd_fake += 1
                new_ipa = g2p(word)
                if new_ipa and new_ipa != word:
                    row["IPA"] = new_ipa
                    row["SCA"] = ipa_to_sound_class(new_ipa)
                    fixed += 1
                else:
                    failed += 1

            rows.append(row)

    if fixed == 0:
        # Nothing changed — don't rewrite the file
        return total_abvd_fake, fixed, failed

    # Rewrite the file preserving exact column order
    with open(tsv_path, "w", encoding="utf-8", newline="") as f:
        f.write(HEADER)
        for row in rows:
            line = "\t".join([
                row.get("Word", ""),
                row.get("IPA", ""),
                row.get("SCA", ""),
                row.get("Source", ""),
                row.get("Concept_ID", ""),
                row.get("Cognate_Set_ID", ""),
            ])
            f.write(line + "\n")

    return total_abvd_fake, fixed, failed


def main() -> None:
    print("=" * 70)
    print("fix_abvd_ipa: Fix ABVD entries where Word == IPA")
    print("=" * 70)

    if _USE_TRANSPHONE:
        print("  G2P backend: transphone")
    else:
        print("  G2P backend: rule-based Austronesian fallback")

    if not LEXICON_DIR.exists():
        print(f"  ERROR: lexicon directory not found: {LEXICON_DIR}")
        sys.exit(1)

    tsv_files = sorted(LEXICON_DIR.glob("*.tsv"))
    print(f"  Lexicon directory: {LEXICON_DIR}")
    print(f"  TSV files found:   {len(tsv_files)}")
    print()

    total_files_scanned = 0
    total_files_modified = 0
    grand_total_fake = 0
    grand_total_fixed = 0
    grand_total_failed = 0

    for tsv_path in tsv_files:
        total_files_scanned += 1
        abvd_fake, fixed, failed = fix_file(tsv_path)

        grand_total_fake += abvd_fake
        grand_total_fixed += fixed
        grand_total_failed += failed

        if fixed > 0:
            total_files_modified += 1
            print(f"  {tsv_path.name}: {fixed} fixed, {failed} failed (of {abvd_fake} fake-IPA)")

    print()
    print("-" * 70)
    print("SUMMARY")
    print("-" * 70)
    print(f"  Files scanned:     {total_files_scanned}")
    print(f"  Files modified:    {total_files_modified}")
    print(f"  ABVD fake-IPA:     {grand_total_fake}")
    print(f"  Entries fixed:     {grand_total_fixed}")
    print(f"  Entries failed:    {grand_total_failed}")

    if grand_total_fake > 0:
        pct = grand_total_fixed / grand_total_fake * 100
        print(f"  Fix rate:          {pct:.1f}%")

    print("Done.")


if __name__ == "__main__":
    main()