Download hf_core/tokenizer.py from Aselionism/ASEL1: direct link, hf CLI and curl.
- Browser
- Download file 5.06 kB
-
https://huggingface.co/Aselionism/ASEL1/resolve/main/hf_core/tokenizer.py
- Command line
-
hf download hf://Aselionism/ASEL1/hf_core/tokenizer.py
-
curl -L -o tokenizer.py https://huggingface.co/Aselionism/ASEL1/resolve/main/hf_core/tokenizer.py
5.06 kB
| """ | |
| 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 | |
| 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." | |
| ) | |
| 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})" |