#!/usr/bin/env python3
"""Check a tokenizer (a Hugging Face directory, or llama-tokenize + GGUF) against llama.cpp's
models/ggml-vocab-NAME.gguf.inp/.out pairs. Prints "NAME side: same/total".

  check_refs.py hf <llama.cpp dir> NAME <tokenizer dir>
  check_refs.py bin <llama.cpp dir> NAME <llama-tokenize> [gguf]
"""
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
side, src, name, arg = sys.argv[1:5]
base = os.path.join(src, "models", "ggml-vocab-%s.gguf" % name)
inp = open(base + ".inp", encoding="utf-8").read().split("\n__ggml_vocab_test__\n")
exp = [[int(x) for x in l.split()] for l in open(base + ".out").read().split("\n")]
if exp and exp[-1] == [] and len(exp) == len(inp) + 1:
    exp.pop()
assert len(inp) == len(exp), (len(inp), len(exp))
if side == "hf":
    from tokcheck import HF
    enc = HF(arg).encode
else:
    from tokcheck import EngineBin
    enc = EngineBin(arg, sys.argv[5] if len(sys.argv) > 5 else base).encode
bad = [(s, enc(s, False), e) for s, e in zip(inp, exp) if enc(s, False) != e]
print("%s %s: %d/%d same as .out" % (name, side, len(inp) - len(bad), len(inp)))
for s, g, e in bad[:3]:
    print("   differs: %r\n     got %s\n     out %s" % (s[:60], g[:12], e[:12]))
