""" hf_core/tokenizer.py ──────────────────── CoreTokenizer — utilities for inspecting tokens: encoding, decoding, token-level stats, BPE merge visualisation, and vocabulary queries. """ from __future__ import annotations import unicodedata from dataclasses import dataclass from typing import List, Dict, Optional, Tuple @dataclass class TokenInfo: """Rich info about a single token.""" id: int text: str bytes: bytes is_special: bool char_count: int unicode_categories: List[str] def __repr__(self) -> str: safe = repr(self.text) return f"TokenInfo(id={self.id}, text={safe}, bytes={len(self.bytes)}B)" class CoreTokenizer: """ Thin wrapper around a HuggingFace tokenizer that adds: - verbose token inspection - byte-level breakdown - vocabulary search - token budget estimation """ def __init__(self): self._hf_tok = None # set by AICore after loading # ── attach to a loaded HF tokenizer ────────────────────────────────────── def attach(self, hf_tokenizer) -> None: self._hf_tok = hf_tokenizer # ── core encode / decode ────────────────────────────────────────────────── def encode(self, text: str) -> List[int]: self._check() return self._hf_tok.encode(text, add_special_tokens=False) def decode(self, ids: List[int], skip_special: bool = True) -> str: self._check() return self._hf_tok.decode(ids, skip_special_tokens=skip_special) def token_count(self, text: str) -> int: return len(self.encode(text)) # ── rich inspection ─────────────────────────────────────────────────────── def inspect(self, text: str) -> List[TokenInfo]: """Return a TokenInfo for every token in `text`.""" self._check() ids = self.encode(text) infos = [] for tid in ids: tok_text = self._hf_tok.decode([tid], skip_special_tokens=False) raw = tok_text.encode("utf-8", errors="replace") cats = list({unicodedata.category(ch) for ch in tok_text if ch.strip()}) special = tid in ( self._hf_tok.all_special_ids if hasattr(self._hf_tok, "all_special_ids") else [] ) infos.append(TokenInfo( id=tid, text=tok_text, bytes=raw, is_special=special, char_count=len(tok_text), unicode_categories=cats, )) return infos def show_tokens(self, text: str) -> None: """Pretty-print token breakdown to stdout.""" infos = self.inspect(text) print(f"\n{'─'*60}") print(f" Token breakdown ({len(infos)} tokens)") print(f"{'─'*60}") for i, t in enumerate(infos): flag = "★" if t.is_special else " " print(f" {flag} [{i:>3}] id={t.id:<7} " f"bytes={len(t.bytes):<3} text={repr(t.text)}") print(f"{'─'*60}\n") # ── token budget helper ─────────────────────────────────────────────────── def budget(self, text: str, context_window: int = 2048) -> Dict: used = self.token_count(text) return { "used": used, "remaining": max(0, context_window - used), "window": context_window, "pct_used": round(used / context_window * 100, 1), } # ── vocab search ────────────────────────────────────────────────────────── def find_tokens(self, substring: str, limit: int = 20) -> List[Tuple[int, str]]: """Find all vocab entries that contain `substring`.""" self._check() vocab = self._hf_tok.get_vocab() hits = [(v, k) for k, v in vocab.items() if substring in k] hits.sort() return hits[:limit] # ── helpers ─────────────────────────────────────────────────────────────── def _check(self): if self._hf_tok is None: raise RuntimeError( "CoreTokenizer not attached. Call AICore.load() first." ) @property def vocab_size(self) -> Optional[int]: return len(self._hf_tok.get_vocab()) if self._hf_tok else None def __repr__(self) -> str: v = self.vocab_size return f"CoreTokenizer(vocab_size={v})"