""" Armenian (Eastern, Western, Classical): the tokenizer, the segmenter of the clitics of Classical Armenian
"""
from pie_extended.processes import Process
import regex as re
from typing import Generator, List, Tuple
from pie_extended.pipeline.tokenizers.simple_tokenizer import SimpleTokenizer
from pie_extended.pipeline.iterators.proto import DataIterator
from pie_extended.pipeline.postprocessor.proto import ProcessorPrototype
from typing import Dict, Iterable, Optional, Sequence, Set
from pie_extended.pipeline.tokenizers.learned import LearnedSegmenter, features, learn, read_conllu # noqa: F401
from pie_extended.utils import get_path
# ---- from models/hy_hye/tokenizer.py
# Armenian marks written on a vowel *inside* the word they belong to: emphasis (՛), exclamation (՜), question (՞).
# The Universal Dependencies treebanks the models are trained on make them a token of their own, placed after the
# word (multiword token `Մի՞թե` -> words `Միթե`, `՞`): the tokenizer does the same.
MARKS = "՛՜՞"
# Armenian letters (not `\p{Armenian}`: this script also contains the Armenian punctuation: ։ ՝ ֊ ...)
LETTERS = "\u0531-\u0556\u0560-\u0588"
# Apostrophe of the Western Armenian clitics (կ՚ուզեմ -> `կ՚`, `ուզեմ`): it stays on the clitic.
APOSTROPHE = "՚"
_MARKS = re.compile("[{}]".format(MARKS))
_TOKEN = re.compile(
r"(?P<number>\d+(?:[.,]\d+)*)" # 1.000 2.37,8 (the UD treebanks keep them in one piece)
r"|(?P<ellipsis>\.{2,}|…)"
r"|(?P<word>[" + LETTERS + r"\p{M}\d_" + MARKS + r"]+" + APOSTROPHE + r"?)"
r"|(?P<foreign>[^\W" + LETTERS + r"]+)" # Latin... words: they never mix with Armenian letters
r"|(?P<other>\S)" # any other punctuation: one token each (hyphens too)
)
# End of a sentence (։ : ! ? …), possibly followed by closing quotes or brackets. The dot is *not* one: in these texts
# it is mostly an abbreviation, an initial or a number (Խ. Աբովյան, 2020թ.): on the dev sets of the three treebanks,
# counting it lowers the precision of the sentence boundaries from 85/90/53% to 99/98/94% (Eastern/Western/Classical).
_SENTENCE_END = re.compile(r"[։:!?…]+[»)\]”\"']*\s+")
[docs]
class ArmenianTokenizer(SimpleTokenizer):
""" Tokenizer for Eastern, Western and Classical Armenian, following the tokenization of their UD treebanks.
Punctuation is made of tokens of their own, hyphens split words, numbers and ellipsis stay in one piece, and
words do not mix scripts (`pensionnaireները` -> `pensionnaire`, `ները`).
>>> tokenizer = ArmenianTokenizer()
>>> list(tokenizer.sentence_tokenizer("Բարև աշխարհ։ Ինչպե՞ս ես՝ լավ, 1.000 դրամ..."))
[['Բարև', 'աշխարհ', '։'], ['Ինչպես', '՞', 'ես', '՝', 'լավ', ',', '1.000', 'դրամ', '...']]
The mark leaves its word: the word is written as it is in the text (`Ինչպե՞ս`) while the mark is not written
anywhere (empty string), which `surface_tokens` tells for the computation of spaces between tokens:
>>> tokenizer.surface_tokens()[3:6]
['Ինչպե՞ս', '', 'ես']
"""
def __init__(self, segmenter=None):
"""
:param segmenter: Object with a `cuts(word) -> List[int]` method that gives where a word is cut in several
words (Classical Armenian clitics, see `pie_extended.models.hy_xcl.segmenter`). None: words are not cut.
"""
super(ArmenianTokenizer, self).__init__()
self.segmenter = segmenter
self._surfaces: List[str] = []
[docs]
def reset(self):
self._surfaces = []
[docs]
def surface_tokens(self) -> List[str]:
return self._surfaces
[docs]
def sentence_tokenizer(self, text: str, lower: bool = False) -> Generator[List[str], None, None]:
self._surfaces = []
start = 0
for match in _SENTENCE_END.finditer(text):
sentence = self.word_tokenizer(text[start:match.end()], lower=lower)
if sentence:
yield sentence
start = match.end()
sentence = self.word_tokenizer(text[start:], lower=lower)
if sentence:
yield sentence
def _pieces(self, word: str, written: str) -> Tuple[List[str], List[str]]:
""" The words a written word is made of, and how each of them is written
>>> class AfterFirstLetter:
... cuts = lambda self, word: [1]
>>> ArmenianTokenizer(AfterFirstLetter())._pieces("զմեղս", "զմեղս")
(['զ', 'մեղս'], ['զ', 'մեղս'])
The marks stay with the piece they follow, whatever the place of the cut:
>>> ArmenianTokenizer(AfterFirstLetter())._pieces("զինչ", "զի՞նչ")
(['զ', 'ինչ'], ['զ', 'ի՞նչ'])
"""
cuts = self.segmenter.cuts(word) if self.segmenter else []
if not cuts:
return [word], [written]
bounds = [0] + list(cuts) + [len(word)]
pieces = [word[start:end] for start, end in zip(bounds, bounds[1:])]
# Place of each letter of the word in the written word (marks are not letters of the word)
place = [index for index, character in enumerate(written) if character not in MARKS]
starts = [0] + [place[cut] for cut in cuts]
surfaces = [written[start:end] for start, end in zip(starts, starts[1:] + [len(written)])]
return pieces, surfaces
[docs]
def word_tokenizer(self, text: str, lower: bool = False) -> List[str]:
tokens: List[str] = []
for match in _TOKEN.finditer(text):
written = match.group()
if match.lastgroup != "word":
tokens.append(written)
self._surfaces.append(written)
continue
word = _MARKS.sub("", written)
marks = _MARKS.findall(written)
if word:
pieces, surfaces = self._pieces(word, written)
tokens.extend(pieces)
self._surfaces.extend(surfaces)
for mark in marks: # Not written anywhere: it comes from the word
tokens.append(mark)
self._surfaces.append("")
else: # Only marks: they were alone in the text
for mark in marks:
tokens.append(mark)
self._surfaces.append(mark)
if lower:
tokens = [token.lower() for token in tokens]
return tokens
# ---- from models/hy_hye/imports.py
[docs]
def armenian_pipeline(max_tokens=256, segmenter=None):
""" Shared by the three Armenian models (hy_hye, hy_hyw, hy_xcl): same tokenization, no pre/post-processing.
Punctuation is tagged by the models (it is part of their training data) so nothing is excluded.
:param segmenter: Cuts words in several words (the clitics of Classical Armenian), see hy_xcl
"""
iterator = DataIterator(
tokenizer=ArmenianTokenizer(segmenter=segmenter),
max_tokens=max_tokens
)
return iterator, ProcessorPrototype()
# ---- from models/hy_xcl/segmenter.py
FILENAME = "clitics.json"
# Treebank the Pie model was trained on. CC BY-NC-SA 4.0: it is downloaded for the user, never redistributed.
TREEBANK = {
split: "https://raw.githubusercontent.com/UniversalDependencies/UD_Classical_Armenian-CAVaL/master/"
"xcl_caval-ud-{}.conllu".format(split)
for split in ("train", "dev", "test")
}
[docs]
def default_path() -> str:
return get_path("hy_xcl", FILENAME)
[docs]
class CliticSegmenter(LearnedSegmenter):
""" Gives where the clitics of a word have to be cut
>>> examples = [("զմեղս", {1}), ("զճանապարհ", {1}), ("յանապատին", {1, 8}), ("մեղս", set()), ("ճանապարհ", set())] * 4
>>> segmenter = train(examples, epochs=6)
>>> segmenter.cuts("զմեղս"), segmenter.cuts("մեղս")
([1], [])
>>> segmenter.split("յանապատին")
['յ', 'անապատի', 'ն']
"""
# Only words made of Armenian letters can be cut
WORD = re.compile(r"^[Ա-Ֆՠ-ֈ]+$")
[docs]
def make_tokenizer(segmenter=None):
""" The tokenizer of the Armenian models (what the tokens to cut are) """
return ArmenianTokenizer(segmenter=segmenter)
[docs]
def load_default(warn: bool = True) -> Optional[CliticSegmenter]:
""" The segmenter trained by `install-addons`, or None (with a warning) if it was not """
return CliticSegmenter.load_or_warn(
default_path(),
"The clitics of Classical Armenian are not split (the model was trained on words where they are): "
"run `pie-extended install-addons hy_xcl` to learn how from the Universal Dependencies treebank",
warn=warn
)
[docs]
def train(examples: Sequence[Tuple[str, Set[int]]], epochs: int = 8, seed: int = 0) -> CliticSegmenter:
return CliticSegmenter.train(examples, epochs=epochs, seed=seed)
[docs]
def training_examples(sentences: Iterable[Tuple[str, List[str]]]) -> List[Tuple[str, Set[int]]]:
""" Where the treebank cuts the words, for the tokens of our tokenizer (without any segmentation) """
return CliticSegmenter.training_examples(sentences, make_tokenizer())
[docs]
def evaluate(segmenter: CliticSegmenter, sentences: Sequence[Tuple[str, List[str]]]) -> Dict[str, float]:
return segmenter.evaluate(sentences, make_tokenizer)
# ---- from models/hy_xcl/imports.py
[docs]
def xcl_pipeline(max_tokens=256):
""" Same tokenization as the other Armenian models, plus the segmentation of the clitics (as in the treebank)
if it was learned (`pie-extended install-addons hy_xcl`) """
return armenian_pipeline(max_tokens=max_tokens, segmenter=load_default())
[docs]
def xcl_addons(model=None) -> bool:
""" Learns where the Universal Dependencies treebank of Classical Armenian cuts the clitics (`զմեղս` -> `զ`, `մեղս`)
The model expects pre-tokenized words like the ones of this treebank. The treebank is downloaded and the
segmenter is trained (a few seconds); only what it learned is kept, in the downloads of the model.
"""
from pie_extended.cli.utils import _download
learn(CliticSegmenter, TREEBANK, make_tokenizer, default_path(), _download)
return True
PROCESSES = {"hye": Process(armenian_pipeline), "xcl": Process(xcl_pipeline, addons=xcl_addons)}