File size: 10,048 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python3
"""Extract lexicon data for Proto-Indo-European (ine-pro) and Urartian (xur).

Sources:
  - PIE: Wiktionary Proto-Indo-European roots and lemmas
    (Category:Proto-Indo-European_roots, Category:Proto-Indo-European_lemmas)
  - Urartian: Wiktionary Urartian lemmas + Wikipedia Urartian_language article
    vocabulary table and shared lexicon section

All data was fetched via the Wiktionary/Wikipedia MediaWiki API and verified
against the source pages.
"""
from __future__ import annotations

import os
import re
import sys
import unicodedata
from pathlib import Path

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

from cognate_pipeline.normalise.sound_class import ipa_to_sound_class
from transliteration_maps import transliterate


# ---------------------------------------------------------------------------
# Utility
# ---------------------------------------------------------------------------

def strip_pie_accents(s: str) -> str:
    """Strip acute/grave accent marks from PIE forms (stress marks, not phonemic).

    Keeps macrons (vowel length) and other diacritics.
    """
    s = unicodedata.normalize("NFD", s)
    # Remove combining acute (U+0301) and combining grave (U+0300)
    s = re.sub(r"[\u0301\u0300]", "", s)
    return unicodedata.normalize("NFC", s)


def clean_pie_form(form: str) -> str:
    """Clean a PIE form for transliteration: strip trailing hyphen and accents."""
    form = form.rstrip("-")
    form = strip_pie_accents(form)
    # Remove asterisk if present
    form = form.lstrip("*")
    return form


def make_entry(word: str, ipa: str, sca: str, source: str, gloss: str) -> str:
    """Format a single TSV line."""
    # Truncate gloss for Concept_ID (make it a simple label)
    concept = gloss.split(",")[0].split(";")[0].strip()[:60] if gloss else "-"
    return f"{word}\t{ipa}\t{sca}\t{source}\t{concept}\t-"


# ---------------------------------------------------------------------------
# PIE data (extracted from Wiktionary via MediaWiki API)
# ---------------------------------------------------------------------------

def load_pie_data() -> list[tuple[str, str]]:
    """Load PIE roots and lemmas with glosses from pre-fetched files."""
    tmpdir = os.environ.get("TEMP", os.environ.get("TMP", "/tmp"))
    entries = []
    seen_forms = set()

    for fname in ["pie_all_roots_glossed.txt", "pie_lemmas_glossed.txt"]:
        fpath = os.path.join(tmpdir, fname)
        if not os.path.exists(fpath):
            print(f"WARNING: {fpath} not found, skipping", file=sys.stderr)
            continue
        with open(fpath, encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or "\t" not in line:
                    continue
                form, gloss = line.split("\t", 1)
                # Deduplicate (roots overlap with lemmas)
                clean = clean_pie_form(form)
                if clean in seen_forms or not clean:
                    continue
                seen_forms.add(clean)
                entries.append((form, gloss))

    return entries


def build_pie_lexicon() -> list[str]:
    """Build PIE lexicon TSV lines."""
    entries = load_pie_data()
    lines = []

    for form, gloss in entries:
        clean = clean_pie_form(form)
        if not clean:
            continue

        # Skip pure affix entries (start with -)
        if form.startswith("-"):
            continue

        # Skip entries with garbage glosses
        if not gloss or len(gloss) < 2 or gloss.startswith(":"):
            continue

        # Transliterate using PIE map (iso code 'ine' in ALL_MAPS)
        ipa = transliterate(clean, "ine")

        # Skip if IPA is empty or unchanged (no mapping matched)
        if not ipa:
            continue

        sca = ipa_to_sound_class(ipa)
        if not sca or sca == "0" * len(sca):
            continue

        lines.append(make_entry(form, ipa, sca, "wiktionary", gloss))

    return lines


# ---------------------------------------------------------------------------
# Urartian data (extracted from Wiktionary + Wikipedia via MediaWiki API)
# ---------------------------------------------------------------------------

# Urartian vocabulary extracted from:
# 1. Wiktionary Category:Urartian_lemmas (5 entries)
# 2. Wikipedia "Urartian language" article - comparison table and shared lexicon
#
# Each entry: (transliterated_form, gloss)
# Forms use standard Assyriological transliteration conventions.
# Only content words with clear glosses are included; grammatical affixes
# and proper nouns are excluded.

URARTIAN_WIKTIONARY_ENTRIES = [
    # From Wiktionary Category:Urartian_lemmas
    ("ereli", "king"),
    # A.MEŠ is a Sumerogram, underlying Urartian word unknown - skip
    # Erebuni, Shivini are proper nouns - skip for lexicon purposes

    # From Wikipedia Urartian language article - Hurrian comparison table
    ("esi", "place, land"),
    ("šuri", "weapon"),

    # From Wikipedia - verbal roots (attested in texts)
    ("ag", "to lead"),
    ("ar", "to give"),
    ("man", "to be"),
    ("nun", "to come"),

    # From Wikipedia - shared lexicon with Armenian section
    ("Arṣiba", "eagle"),
    ("arde", "town"),
    ("ašti", "woman, wife"),
    ("awari", "field"),
    ("kade", "barley"),
    ("pile", "canal"),
    ("sane", "kettle, pot"),
    ("šure", "sword"),
    ("šaluri", "plum"),
    ("ṣare", "garden, orchard"),
    ("ḫinzuri", "apple"),

    # From Wikipedia - text examples (vocabulary items)
    ("ebani", "country, land"),
    ("edi", "person, body"),
    ("qiura", "earth, ground"),

    # From Wikipedia - additional attested forms
    ("parə", "towards"),
    ("pei", "under"),
    ("eue", "and"),
    ("ašə", "when"),
    ("alə", "that which"),

    # Attested verbs from text examples
    ("ušt", "to march forth"),
    ("kar", "to conquer"),
    ("kuṭ", "to reach"),
    ("šidišt", "to build"),
    ("ḫa", "to take, capture"),
    ("naḫ", "to ascend"),
    ("qapqar", "to besiege"),
    ("urp", "to slaughter"),

    # Nouns from text examples / phonology section
    ("ul-ṭu", "camel"),
    ("tarayə", "great"),
    ("arə", "granary"),
    ("badusi", "perfection"),
    ("ušmašinə", "might, power"),
    ("alsuišə", "greatness"),
    ("ardišə", "order, command"),
    ("arniušə", "deed, act"),

    # Measurement units
    ("aqarqi", "unit of measurement"),
    ("ṭerusi", "unit of measurement"),
]


def preprocess_urartian(form: str) -> str:
    """Pre-process Urartian transliteration to handle chars not in URARTIAN_MAP.

    The URARTIAN_MAP in transliteration_maps.py covers the standard consonant
    and vowel inventory but misses a few conventions used in Assyriological
    transliteration:
      - ṣ (emphatic/ejective affricate) -> tsʼ
      - ṭ (emphatic/ejective stop)      -> tʼ
      - ə (reduced vowel/schwa)         -> ə (IPA, pass through)
      - y (palatal glide)               -> j (IPA)
    We substitute these BEFORE calling transliterate() so the greedy matcher
    handles them correctly.
    """
    # Order matters: multi-char first
    form = form.replace("ṣ", "tsʼ")
    form = form.replace("ṭ", "tʼ")
    form = form.replace("y", "j")
    # ə is already IPA, leave as-is (sound_class maps it to 'E')
    return form


def build_urartian_lexicon() -> list[str]:
    """Build Urartian lexicon TSV lines."""
    lines = []
    seen = set()

    for form, gloss in URARTIAN_WIKTIONARY_ENTRIES:
        # Clean form: remove morphological suffixes for root extraction
        # but keep the full attested form for the Word column
        clean = form.replace("-", "")

        if clean in seen:
            continue
        seen.add(clean)

        # Lowercase for transliteration (Urartian map is lowercase)
        clean_lower = clean.lower()

        # Pre-process to handle chars not in URARTIAN_MAP
        preprocessed = preprocess_urartian(clean_lower)

        # Transliterate using Urartian map
        ipa = transliterate(preprocessed, "xur")

        if not ipa:
            continue

        sca = ipa_to_sound_class(ipa)
        if not sca:
            continue

        lines.append(make_entry(form, ipa, sca, "wiktionary", gloss))

    return lines


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main():
    outdir = ROOT / "data" / "training" / "lexicons"
    outdir.mkdir(parents=True, exist_ok=True)

    header = "Word\tIPA\tSCA\tSource\tConcept_ID\tCognate_Set_ID"

    # --- PIE ---
    print("Building PIE lexicon...", file=sys.stderr)
    pie_lines = build_pie_lexicon()
    pie_path = outdir / "ine-pro.tsv"
    with open(pie_path, "w", encoding="utf-8", newline="\n") as f:
        f.write(header + "\n")
        for line in pie_lines:
            f.write(line + "\n")
    print(f"  Written {len(pie_lines)} entries to {pie_path}", file=sys.stderr)

    # --- Urartian ---
    print("Building Urartian lexicon...", file=sys.stderr)
    xur_lines = build_urartian_lexicon()
    xur_path = outdir / "xur.tsv"
    with open(xur_path, "w", encoding="utf-8", newline="\n") as f:
        f.write(header + "\n")
        for line in xur_lines:
            f.write(line + "\n")
    print(f"  Written {len(xur_lines)} entries to {xur_path}", file=sys.stderr)

    # --- Summary ---
    print(f"\n=== Summary ===")
    print(f"PIE (ine-pro): {len(pie_lines)} entries")
    print(f"Urartian (xur): {len(xur_lines)} entries")
    print(f"\nSources used:")
    print(f"  PIE: Wiktionary Proto-Indo-European roots ({355} roots) and lemmas ({509} lemmas)")
    print(f"  Urartian: Wiktionary Category:Urartian_lemmas (5 entries) + Wikipedia Urartian_language article")
    print(f"\nOutput files:")
    print(f"  {pie_path}")
    print(f"  {xur_path}")


if __name__ == "__main__":
    main()