Datasets:
Download code/gemination.py from Chapimenge/amharic-gemination-lexicon: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/datasets/Chapimenge/amharic-gemination-lexicon/resolve/main/code/gemination.py
- Command line
-
hf download hf://datasets/Chapimenge/amharic-gemination-lexicon/code/gemination.py
-
curl -L -o gemination.py https://huggingface.co/datasets/Chapimenge/amharic-gemination-lexicon/resolve/main/code/gemination.py
12.5 kB
| """Amharic gemination from HornMorpho analyses. | |
| Amharic gemination (consonant doubling) changes meaning but is not written in | |
| Ge'ez script. HornMorpho (Michael Gasser, https://github.com/hltdi/HornMorpho) | |
| computes it while analysing a word, and keeps it in the `seg` field if and only | |
| if you call | |
| hm.anal('a', word, degem=False) | |
| With the default degem=True the marks are stripped. With degem=False, the | |
| character `/` stands immediately before every geminated character of the | |
| morphemic segmentation, whatever caused the doubling: the root template, the | |
| passive/reciprocal prefix t- assimilating to the first root consonant, a | |
| suffix such as the auxiliary -all, a lexicon entry, or reduplication. | |
| Example segs (degem=False): | |
| ይገኛል passive imperfect ----ይ</ገ/ኝ>---ኣ/ል--- ገ (t- prefix), ኛ (root), ል (suffix) | |
| ክልል noun -<ክ/ልል>------ ል (lexicon) | |
| የሚገኙ relative የ--/ም--ይ</ገ/ኝ>ኡ------ ሚ (prefix), ገ (t- prefix), ኙ (root) | |
| The seg is morphemic, not a copy of the surface word: vowels merge across | |
| morpheme boundaries (ቀም + ኣል gives ቀማል), palatalisation changes letters | |
| (ን + ኢ gives ኝ), and the glottal letter of a vowel-initial suffix disappears. | |
| This module therefore aligns the seg letters to the surface word by consonant | |
| series and moves each `/` to the surface character it aligned with. | |
| Do not read gemination from the `+gemN` feature instead. It only describes the | |
| root template, so it misses every geminate created by a prefix or suffix, and | |
| in reduplicated stems N counts template slots, not root consonants. | |
| Usage: | |
| python gemination.py ይገኛል ክልል መለወጥ (needs HornMorpho, see INSTALL.md) | |
| >>> from gemination import reading_gemination | |
| >>> reading_gemination("ይገኛል", {"seg": "----ይ</ገ/ኝ>---ኣ/ል---"})["pos"] | |
| [1, 2] | |
| Positions are 0-based indices into the word's Unicode characters (one Ge'ez | |
| fidel per index). | |
| Lexicon v3 rules (on by default; pass rules=False for the v2 behaviour). Each | |
| is backed by more than one independent source, see the dataset card: | |
| causative_glottal a causative prefix ስ- or ስተ- on a glottal-initial root | |
| holds the next root consonant (ማሳደ፟ግ, አስታው፟ስ); | |
| HornMorpho leaves it out of many segs | |
| relative_m_light the relative prefix's ም before a subject prefix | |
| (የሚ-, እንደሚ-, በሚ-, የምን-, የማይ-) is not held | |
| relative_exist with relative የ-, the reading of አለ "exist" (ለ held) | |
| is ranked above አለ "say" (ያለው, ያሉት) | |
| """ | |
| import difflib | |
| import re | |
| import sys | |
| GEM_PRE = "/" | |
| GEM_MARK = "፟" # ETHIOPIC COMBINING GEMINATION MARK | |
| BOUNDARY = set("-<>") | |
| GEEZ = re.compile(r"[ሀ-]") | |
| GLOTTAL = {(0x12A0 - 0x1200) // 8, (0x12D0 - 0x1200) // 8} # አ and ዐ series | |
| # palatalised surface letter -> base consonant it comes from | |
| PALATAL = {"ሽ": "ስ", "ች": "ት", "ጭ": "ጥ", "ኝ": "ን", "ዥ": "ዝ", "ጅ": "ድ", "ይ": "ል"} | |
| # letters pronounced the same in Amharic, spelled either way (ሣ/ሳ, ሐ/ሀ, ፀ/ጸ) | |
| HOMOPHONE = {"ሥ": "ስ", "ሕ": "ህ", "ኅ": "ህ", "ፅ": "ጽ", "ኽ": "ህ"} | |
| # labialised series (ቈ ኰ ጐ ኈ ዀ) are the base consonant plus w: ቅ + ዋ gives ቋ | |
| LABIAL_SERIES = {0x1248: 0x1240, 0x12B0: 0x12A8, 0x1310: 0x1308, 0x1288: 0x1280, 0x12C0: 0x12B8} | |
| SOURCES = ("root", "t-prefix", "prefix", "suffix", "lexicon", "reduplication") | |
| def series(ch): | |
| return (ord(ch) - 0x1200) // 8 | |
| def _key(ch): | |
| """Alignment key: consonant series, with labialised, homophone and palatal | |
| spellings folded to their base and both glottal series merged.""" | |
| base = 0x1200 + series(ch) * 8 | |
| base = LABIAL_SERIES.get(base, base) | |
| sixth = chr(base + 5) | |
| sixth = HOMOPHONE.get(sixth, sixth) | |
| sixth = PALATAL.get(sixth, sixth) | |
| s = series(sixth) | |
| return "G" if s in GLOTTAL else s | |
| def parse_seg(seg): | |
| """Seg string -> list of (char, geminated, region, source) for its Ge'ez | |
| characters. region: 'pre' before '<', 'stem' inside <...>, 'suf' after '>'. | |
| source (only for geminated characters) is inferred from the seg alone: | |
| prefix '/' before '<' (for example the relative yä-m- in የሚ) | |
| suffix '/' after '>' (the auxiliary -all, plural -očč, -nna) | |
| t-prefix '/' opens the stem ('</X'), sits on a boundary ('/-X'), | |
| or doubles an unassimilated ተ- ('/ተ-'): the passive or | |
| reciprocal t- merging into the next consonant | |
| lexicon stem without internal boundaries in a noun-shaped seg: an | |
| unanalysed dictionary entry that stores the gemination | |
| reduplication the same consonant series occurs earlier in the same | |
| morpheme (frequentative stems such as ገለባ/በጥ). Roots | |
| whose second half repeats the first (ግልግል, ስብስብ) also | |
| land here. | |
| root any other stem geminate: the root's template | |
| """ | |
| stem = seg[seg.find("<") + 1:seg.find(">")] if "<" in seg and ">" in seg else "" | |
| lexical = "<" in seg and "-" not in stem and seg[:seg.find("<")].count("-") <= 2 | |
| out, pending, opens, region, last, morph = [], False, False, "pre", "", [] | |
| for i, ch in enumerate(seg): | |
| if ch == GEM_PRE: | |
| pending = True | |
| nxt = seg[i + 1:i + 3] | |
| opens = last == "<" or nxt[:1] == "-" or nxt == "ተ-" | |
| elif ch == "<": | |
| region, morph = "stem", [] | |
| elif ch == ">": | |
| region = "suf" | |
| elif ch == "-": | |
| if region == "stem": | |
| morph = [] | |
| elif GEEZ.match(ch): | |
| src = None | |
| if pending: | |
| if region == "pre": | |
| src = "prefix" | |
| elif region == "suf": | |
| src = "suffix" | |
| elif opens: | |
| src = "t-prefix" | |
| elif lexical: | |
| src = "lexicon" | |
| elif series(ch) in {series(c) for c in morph}: | |
| src = "reduplication" | |
| else: | |
| src = "root" | |
| out.append((ch, pending, region, src)) | |
| if region == "stem": | |
| morph.append(ch) | |
| pending = opens = False | |
| if ch != "-": | |
| last = ch | |
| return out | |
| def seg_to_positions(word, seg): | |
| """-> ([(surface index, region, source)], ok). ok is False when a geminated | |
| seg character could not be aligned to the surface word.""" | |
| segc = parse_seg(seg) | |
| a = [_key(c) for c, _, _, _ in segc] | |
| b = [_key(c) for c in word] | |
| sm = difflib.SequenceMatcher(None, a, b, autojunk=False) | |
| m = {} | |
| for tag, i1, i2, j1, j2 in sm.get_opcodes(): | |
| if tag == "equal" or (tag == "replace" and i2 - i1 == j2 - j1): | |
| for k in range(i2 - i1): | |
| m[i1 + k] = j1 + k | |
| pos, ok = {}, True | |
| for i, (_, gem, region, src) in enumerate(segc): | |
| if not gem: | |
| continue | |
| if i in m: | |
| pos.setdefault(m[i], (region, src)) | |
| else: | |
| ok = False | |
| return sorted((p, r, s) for p, (r, s) in pos.items()), ok | |
| CAUSATIVE_GLOTTAL = re.compile(r"(ስተ?-ኣ)([ሀ-])") | |
| RELATIVE_M = re.compile(r"/ም(?=-+(?:ይ|እን|ት|ኣ))") | |
| def apply_rules(seg): | |
| """Apply the v3 seg rules. -> (new seg, names of the rules that fired).""" | |
| if not seg: | |
| return seg, [] | |
| fired = [] | |
| new = CAUSATIVE_GLOTTAL.sub(r"\1/\2", seg) | |
| if new != seg: | |
| fired.append("causative_glottal") | |
| if "<" in new: | |
| pre, rest = new.split("<", 1) | |
| light = RELATIVE_M.sub("ም", pre) | |
| if light != pre: | |
| fired.append("relative_m_light") | |
| new = light + "<" + rest | |
| return new, fired | |
| def relative_exist_first(word, patterns): | |
| """v3: with relative የ-, put the existence reading of አለ (ለ held) first. | |
| Bare ያለ is left alone: it can also be privative 'without', which holds nothing.""" | |
| if word == "ያለ": | |
| return patterns | |
| for i, p in enumerate(patterns): | |
| if any("<ኣ/ለ>" in s and s.split("<")[0].replace("-", "") == "የ" for s in p["segs"]): | |
| if i: | |
| p["rules"] = sorted(set(p.get("rules", [])) | {"relative_exist"}) | |
| patterns = [p] + patterns[:i] + patterns[i + 1:] | |
| return patterns | |
| return patterns | |
| def native_first(word, patterns, taps): | |
| """Put a native speaker's tapped positions first. taps: word -> positions.""" | |
| if word not in taps: | |
| return patterns | |
| pos = sorted(taps[word]) | |
| for i, p in enumerate(patterns): | |
| if p["pos"] == pos: | |
| p["native"] = True | |
| return [p] + patterns[:i] + patterns[i + 1:] | |
| return [{"pos": pos, "letters": [word[k] for k in pos], "sources": ["native"] * len(pos), "freq": None, | |
| "pos_tags": [], "ok": True, "segs": [], "rules": [], "native": True}] + patterns | |
| def reading_gemination(word, reading, final="suffix", rules=True): | |
| """Geminated surface positions for one HornMorpho reading (a dict with a | |
| 'seg' from hm.anal(..., degem=False)). | |
| final: what to do with a geminate on the last character. | |
| "suffix" (default) drop it only if it comes from a suffix and the last | |
| letter is sixth order, so no vowel follows. In practice this is | |
| the auxiliary -all of ይገኛል: it is not audible before a pause | |
| and Armbruster never marks it. Vowel-final suffixes (-allu) and | |
| stem-final geminates (ይሰ፟ጥ፟) are kept. | |
| "keep" keep every geminate. | |
| "drop" drop any word-final geminate. | |
| """ | |
| seg = reading.get("seg") or "" | |
| used, fired = apply_rules(seg) if rules else (seg, []) | |
| items, ok = seg_to_positions(word, used) | |
| last = len(word) - 1 | |
| if final == "suffix" and word: | |
| sixth = (ord(word[last]) - 0x1200) % 8 == 5 | |
| items = [x for x in items if not (x[0] == last and x[1] == "suf" and sixth)] | |
| elif final == "drop": | |
| items = [x for x in items if x[0] != last] | |
| return {"pos": [p for p, _, _ in items], "letters": [word[p] for p, _, _ in items], | |
| "sources": [s for _, _, s in items], "ok": ok, "seg": seg, "rules": fired} | |
| def word_gemination(word, readings, final="suffix", rules=True): | |
| """Distinct gemination patterns over all readings of a word, most frequent | |
| root first (HornMorpho's 'freq'). Readings that differ only in grammar but | |
| geminate the same positions share one pattern.""" | |
| pats = {} | |
| for r in readings: | |
| g = reading_gemination(word, r, final, rules) | |
| f = r.get("freq") or 0 | |
| e = pats.get(tuple(g["pos"])) | |
| if e is None: | |
| e = pats[tuple(g["pos"])] = {"pos": g["pos"], "letters": g["letters"], "sources": g["sources"], | |
| "freq": f, "pos_tags": set(), "ok": True, "segs": [], "rules": set()} | |
| elif f > e["freq"]: | |
| e["freq"], e["sources"] = f, g["sources"] | |
| e["pos_tags"].add(str(r.get("pos"))) | |
| e["segs"].append(g["seg"]) | |
| e["ok"] = e["ok"] and g["ok"] | |
| e["rules"].update(g["rules"]) | |
| out = sorted(pats.values(), key=lambda e: -e["freq"]) | |
| for e in out: | |
| e["pos_tags"], e["rules"] = sorted(e["pos_tags"]), sorted(e["rules"]) | |
| return relative_exist_first(word, out) if rules else out | |
| def mark(word, pos): | |
| """Write the gemination mark U+135F after each geminated character.""" | |
| s = set(pos) | |
| return "".join(c + (GEM_MARK if i in s else "") for i, c in enumerate(word)) | |
| def analyze(word, final="suffix", rules=True): | |
| """Run HornMorpho on one word and return its gemination patterns.""" | |
| import hm | |
| try: | |
| rs = list(hm.anal("a", word, degem=False)) | |
| except Exception: | |
| rs = [] | |
| return word_gemination(word, rs, final, rules) | |
| if __name__ == "__main__": | |
| for w in sys.argv[1:] or ["ይገኛል", "ክልል", "መለወጥ"]: | |
| pats = analyze(w) | |
| if not pats: | |
| print(f"{w}\tno analysis") | |
| for p in pats: | |
| print(f"{w}\t{mark(w, p['pos'])}\tpositions={p['pos']}\tsources={p['sources']}\t" | |
| f"pos={','.join(p['pos_tags'])}\troot_freq={p['freq']}\tseg={p['segs'][0]}") | |