#!/usr/bin/env python3
"""tokcheck.py - does this GGUF tokenize like the Hugging Face tokenizer it was converted from?

It reads the tokenizer metadata in the GGUF header, tokenizes a fixed battery of
strings with llama.cpp (the real code: llama-tokenize, llama-server /tokenize, or
llama-cpp-python) and with the Hugging Face tokenizer, and reports the first place
where the token ids differ and which of the known causes it looks like.

  python tokcheck.py --gguf model.gguf --hf ./original-model-dir --llama-tokenize ./llama-tokenize
  python tokcheck.py --gguf model.gguf --hf Qwen/Qwen3-0.6B   --server http://127.0.0.1:8080
  python tokcheck.py --gguf model.gguf --hf ./tokenizer.json                  # uses llama-cpp-python
  python tokcheck.py --gguf model.gguf --hf ./dir --static                    # header checks only
  python tokcheck.py --gguf model.gguf --hf ./dir --slow ...                  # slow SentencePiece tokenizer (transformers 4.x)

Needs: Python 3.9+, and `transformers` (or just `tokenizers` when --hf is a tokenizer.json).
The GGUF reader is built in. Exit code: 0 = same ids, 1 = mismatch, 2 = could not run.
"""
import argparse, hashlib, json, os, struct, subprocess, sys, tempfile, unicodedata, urllib.request

VERSION = "1.0"
TYPE_NAMES = {1: "NORMAL", 2: "UNKNOWN", 3: "CONTROL", 4: "USER_DEFINED", 5: "UNUSED", 6: "BYTE"}
# token types that llama.cpp matches as whole tokens before the text is tokenized
# (src/llama-vocab.cpp, "build special tokens cache")
PARSED_TYPES = (2, 3, 4)

# The string convert_hf_to_gguf.py hashes to pick tokenizer.ggml.pre (get_vocab_base_pre).
CHKTXT = ('\n \n\n \n\n\n \t \t\t \t\n  \n   \n    \n     \n\U0001f680 (normal) \U0001f636\u200d\U0001f32b\ufe0f (multiple emojis concatenated) \u2705 '
          '\U0001f999\U0001f999 3 33 333 3333 33333 333333 3333333 33333333 3.3 3..3 3...3 \u1780\u17b6\u1793\u17cb\u178f\u17c2\u1796\u17b7\u179f\u17c1\u179f\u17a2\u17b6\u1785\U0001f601 ?\u6211\u60f3\u5728apple\u5de5\u4f5c1314151\u5929\uff5e '
          '------======= \u043d\u0435\u0449\u043e \u043d\u0430 \u0411\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438 \'\'\'\'\'\'```````""""......!!!!!!?????? I\'ve been \'told he\'s there, '
          '\'RE you sure? \'M not sure I\'ll make it, \'D you like some tea? We\'Ve a\'lL')

# ---------------------------------------------------------------- GGUF header

_SCALAR = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}


def read_gguf_metadata(path, want_prefix=("tokenizer.", "general.")):
    """Return {key: value} for the header keys that start with one of want_prefix."""
    out = {}
    with open(path, "rb") as f:
        if f.read(4) != b"GGUF":
            raise ValueError("%s is not a GGUF file" % path)
        version, = struct.unpack("<I", f.read(4))
        if version < 2:
            raise ValueError("GGUF version %d is not supported" % version)
        _n_tensors, n_kv = struct.unpack("<QQ", f.read(16))

        def rstr():
            n, = struct.unpack("<Q", f.read(8))
            return f.read(n)

        def rval(t, keep):
            if t in _SCALAR:
                fmt = _SCALAR[t]
                return struct.unpack(fmt, f.read(struct.calcsize(fmt)))[0]
            if t == 8:
                b = rstr()
                return b.decode("utf-8", "replace") if keep else None
            if t == 9:
                et, n = struct.unpack("<IQ", f.read(12))
                if et in _SCALAR:
                    fmt = _SCALAR[et]
                    raw = f.read(struct.calcsize(fmt) * n)
                    return list(struct.unpack("<%d%s" % (n, fmt[1]), raw)) if keep else None
                return [rval(et, keep) for _ in range(n)]
            raise ValueError("unknown GGUF value type %d" % t)

        for _ in range(n_kv):
            key = rstr().decode()
            t, = struct.unpack("<I", f.read(4))
            keep = key.startswith(want_prefix)
            v = rval(t, keep)
            if keep:
                out[key] = v
    return out

# ---------------------------------------------------------------- Hugging Face side


class HF:
    def __init__(self, spec, slow=False):
        self.spec = spec
        self.bos_id = self.eos_id = None
        if os.path.isfile(spec) and spec.endswith(".json"):
            from tokenizers import Tokenizer
            self.kind = "tokenizers"
            self.tk = Tokenizer.from_file(spec)
            self._enc = lambda s, sp: self.tk.encode(s, add_special_tokens=sp).ids
            self.size = self.tk.get_vocab_size(with_added_tokens=True)
            self.id_to_token = self.tk.id_to_token
            added = self.tk.get_added_tokens_decoder()
        else:
            from transformers import AutoTokenizer
            self.kind = "transformers"
            self.tk = AutoTokenizer.from_pretrained(spec, use_fast=False) if slow else AutoTokenizer.from_pretrained(spec)
            if slow:
                self.kind = "transformers, slow %s" % type(self.tk).__name__
            self._enc = lambda s, sp: self.tk.encode(s, add_special_tokens=sp)
            self.size = len(self.tk)
            self.id_to_token = self.tk.convert_ids_to_tokens
            added = self.tk.added_tokens_decoder
            self.bos_id, self.eos_id = self.tk.bos_token_id, self.tk.eos_token_id
        self.added = {int(i): {"content": a.content, "special": bool(a.special), "lstrip": bool(a.lstrip),
                               "rstrip": bool(a.rstrip)} for i, a in added.items()}

    def encode(self, s, add_special):
        return list(self._enc(s, add_special))

# ---------------------------------------------------------------- llama.cpp side


class EngineBin:
    name = "llama-tokenize"

    def __init__(self, binary, gguf):
        self.binary, self.gguf = binary, gguf

    def encode(self, s, add_special):
        if s == "":
            return []
        with tempfile.NamedTemporaryFile("wb", suffix=".txt", delete=False) as t:
            t.write(s.encode("utf-8"))
        try:
            # --no-escape: without it llama-tokenize turns a literal backslash-n in the file into a newline
            cmd = [self.binary, "-m", self.gguf, "-f", t.name, "--ids", "--log-disable", "--no-escape"]
            if not add_special:
                cmd.append("--no-bos")
            p = subprocess.run(cmd, capture_output=True, text=True)
        finally:
            os.unlink(t.name)
        lines = [l for l in p.stdout.strip().splitlines() if l.startswith("[")]
        if p.returncode != 0 or not lines:
            raise RuntimeError("llama-tokenize failed (exit %d): %s" % (p.returncode, (p.stderr or p.stdout)[-400:]))
        return json.loads(lines[-1])


class EngineServer:
    name = "llama-server /tokenize"

    def __init__(self, url):
        self.url = url.rstrip("/") + "/tokenize"

    def encode(self, s, add_special):
        body = json.dumps({"content": s, "add_special": add_special, "parse_special": True}).encode()
        req = urllib.request.Request(self.url, body, {"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=60) as r:
            return json.loads(r.read())["tokens"]


class EnginePy:
    name = "llama-cpp-python"

    def __init__(self, gguf):
        from llama_cpp import Llama
        self.llm = Llama(model_path=gguf, vocab_only=True, verbose=False)

    def encode(self, s, add_special):
        return self.llm.tokenize(s.encode("utf-8"), add_bos=add_special, special=True)

# ---------------------------------------------------------------- the test strings

PLAIN = [
    ("words", "Hello world"), ("words", " Hello world"), ("words", "Hello, world!"), ("words", "The quick brown fox"),
    ("words", "I've been told he's there, we'll see"), ("words", "na\u00efve caf\u00e9 \u00c4pfel"),
    ("space", "a  b"), ("space", "a   b"), ("space", "    indented"), ("space", "a\tb"), ("space", "a\nb"),
    ("space", "a\n\nb"), ("space", "a\n\n\nb"), ("space", "line one\n  line two\n"), ("space", "trailing space "),
    ("space", "a  #"), ("space", "    }"),
    ("digits", "1234567"), ("digits", "3.14159"), ("digits", "In 1999, 1234567 people paid $3.50 each"),
    ("digits", "2,560 x 6912"), ("digits", "0x1F4A9 1e-5"),
    ("code", "def f(*args, **kwargs):"), ("code", "for (int i = 0; i < n; ++i) { x[i] += 1; }"),
    ("code", '{"key": [1, 2, 3], "ok": true}'), ("code", "print(f\"{a!r}\\n\")"), ("code", "<div class=\"x\">y</div>"),
    ("unicode", "\u3053\u3093\u306b\u3061\u306f\u3001\u4e16\u754c\u3002"), ("unicode", "\u6771\u4eac\u90fd\u306f\u65e5\u672c\u306e\u9996\u90fd\u3067\u3059"), ("unicode", "\u6211\u60f3\u5728apple\u5de5\u4f5c"),
    ("unicode", "\u041f\u0440\u0438\u0432\u0435\u0442, \u043c\u0438\u0440"), ("unicode", "\u0645\u0631\u062d\u0628\u0627 \u0628\u0627\u0644\u0639\u0627\u0644\u0645"), ("unicode", "\u0926\u0940 \u0939\u093f\u0902\u0926\u0940"), ("unicode", "\u0e20\u0e32\u0e29\u0e32\u0e44\u0e17\u0e22"),
    ("unicode", "\U0001f999\U0001f999 \U0001f680 \u2705"), ("unicode", "\U0001f636\u200d\U0001f32b\ufe0f ok"), ("unicode", "e\u0301 vs \u00e9"),
]
SPECIAL_SHAPES = ["{t}", "a{t}b", "{t}b", "{t} b", "{t}  b", "{t}\nb", "a {t}", "a{t} b c"]
CAUSES = {
    "vocab": "The vocabulary itself differs (size or token text at the same id). The GGUF was made from a different "
             "tokenizer than --hf (another revision, a fine-tune that added tokens, or a merge). Reconvert from the "
             "exact model directory you are comparing against.",
    "special-type": "A token the Hugging Face tokenizer treats as an added/special token is typed NORMAL in the GGUF, "
                    "so llama.cpp never matches it as one token and splits its text into pieces. Chat templates then "
                    "silently feed the model fragments. Fix the token_type entries (3 = CONTROL) or reconvert from a "
                    "model directory whose tokenizer_config.json / tokenizer.json still lists the token under added tokens.",
    "space-after-special": "Ids differ only in the text right after a special token. Hugging Face decides what happens "
                           "to whitespace there per token (lstrip/rstrip flags, and for SentencePiece models the "
                           "`legacy` flag); llama.cpp has its own rule (SPM: it does not add the space prefix after a "
                           "special token; rstrip/lstrip only for a few hard-coded model families). No header fix: "
                           "format prompts so the template's own spacing is used, and compare with the template applied.",
    "bos-eos": "Only the tokens added at the start/end differ. Compare tokenizer.ggml.add_bos_token / add_eos_token "
               "and the bos/eos ids with the Hugging Face tokenizer; a double BOS also appears when the chat template "
               "already contains it.",
    "pre-missing": "The GGUF has a BPE vocabulary but no tokenizer.ggml.pre, so llama.cpp falls back to the 'default' "
                   "pre-tokenizer. Reconvert with a current convert_hf_to_gguf.py, or write the name into a copy of "
                   "the file: gguf-new-metadata in.gguf out.gguf --pre-tokenizer <name> (llama-tokenize ignores "
                   "--override-kv, so an override cannot be tested with it).",
    "pre-tokenizer": "Plain text (no special tokens) is split differently. For BPE models this is the pre-tokenizer: "
                     "tokenizer.ggml.pre names the wrong rule for this tokenizer, or the rule in this llama.cpp build "
                     "differs from tokenizer.json. Look up the chkhsh printed above to see which name "
                     "the converter assigns, write it into a copy (gguf-new-metadata in.gguf out.gguf "
                     "--pre-tokenizer <name>) and run this again; if the name is already right, update llama.cpp.",
    "normalizer": "Plain text (no special tokens) differs on a vocabulary that is not byte-level BPE. Check "
                  "tokenizer.ggml.add_space_prefix and remove_extra_whitespaces in the header, the llama.cpp build "
                  "(SentencePiece prefix handling changed in b12751), and that you compare against the Hugging Face "
                  "variant the model was trained with (slow vs fast, the `legacy` flag: try --slow).",
    "unicode-normalization": "The Hugging Face tokenizer normalises text to NFC before tokenizing (tokenizer.json "
                             "\"normalizer\"), llama.cpp tokenizes the bytes as given. Only text with decomposed "
                             "characters (a letter followed by a combining mark) is affected, and llama.cpp gives the "
                             "Hugging Face ids once the input is NFC. Normalise prompts yourself: "
                             "unicodedata.normalize('NFC', text).",
    "other": "Ids differ in a way this script does not recognise. Use the first differing string above as a repro.",
}

# ---------------------------------------------------------------- checks


def static_checks(md, hf):
    """Compare the header with the HF tokenizer. Returns (facts, findings); a finding is (level, code, text)."""
    toks = md.get("tokenizer.ggml.tokens") or []
    types = md.get("tokenizer.ggml.token_type") or [1] * len(toks)
    model = md.get("tokenizer.ggml.model")
    pre = md.get("tokenizer.ggml.pre")
    facts = {"tokenizer.ggml.model": model, "tokenizer.ggml.pre": pre, "gguf_vocab": len(toks), "hf_vocab": hf.size,
             "add_bos_token": md.get("tokenizer.ggml.add_bos_token"), "add_eos_token": md.get("tokenizer.ggml.add_eos_token"),
             "add_space_prefix": md.get("tokenizer.ggml.add_space_prefix"),
             "bos_token_id": md.get("tokenizer.ggml.bos_token_id"), "eos_token_id": md.get("tokenizer.ggml.eos_token_id"),
             "general.name": md.get("general.name"), "general.architecture": md.get("general.architecture")}
    f = []
    if not toks:
        return facts, [("FAIL", "vocab", "the GGUF has no tokenizer.ggml.tokens (no embedded vocabulary)")]
    if len(toks) != hf.size:
        lvl = "FAIL" if len(toks) < hf.size else "WARN"
        f.append((lvl, "vocab", "vocabulary size: GGUF %d, Hugging Face %d" % (len(toks), hf.size)))
    if model == "gpt2":
        try:
            facts["chkhsh"] = hashlib.sha256(str(hf.encode(CHKTXT, True)).encode()).hexdigest()
        except Exception as e:  # pragma: no cover
            facts["chkhsh"] = "error: %s" % e
        if not pre:
            f.append(("FAIL", "pre-missing", "BPE vocabulary without tokenizer.ggml.pre: llama.cpp uses 'default'"))
    if model in ("gpt2", "llama"):  # WordPiece/Unigram converters rewrite the token text, so skip those
        bad = []
        for i in range(min(len(toks), hf.size)):
            if types[i] == 5 or i in hf.added:
                continue
            if toks[i] != hf.id_to_token(i):
                bad.append(i)
        facts["token_text_mismatches"] = len(bad)
        if bad:
            ex = ", ".join("%d: %r vs %r" % (i, toks[i], hf.id_to_token(i)) for i in bad[:4])
            f.append(("FAIL", "vocab", "%d token texts differ at the same id (GGUF vs HF), e.g. %s" % (len(bad), ex)))
    wrong = []
    for i, a in sorted(hf.added.items()):
        if i >= len(toks):
            continue
        if toks[i] != a["content"]:
            f.append(("FAIL", "vocab", "added token %d is %r in Hugging Face but %r in the GGUF" % (i, a["content"], toks[i])))
        elif types[i] not in PARSED_TYPES:
            wrong.append(i)
    facts["added_tokens"] = len(hf.added)
    facts["added_tokens_typed_normal"] = wrong
    if wrong:
        ex = ", ".join("%d %r=%s" % (i, toks[i], TYPE_NAMES.get(types[i], types[i])) for i in wrong[:6])
        f.append(("FAIL", "special-type", "%d added token(s) are not CONTROL/USER_DEFINED in the GGUF: %s" % (len(wrong), ex)))
    strip = [i for i, a in hf.added.items() if a["lstrip"] or a["rstrip"]]
    facts["added_tokens_with_strip"] = len(strip)
    if strip:
        ex = ", ".join("%r(%s)" % (hf.added[i]["content"], "+".join(k for k in ("lstrip", "rstrip") if hf.added[i][k]))
                       for i in sorted(strip)[:5])
        f.append(("NOTE", "space-after-special", "%d Hugging Face added token(s) strip neighbouring whitespace: %s. "
                  "GGUF has no field for this; llama.cpp hard-codes it for a few model families." % (len(strip), ex)))
    for k, hid in (("bos_token_id", hf.bos_id), ("eos_token_id", hf.eos_id)):
        g = md.get("tokenizer.ggml." + k)
        if hid is not None and g is not None and g != hid:
            f.append(("WARN", "bos-eos", "%s: GGUF %s, Hugging Face %s" % (k, g, hid)))
    return facts, f


def pick_specials(md, hf, limit=6):
    toks = md.get("tokenizer.ggml.tokens") or []
    types = md.get("tokenizer.ggml.token_type") or []
    # tokens the header check flagged come first, so the report shows what llama.cpp does with them
    order = [i for i in sorted(hf.added) if i < len(types) and toks[i] == hf.added[i]["content"]
             and types[i] not in PARSED_TYPES][:3]
    for i in (hf.bos_id, hf.eos_id, md.get("tokenizer.ggml.bos_token_id"), md.get("tokenizer.ggml.eos_token_id")):
        if i is not None and i in hf.added and i not in order:
            order.append(i)
    rest = sorted(i for i in hf.added if i not in order and i < len(toks))
    sp = [i for i in rest if hf.added[i]["special"]]
    ns = [i for i in rest if not hf.added[i]["special"]]
    order += sp[:max(0, limit - len(order) - min(2, len(ns)))] + ns[:2]
    return order[:limit]


def build_cases(md, hf):
    cases = [(cat, s, False) for cat, s in PLAIN]
    for i in pick_specials(md, hf):
        t = hf.added[i]["content"]
        cases += [("special", shape.format(t=t), False) for shape in SPECIAL_SHAPES]
    cases += [("bos-eos", "Hello world", True), ("bos-eos", "\u3053\u3093\u306b\u3061\u306f", True)]
    return cases


def first_diff(a, b):
    n = min(len(a), len(b))
    for i in range(n):
        if a[i] != b[i]:
            return i
    return n if len(a) != len(b) else -1


def classify(cat, text, g, h, md, hf):
    """Name the cause of one mismatch. g = llama.cpp ids, h = Hugging Face ids."""
    types = md.get("tokenizer.ggml.token_type") or [1] * len(md.get("tokenizer.ggml.tokens") or [])
    if cat == "yours" and any(i in hf.added for i in h):
        cat = "special"  # a line from --text-file that contains an added token
    if cat == "bos-eos":
        ends = {md.get("tokenizer.ggml.bos_token_id"), md.get("tokenizer.ggml.eos_token_id"), hf.bos_id, hf.eos_id}
        ends |= set(hf.added)
        if [i for i in g if i not in ends] == [i for i in h if i not in ends]:
            return "bos-eos"
    if cat == "special":
        missed = [i for i in h if i in hf.added and i not in g]
        if missed:
            return "special-type" if any(i < len(types) and types[i] not in PARSED_TYPES for i in missed) else "other"
        d = first_diff(g, h)
        if d > 0 and (g[d - 1] in hf.added or any(i in hf.added for i in h[:d])):
            return "space-after-special"
        if d == 0 and not (h and h[0] in hf.added):
            return "space-after-special"  # text in front of the token, e.g. lstrip
        return "other"
    if md.get("tokenizer.ggml.model") != "gpt2":
        return "normalizer"
    return "pre-tokenizer" if md.get("tokenizer.ggml.pre") else "pre-missing"


def pieces(ids, toks, around, width=6):
    lo = max(0, around - 2)
    out = []
    for i in ids[lo:lo + width]:
        out.append("%d:%r" % (i, toks[i] if 0 <= i < len(toks) else "?"))
    return ("... " if lo else "") + " ".join(out) + (" ..." if lo + width < len(ids) else "")


def run(args):
    md = read_gguf_metadata(args.gguf)
    hf = HF(args.hf, args.slow)
    facts, findings = static_checks(md, hf)
    toks = md.get("tokenizer.ggml.tokens") or []
    report = {"tokcheck": VERSION, "gguf": args.gguf, "hf": args.hf, "hf_loader": hf.kind, "facts": facts,
              "findings": [], "cases": [], "engine": None}
    out = []
    out.append("tokcheck %s" % VERSION)
    out.append("GGUF  %s" % args.gguf)
    out.append("HF    %s (%s)" % (args.hf, hf.kind))
    for k in ("general.name", "tokenizer.ggml.model", "tokenizer.ggml.pre", "gguf_vocab", "hf_vocab", "add_bos_token",
              "add_eos_token", "add_space_prefix", "added_tokens", "chkhsh"):
        if facts.get(k) is not None:
            out.append("  %-22s %s" % (k, facts[k]))
    causes = []
    for lvl, code, text in findings:
        out.append("[%s] header: %s" % (lvl, text))
        if lvl == "FAIL" and code not in causes:
            causes.append(code)
    n_bad = 0
    vocab_differs = "vocab" in causes  # then every later difference is a consequence of it
    if not args.static:
        if args.server:
            eng = EngineServer(args.server)
        elif args.llama_tokenize:
            eng = EngineBin(args.llama_tokenize, args.gguf)
        else:
            eng = EnginePy(args.gguf)
        report["engine"] = eng.name
        cases = build_cases(md, hf)
        if args.text_file:
            with open(args.text_file, encoding="utf-8") as fh:
                cases += [("yours", line.rstrip("\n"), False) for line in fh if line.strip()]
        per = {}
        for cat, text, add_special in cases:
            g, h = list(eng.encode(text, add_special)), hf.encode(text, add_special)
            ok = g == h
            c = per.setdefault(cat, [0, 0, None])
            c[0] += 1
            rec = {"category": cat, "text": text, "add_special": add_special, "match": ok}
            if not ok:
                n_bad += 1
                c[1] += 1
                d = first_diff(g, h)
                cause = "vocab" if vocab_differs else classify(cat, text, g, h, md, hf)
                nfc = unicodedata.normalize("NFC", text)
                if cause != "vocab" and cat not in ("special", "bos-eos") and nfc != text and list(eng.encode(nfc, add_special)) == h:
                    cause = "unicode-normalization"  # llama.cpp gives HF's ids once the text is NFC-normalised
                rec.update({"llama_cpp": g, "hf": h, "first_diff": d, "cause": cause})
                if cause not in causes:
                    causes.append(cause)
                if c[2] is None:
                    c[2] = (text, d, g, h, cause)
            report["cases"].append(rec)
        out.append("")
        out.append("engine: %s, %d strings" % (eng.name, len(cases)))
        for cat, (n, bad, first) in per.items():
            out.append("  %-8s %3d/%-3d same%s" % (cat, n - bad, n, "" if not bad else "   <-- %d differ" % bad))
            if first:
                text, d, g, h, cause = first
                out.append("      first: %r  (differs at token %d, looks like: %s)" % (text, d, cause))
                out.append("        llama.cpp %s" % pieces(g, toks, d))
                out.append("        HF        %s" % pieces(h, toks, d))
    report["findings"] = [{"level": l, "code": c, "text": t} for l, c, t in findings]
    report["causes"] = causes
    report["verdict"] = "MISMATCH" if causes else "SAME"
    out.append("")
    if causes:
        out.append("RESULT: MISMATCH - likely cause%s, most specific first (fix the first one, then run again):"
                   % ("s" if len(causes) > 1 else ""))
        order = ["vocab", "special-type", "pre-missing", "pre-tokenizer", "normalizer", "unicode-normalization", "bos-eos", "space-after-special", "other"]
        for code in sorted(causes, key=order.index):
            out.append("  * %s: %s" % (code, CAUSES[code]))
    elif args.static:
        out.append("RESULT: no failing header check%s (no strings were tokenized: --static)"
                   % (", see the warnings above" if any(l == "WARN" for l, _, _ in findings) else ""))
    else:
        out.append("RESULT: SAME - every test string gave identical token ids")
    print("\n".join(out))
    if args.json:
        with open(args.json, "w", encoding="utf-8") as fh:
            json.dump(report, fh, ensure_ascii=False, indent=1)
    return 1 if causes else 0


def main():
    ap = argparse.ArgumentParser(description="Compare a GGUF's tokenization with the Hugging Face tokenizer.")
    ap.add_argument("--gguf", required=True, help="the GGUF file (only its header is read by this script)")
    ap.add_argument("--hf", required=True, help="model directory, Hub id, or a tokenizer.json file")
    ap.add_argument("--llama-tokenize", help="path to the llama-tokenize binary")
    ap.add_argument("--server", help="base URL of a running llama-server that has this GGUF loaded")
    ap.add_argument("--slow", action="store_true", help="use the slow (SentencePiece) Hugging Face tokenizer; "
                    "transformers 4.x only")
    ap.add_argument("--static", action="store_true", help="only compare the header; do not run llama.cpp")
    ap.add_argument("--text-file", help="extra test strings, one per line (your own prompts)")
    ap.add_argument("--json", help="also write the full result to this file")
    args = ap.parse_args()
    try:
        sys.exit(run(args))
    except Exception as e:  # unreadable GGUF, missing package, server not reachable ...
        print("tokcheck: could not run: %s: %s" % (type(e).__name__, e), file=sys.stderr)
        sys.exit(2)


if __name__ == "__main__":
    main()
