Run this model with HF Jobs

Run firqaaa/id_core_web_sm on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/firqaaa/id_core_web_sm. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/firqaaa/id_core_web_sm on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
id_core_web_sm / id_tokenizer.py
firqaaa's picture
Replace with id_core_news_sm 0.2.0 (spaCy 3.8, UD-style tokenizer, 18 NER labels)
33da93b verified
Raw History Blame Contribute Delete
6.81 kB
"""Indonesian tokenizer that follows UD Indonesian word segmentation.
spaCy's default `id` tokenizer, changed in two ways:
1. Intra-word hyphens never split a token. UD keeps reduplications
(konsep-konsep), ordinals (ke-3), decades (1990-an), ranges (2014-2019) and
compounds (APBN-P) as one word: 1,070 of 1,074 hyphenated words in GSD/CSUI
train+dev.
2. Clitics are split off with a lexicon check, so lexicalised words are kept:
enclitic particles -lah -kah -tah -pun (apakah -> apa kah)
enclitic pronouns -nya -ku -mu (bukunya -> buku nya)
proclitic pronouns ku- kau- (kuambil -> ku ambil)
but hanya, punya, masalah, sekolah, buku, kaum and meskipun stay whole,
because they are words in the lexicon.
Rules for splitting a token that is not itself in the lexicon:
- particles, -ku, -mu, ku-, kau-: only if the remainder is a lexicon word (or
splits further into one, e.g. bukunyalah -> buku nya lah).
- -nya on a lowercase token: the remainder only needs >= 3 letters, because
almost every lowercase word ending in -nya is host + clitic; the few that
aren't (hanya, punya) are in the lexicon. Capitalised tokens (Kenya, Sonya)
need the strict lexicon check.
The lexicon is built by scripts/build_tokenizer_lexicon.py from UD train+dev
words and spaCy's Indonesian lookup tables. It is loaded through
[initialize.tokenizer] and saved with the pipeline.
Register with `--code scripts/id_tokenizer.py` when training or loading.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
import spacy
from spacy.tokens import Doc
from spacy.util import compile_infix_regex, ensure_path
PARTICLES = ("lah", "kah", "tah", "pun")
PRONOUNS = ("nya", "ku", "mu")
PROCLITICS = ("kau", "ku")
# Strings each infix rule is tested on; a rule that splits any of them is dropped.
_HYPHEN_PROBES = ["konsep-konsep", "ke-3", "1990-an", "2014-2019", "APBN-P", "pra-Columbus", "Soekarno-Hatta"]
def _keep_infix(pattern: str) -> bool:
rx = re.compile(pattern)
return not any(rx.search(p) for p in _HYPHEN_PROBES)
class CliticSplitter:
def __init__(self, lexicon: set[str] | None = None):
self.lexicon = lexicon or set()
def _known(self, w: str) -> bool:
return w.lower() in self.lexicon
def split(self, word: str) -> list[str]:
"""Return the pieces of `word`; their concatenation always equals `word`."""
if not word[:1].isalpha() or self._known(word):
return [word]
parts = self._split(word, depth=0)
return parts if parts else [word]
def _valid(self, rest: str, depth: int) -> list[str] | None:
if len(rest) < 2:
return None
if self._known(rest):
return [rest]
if depth < 2:
return self._split(rest, depth + 1)
return None
def _split(self, word: str, depth: int) -> list[str] | None:
lw = word.lower()
for p in PARTICLES:
if lw.endswith(p) and len(lw) > len(p) + 1:
head = self._valid(word[: -len(p)], depth)
if head:
return head + [word[-len(p):]]
for c in PRONOUNS:
if lw.endswith(c) and len(lw) > len(c) + 1:
rest = word[: -len(c)]
head = self._valid(rest, depth)
if head:
return head + [word[-len(c):]]
if c == "nya" and word[:1].islower() and len(rest) >= 3 and rest.replace("-", "").isalpha():
return [rest, word[-3:]]
for c in PROCLITICS:
if lw.startswith(c) and len(lw) > len(c) + 2:
tail = self._valid(word[len(c):], depth)
if tail:
return [word[: len(c)]] + tail
return None
class IndonesianUDTokenizer:
"""Wraps spaCy's rule-based tokenizer and post-splits clitics."""
def __init__(self, nlp):
self.vocab = nlp.vocab
# spaCy's default rule-based tokenizer for nlp's language and vocab
self.base = spacy.registry.tokenizers.get("spacy.Tokenizer.v1")()(nlp)
infixes = [p for p in spacy.lang.id.Indonesian.Defaults.infixes if _keep_infix(p)]
self.base.infix_finditer = compile_infix_regex(infixes).finditer
# Special cases:
# - drop those that split a hyphenated word (UD keeps it whole);
# - drop abbreviations/initials ending in "." (UD splits the period off:
# Dr . 16-0, M . 16-0, H . 12-0, No . 14-3 in GSD/CSUI train+dev);
# - add PTB-style quote/dash tokens that GSD uses.
rules = {
k: v for k, v in self.base.rules.items()
if not ("-" in k and len(v) > 1 and k[:1].isalnum())
and not (len(k) > 1 and k.endswith(".") and k[:1].isalpha())
}
for s in ("``", "''", "--"):
rules[s] = [{"ORTH": s}]
self.base.rules = rules
self.splitter = CliticSplitter()
def __call__(self, text: str) -> Doc:
doc = self.base(text)
words, spaces = [], []
for t in doc:
text = t.text
# Abbreviations and initials: UD splits the period off (Dr . / R .)
if len(text) > 1 and text.endswith(".") and text[:-1].isalpha():
words.extend([text[:-1], "."])
spaces.extend([False, bool(t.whitespace_)])
continue
pieces = self.splitter.split(text)
words.extend(pieces)
spaces.extend([False] * (len(pieces) - 1) + [bool(t.whitespace_)])
return Doc(self.vocab, words=words, spaces=spaces)
def pipe(self, texts, batch_size=1000):
for t in texts:
yield self(t)
# --- initialize / serialization ------------------------------------------
def initialize(self, get_examples=None, *, nlp=None, lexicon_path: str | None = None):
if lexicon_path:
self.splitter.lexicon = set(json.loads(Path(lexicon_path).read_text(encoding="utf8")))
def to_bytes(self, *, exclude=tuple()):
return json.dumps(sorted(self.splitter.lexicon), ensure_ascii=False).encode("utf8")
def from_bytes(self, data, *, exclude=tuple()):
self.splitter.lexicon = set(json.loads(data.decode("utf8")))
return self
def to_disk(self, path, *, exclude=tuple()):
path = ensure_path(path)
path.mkdir(parents=True, exist_ok=True)
(path / "lexicon.json").write_bytes(self.to_bytes())
def from_disk(self, path, *, exclude=tuple()):
return self.from_bytes((ensure_path(path) / "lexicon.json").read_bytes())
@spacy.registry.tokenizers("id_ud_tokenizer.v1")
def create_id_ud_tokenizer():
def make(nlp):
return IndonesianUDTokenizer(nlp)
return make