"""Tokenizers. All expose the same interface: tok.encode(text) -> list[int] # control tokens like map to single ids tok.vocab_size, tok.pad_id, tok.id(token_str) ByteTokenizer: UTF-8 bytes + control tokens. Language-agnostic, used for tests and Photon-S fallback. HFTokenizer: wraps a pretrained LLM tokenizer (Qwen3) with the control tokens added. CTC targets always use bytes (`ctc_targets`), independent of the backbone tokenizer. """ from __future__ import annotations from .tags import SPECIAL_TOKENS, split_specials, strip_tags CTC_BLANK = 0 # CTC vocab: 0 = blank, 1..256 = byte value + 1 CTC_VOCAB = 257 def ctc_targets(text: str) -> list[int]: return [b + 1 for b in strip_tags(text).encode("utf-8")] class ByteTokenizer: def __init__(self): self.specials = {t: 256 + i for i, t in enumerate(SPECIAL_TOKENS)} self.vocab_size = 256 + len(SPECIAL_TOKENS) self.pad_id = self.specials[""] def id(self, token: str) -> int: return self.specials[token] def encode(self, text: str) -> list[int]: ids: list[int] = [] for chunk, special in split_specials(text): ids.extend([self.specials[chunk]] if special else chunk.encode("utf-8")) return ids def decode(self, ids: list[int]) -> str: inv = {v: k for k, v in self.specials.items()} out, buf = [], bytearray() for i in ids: if i < 256: buf.append(i) else: out.append(buf.decode("utf-8", errors="replace")) buf = bytearray() out.append(inv.get(i, "")) out.append(buf.decode("utf-8", errors="replace")) return "".join(out) class HFTokenizer: def __init__(self, name: str): from transformers import AutoTokenizer self.tok = AutoTokenizer.from_pretrained(name) self.tok.add_special_tokens({"additional_special_tokens": SPECIAL_TOKENS}) self.vocab_size = len(self.tok) self.pad_id = self.tok.convert_tokens_to_ids("") def id(self, token: str) -> int: return self.tok.convert_tokens_to_ids(token) def encode(self, text: str) -> list[int]: return self.tok.encode(text, add_special_tokens=False) def decode(self, ids: list[int]) -> str: return self.tok.decode(ids) def build_tokenizer(name: str): return ByteTokenizer() if name == "bytes" else HFTokenizer(name)