Instructions to use orucexe/ulduz-morph-128k with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use orucexe/ulduz-morph-128k with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("orucexe/ulduz-morph-128k", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download tokenization_ulduz_morph.py from orucexe/ulduz-morph-128k: direct link, hf CLI and curl.
- Browser
- Download file 9.46 kB
-
https://huggingface.co/orucexe/ulduz-morph-128k/resolve/main/tokenization_ulduz_morph.py
- Command line
-
hf download hf://orucexe/ulduz-morph-128k/tokenization_ulduz_morph.py
-
curl -L -o tokenization_ulduz_morph.py https://huggingface.co/orucexe/ulduz-morph-128k/resolve/main/tokenization_ulduz_morph.py
9.46 kB
| """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, | |
| ) | |
| 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) | |