Skip to content

Tokenizer

Character-level Sinhala tokenizer with a HuggingFace-compatible API. Splits Sinhala text into phonological units (base consonant + vowel diacritics) and maps them to integer IDs.

Class

Main tokenizer class. Combines consonants and diacritics dynamically.

Tokenizer(model_max_length=None, unk_token="<|unk|>", pad_token="<|pad|>", eos_token="<|end_of_text|>", bos_token="<|bos|>")
ArgumentTypeDescription
model_max_lengthintOptionalMaximum sequence length for padding/truncation. Default is None.
unk_tokenstrOptionalToken representing unknown characters.
pad_tokenstrOptionalToken representing padding.
bos_tokenstrOptionalBeginning of sequence token.
eos_tokenstrOptionalEnd of sequence token.

Load a pretrained tokenizer from the HuggingFace Hub or a local path.

Tokenizer.from_pretrained(pretrained_model_name_or_path, model_max_length=None)
ArgumentTypeDescription
pretrained_model_name_or_pathstrRequiredHuggingFace repo ID or local directory path.
model_max_lengthintOptionalOverride maximum sequence length.

Split text into phonological unit token strings.

tokenizer.tokenize(text)
ArgumentTypeDescription
textstrRequiredSinhala input string to split.

Encode text directly to a list of token IDs.

tokenizer.encode(text, add_special_tokens=True, add_bos_token=False)
ArgumentTypeDescription
textstrRequiredSinhala input string to encode.
from sinlib import Tokenizer
# Load default tokenizer
tokenizer = Tokenizer.from_pretrained("Ransaka/sinlib")
tokens = tokenizer.tokenize("ආයුබෝවන්")
# ['ආ', 'යු', 'බෝ', 'ව', 'න්']
# Simple ID list
ids = tokenizer.encode("ආයුබෝවන්")
# [4, 23, 18, 7, 12]
# Full BatchEncoding output
encoding = tokenizer("ආයුබෝවන්")
# BatchEncoding(input_ids=[4, 23, 18, 7, 12],
# attention_mask=[1, 1, 1, 1, 1])
res = tokenizer(
["ආයුබෝවන්", "සිංහල"],
padding=True,
truncation=True,
max_length=6,
return_tensors="np"
)
# returns arrays of uniform lengths