File size: 9,461 Bytes
ff7920a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Self-contained Hugging Face PreTrainedTokenizer wrapper for `ulduz-morph-128k`."""

from __future__ import annotations

import gzip
import json
import os
import pathlib
import re
import unicodedata
from typing import Dict, List, Optional, Tuple

from tokenizers import Tokenizer
from transformers import PreTrainedTokenizer

MARKER = "\u241f"
AZ_WORD_RE = re.compile(r"[A-Za-zƏəĞğİıÖöŞşÜüÇç]{5,}")
AZ_SPECIFIC_RE = re.compile(r"[ƏəĞğİıÖöŞşÜüÇç]")
AZ_CONTEXT_RE = re.compile(
    r"[ƏəĞğİıÖöŞşÜüÇç]|\b(?:və|ilə|üçün|olan|kimi|görə|daha|çox|bir|bu|ki|hər|bütün|tərəfindən)\b",
    re.IGNORECASE,
)
EN_BLOCK_SUFFIX_RE = re.compile(
    r"(?:ing|tion|sion|ment|ness|able|ible|ous|ive|ful|less|ship|ized|ised|ally|ology|graphy)$",
    re.IGNORECASE,
)


def _az_lower(s: str) -> str:
    return s.replace("İ", "i").replace("I", "ı").lower()


def _reapply_case(orig: str, pieces: List[str]) -> List[str]:
    if sum(len(p) for p in pieces) != len(orig):
        return [orig]
    out: List[str] = []
    pos = 0
    for p in pieces:
        out.append(orig[pos : pos + len(p)])
        pos += len(p)
    return out


class UlduzMorphTokenizer(PreTrainedTokenizer):
    vocab_files_names = {
        "vocab_file": "tokenizer_backend.json",
        "suffixes_file": "az_all_suffixes.json",
        "roots_file": "az_roots.tsv.gz",
        "parsed_file": "az_fsm_parsed_top100k.tsv.gz",
    }
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(

        self,

        vocab_file: Optional[str] = None,

        suffixes_file: Optional[str] = None,

        roots_file: Optional[str] = None,

        parsed_file: Optional[str] = None,

        bos_token: str = "<s>",

        eos_token: str = "</s>",

        unk_token: str = "<unk>",

        pad_token: str = "<pad>",

        mask_token: str = "<mask>",

        cls_token: str = "<cls>",

        sep_token: str = "<sep>",

        **kwargs,

    ):
        here = pathlib.Path(vocab_file).resolve().parent if vocab_file else pathlib.Path(__file__).resolve().parent
        backend_path = pathlib.Path(vocab_file) if vocab_file else (here / "tokenizer_backend.json")
        suf_path = pathlib.Path(suffixes_file) if suffixes_file else (here / "az_all_suffixes.json")
        roots_gz = pathlib.Path(roots_file) if roots_file else (here / "az_roots.tsv.gz")
        parsed_gz = pathlib.Path(parsed_file) if parsed_file else (here / "az_fsm_parsed_top100k.tsv.gz")

        self._here = here
        self._suf_path = suf_path
        self._roots_gz = roots_gz
        self._parsed_gz = parsed_gz
        self._backend = Tokenizer.from_file(str(backend_path))
        self._vocab_dict: Dict[str, int] = self._backend.get_vocab()
        self._id_to_tok: Dict[int, str] = {v: k for k, v in self._vocab_dict.items()}

        from . import az_fsm
        az_fsm.SUFFIXES_JSON = suf_path
        from .az_fsm import AzerbaijaniFSM

        self._roots: set[str] = set()
        self._freqs: Dict[str, int] = {}
        if roots_gz.exists():
            with gzip.open(roots_gz, "rt", encoding="utf-8") as f:
                next(f, None)
                for ln in f:
                    parts = ln.rstrip("\n").split("\t")
                    if len(parts) >= 2:
                        self._roots.add(parts[0])
                        self._freqs[parts[0]] = int(parts[1])

        self._cache: Dict[str, List[str]] = {r: [r] for r in self._roots}
        if parsed_gz.exists():
            with gzip.open(parsed_gz, "rt", encoding="utf-8") as f:
                next(f, None)
                for ln in f:
                    w, _, sp, _ = ln.rstrip("\n").split("\t")
                    if w in self._roots:
                        continue
                    pcs = [
                        t[:-1] if t.endswith("-") else (t[1:] if t.startswith("+") else t)
                        for t in sp.split()
                    ]
                    if sum(len(p) for p in pcs) == len(w):
                        self._cache[w] = pcs

        suf_data = json.loads(suf_path.read_text(encoding="utf-8"))
        self._prefixes = set()
        for k, v in suf_data.items():
            if "prefix" in k.lower() and isinstance(v, list):
                for item in v:
                    s = item["form"] if isinstance(item, dict) else str(item)
                    self._prefixes.add(s.strip("-").lower())

        self._fsm = AzerbaijaniFSM(known_roots=self._roots, word_freqs=self._freqs)
        kwargs.pop("clean_up_tokenization_spaces", None)
        super().__init__(
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            pad_token=pad_token,
            mask_token=mask_token,
            cls_token=cls_token,
            sep_token=sep_token,
            clean_up_tokenization_spaces=False,
            **kwargs,
        )

    @property
    def vocab_size(self) -> int:
        return len(self._vocab_dict)

    def get_vocab(self) -> Dict[str, int]:
        return dict(self._vocab_dict)

    def _segment_word(self, orig: str, az_sentence: bool) -> str:
        if not AZ_SPECIFIC_RE.search(orig):
            if not az_sentence or any(c in orig for c in "wWxX") or EN_BLOCK_SUFFIX_RE.search(orig):
                return orig
        low = _az_lower(orig)
        pcs = self._cache.get(low)
        if pcs is None:
            an = self._fsm.analyze(low, max_depth=8, min_root_len=2)[0]
            if (an.suffixes or an.prefix) and an.canonical_root in self._roots:
                pcs = ([an.prefix] if an.prefix else []) + [an.root] + [s for s, _ in an.suffixes]
                if sum(len(p) for p in pcs) != len(low):
                    pcs = [low]
            else:
                pcs = [low]
            if len(self._cache) < 300_000:
                self._cache[low] = pcs
        if len(pcs) <= 1:
            return orig
        cased = _reapply_case(orig, pcs)
        if len(cased) <= 2:
            return MARKER.join(cased)
        p0 = _az_lower(cased[0])
        if p0 in self._prefixes and len(cased) >= 3:
            return f"{cased[0]}{MARKER}{cased[1]}{MARKER}{''.join(cased[2:])}"
        return f"{cased[0]}{MARKER}{''.join(cased[1:])}"

    def _presegment(self, text: str) -> str:
        az_sentence = bool(AZ_CONTEXT_RE.search(text))
        if not az_sentence and not AZ_SPECIFIC_RE.search(text):
            return text
        return AZ_WORD_RE.sub(lambda m: self._segment_word(m.group(0), az_sentence), text)

    def _tokenize(self, text: str) -> List[str]:
        txt = unicodedata.normalize("NFC", text)
        if MARKER not in txt:
            return self._backend.encode(self._presegment(txt)).tokens
        parts = txt.split(MARKER)
        m_toks = self._backend.encode(MARKER).tokens
        out: List[str] = []
        for i, p in enumerate(parts):
            if p:
                out.extend(self._backend.encode(self._presegment(p)).tokens)
            if i + 1 < len(parts):
                out.extend(m_toks)
        return out

    def _convert_token_to_id(self, token: str) -> int:
        return self._vocab_dict.get(token, self._vocab_dict.get("<unk>", 1))

    def _convert_id_to_token(self, index: int) -> str:
        return self._id_to_tok.get(int(index), "<unk>")

    def convert_tokens_to_string(self, tokens: List[str]) -> str:
        ids = [self._vocab_dict[t] for t in tokens if t in self._vocab_dict]
        return self._backend.decode(ids, skip_special_tokens=False)

    def _decode(

        self,

        token_ids: List[int],

        skip_special_tokens: bool = False,

        clean_up_tokenization_spaces: bool = False,

        **kwargs,

    ) -> str:
        return self._backend.decode([int(i) for i in token_ids], skip_special_tokens=skip_special_tokens)

    def build_inputs_with_special_tokens(

        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None

    ) -> List[int]:
        if token_ids_1 is None:
            return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
        return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1 + [self.sep_token_id]

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str, str, str, str]:
        dst_dir = pathlib.Path(save_directory)
        dst_dir.mkdir(parents=True, exist_ok=True)
        pfx = (filename_prefix + "-") if filename_prefix else ""
        out_backend = dst_dir / (pfx + "tokenizer_backend.json")
        self._backend.save(str(out_backend))
        outs = [str(out_backend)]
        for src, base in (
            (self._suf_path, "az_all_suffixes.json"),
            (self._roots_gz, "az_roots.tsv.gz"),
            (self._parsed_gz, "az_fsm_parsed_top100k.tsv.gz"),
        ):
            dst = dst_dir / (pfx + base)
            if src.exists() and src.resolve() != dst.resolve():
                shutil.copy2(src, dst)
            outs.append(str(dst))
        fsm_src = pathlib.Path(__file__).resolve().parent / "az_fsm.py"
        fsm_dst = dst_dir / "az_fsm.py"
        if fsm_src.exists() and fsm_src.resolve() != fsm_dst.resolve():
            shutil.copy2(fsm_src, fsm_dst)
        return tuple(outs)