# /// script
# requires-python = ">=3.11"
# dependencies = ["numpy", "tiktoken", "tokenizers", "huggingface_hub", "transformers", "mistral-common", "blobfile"]
# ///
"""Reproduce the ES-vs-EN (and 25-language) token-count study on FLORES-200 devtest.

    uv run reproduce.py            # writes results.json and langs.json next to this file

Data and tokenizer files are cached in ./cache. Tokenizer files only (no weights) are
fetched from the HF hub at pinned revisions. Kimi uses its official class with
trust_remote_code=True, pinned to the revision (the code is executed from that revision).
"""
import json, re, statistics, tarfile, urllib.request, warnings
from collections import Counter
from pathlib import Path

import numpy as np
import tiktoken
from huggingface_hub import snapshot_download
from mistral_common.tokens.tokenizers.tekken import Tekkenizer
from tokenizers import Tokenizer

warnings.filterwarnings("ignore")
ROOT = Path(__file__).resolve().parent
CACHE = ROOT / "cache"
URL = "https://dl.fbaipublicfiles.com/nllb/flores200_dataset.tar.gz"
SEED, N_BOOT, TOP_N, N_LINES = 12345, 10_000, 1000, 1012

# name -> (kind, repo or tiktoken encoding, full revision)
TOKENIZERS = {
    "tiktoken o200k_base": ("tiktoken", "o200k_base", None),
    "tiktoken o200k_harmony": ("tiktoken", "o200k_harmony", None),
    "tiktoken cl100k_base": ("tiktoken", "cl100k_base", None),
    "Xenova/gpt-4o (o200k_base)": ("hf", "Xenova/gpt-4o", "7956d98f2a83b2751a98ea7136fdf7fe6cf54e69"),
    "DeepSeek-V3.2": ("hf", "deepseek-ai/DeepSeek-V3.2", "a7e62ac04ecb2c0a54d736dc46601c5606cf10a6"),
    "DeepSeek-V4.1-Flash-1017": ("hf", "deepseek-ai/DeepSeek-V4.1-Flash-1017", "1bae0e1088993b9b82de08f59de5be5a34e42170"),
    "Mistral-Small-3.2 (Tekken)": ("tekken", "mistralai/Mistral-Small-3.2-24B-Instruct-2506", "95a6d26c4bfb886c58daf9d3f7332c857cb27b43"),
    "Mistral-Large-4": ("tekken", "mistralai/Mistral-Large-4-1T-A52B", "f12dabdc0c1e99e7f7924461a6f308859b05af4d"),
    "Qwen3-8B": ("hf", "Qwen/Qwen3-8B", "b968826d9c46dd6066d109eabc6255188de91218"),
    "Qwen3.8": ("hf", "Qwen/Qwen3.8-2.4T-A95B", "207bd685a7e3696cfaff12ded7c6a7ea0f88c996"),
    "Llama-3.3": ("hf", "unsloth/Llama-3.3-70B-Instruct", "99cd0d2c829e92a67c844f9144c2509632e5c87f"),
    "Llama-4-Scout": ("hf", "unsloth/Llama-4-Scout-17B-16E-Instruct", "afd8e498c87bda51c7ea8ec68ea2f7c066e6340b"),
    "Gemma-3 (4b-it)": ("hf", "unsloth/gemma-3-4b-it", "bf46152c47f5dd20b896357cb51abc4c03b8ee8c"),
    "Gemma-3 (27b-it)": ("hf", "unsloth/gemma-3-27b-it", "7a5a3053dbd5d1d58e48159e87b9df2fc545a49a"),
    "Gemma-4 (12B-it)": ("hf", "google/gemma-4-12B-it", "43c9d014b231474fa7212dbb48a762566c2b255d"),
    "Gemma-4 (31B-it)": ("hf", "google/gemma-4-31B-it", "842da3794eaa0b77d5f08bae87a17459d91ff475"),
    "GLM-4.6": ("hf", "zai-org/GLM-4.6", "be72194883d968d7923a07e2f61681ea9a2826d1"),
    "GLM-5.3": ("hf", "zai-org/GLM-5.3", "ba32f8c19c8738e2c57c71798c601d477a7bf844"),
    "Kimi-K2": ("kimi", "moonshotai/Kimi-K2-Instruct", "fd1984e2b7a3350dbf7305fe73a4ede25c14de50"),
    "Kimi-K3": ("kimi", "moonshotai/Kimi-K3", "f831ab66814297da540d832a5235f8e904f29d06"),
}
# tokenizers shown in langs.json (names as in the original langs table)
LANG_TOKENIZERS = ["tiktoken o200k_base", "tiktoken cl100k_base", "Gemma-3 (27b-it)", "Mistral-Large-4",
                   "DeepSeek-V4.1-Flash-1017", "Qwen3-8B", "Qwen3.8", "Kimi-K3", "GLM-5.3", "Llama-4-Scout"]
LANGS = ("eng_Latn spa_Latn por_Latn fra_Latn ita_Latn deu_Latn nld_Latn pol_Latn rus_Cyrl ukr_Cyrl tur_Latn "
         "arb_Arab heb_Hebr hin_Deva ben_Beng tam_Taml zho_Hans jpn_Jpan kor_Hang vie_Latn ind_Latn swh_Latn "
         "cat_Latn eus_Latn glg_Latn").split()
FILES = {"hf": ["tokenizer.json"], "tekken": ["tekken.json"],
         "kimi": ["tiktoken.model", "*.py", "tokenizer_config.json"]}


def data_dir() -> Path:
    d = CACHE / "flores200_dataset"
    if not (d / "devtest").exists():
        CACHE.mkdir(exist_ok=True)
        tgz = CACHE / "flores.tgz"
        if not tgz.exists():
            urllib.request.urlretrieve(URL, tgz)
        with tarfile.open(tgz) as t:
            t.extractall(CACHE, filter="data")
    return d


def load(lang: str) -> list[str]:
    lines = (data_dir() / "devtest" / f"{lang}.devtest").read_text(encoding="utf-8").splitlines()
    assert len(lines) == N_LINES, (lang, len(lines))
    return lines


def make_counter(kind: str, repo: str, rev: str | None):
    """Return fn(list[str]) -> list[int] of token counts, no special tokens."""
    if kind == "tiktoken":
        e = tiktoken.get_encoding(repo)
        return lambda xs: [len(t) for t in e.encode_ordinary_batch(xs)]
    p = snapshot_download(repo, revision=rev, local_dir=CACHE / "tok" / repo.replace("/", "__"), allow_patterns=FILES[kind])
    if kind == "hf":
        tk = Tokenizer.from_file(str(Path(p) / "tokenizer.json"))
        return lambda xs: [len(e.ids) for e in tk.encode_batch(xs, add_special_tokens=False)]
    if kind == "tekken":
        tk = Tekkenizer.from_file(str(Path(p) / "tekken.json"))
        return lambda xs: [len(tk.encode(x, bos=False, eos=False)) for x in xs]
    from transformers import AutoTokenizer  # kimi: official class, pinned revision
    tk = AutoTokenizer.from_pretrained(p, trust_remote_code=True)
    return lambda xs: [len(tk.encode(x, add_special_tokens=False)) for x in xs]


def boot_ci(es: np.ndarray, en: np.ndarray) -> list[float]:
    idx = np.random.default_rng(SEED).integers(0, len(es), size=(N_BOOT, len(es)))
    r = es[idx].sum(1) / en[idx].sum(1)
    return [float(np.percentile(r, 2.5)), float(np.percentile(r, 97.5))]


def top_words(lines: list[str]) -> list[str]:
    c = Counter(w for l in lines for w in re.findall(r"\w+", l.lower()))
    return [w for w, _ in c.most_common(TOP_N)]


def main() -> None:
    data = {l: load(l) for l in LANGS}
    assert len({len(v) for v in data.values()}) == 1  # sentence counts equal
    stats = {l: dict(sentences=len(v), chars=sum(map(len, v)), bytes=sum(len(s.encode()) for s in v)) for l, v in data.items()}
    es_en = {l: np.array([len(s) for s in data[l]]) for l in ("eng_Latn", "spa_Latn")}
    top = {l: top_words(data[l]) for l in ("eng_Latn", "spa_Latn")}
    res = {"seed": SEED, "n_boot": N_BOOT, "tiktoken": tiktoken.__version__, "sentences": N_LINES,
           "chars": {k: stats[l]["chars"] for k, l in (("EN", "eng_Latn"), ("ES", "spa_Latn"))},
           "bytes": {k: stats[l]["bytes"] for k, l in (("EN", "eng_Latn"), ("ES", "spa_Latn"))},
           "tokenizers": {}}
    res["ratio_chars_es_en"] = res["chars"]["ES"] / res["chars"]["EN"]
    res["ratio_bytes_es_en"] = res["bytes"]["ES"] / res["bytes"]["EN"]
    langs_tokens: dict[str, dict[str, int]] = {l: {} for l in LANGS}
    for name, (kind, repo, rev) in TOKENIZERS.items():
        fn = make_counter(kind, repo, rev)
        n = {k: np.array(fn(data[l])) for k, l in (("EN", "eng_Latn"), ("ES", "spa_Latn"))}
        assert (n["EN"] / n["EN"] == 1).all() and (n["EN"] > 0).all()  # EN/EN ratio is 1
        r = float(n["ES"].sum() / n["EN"].sum())
        one = fn(["a"])[0]
        single = {k: sum(fn(["a " + w])[0] - one == 1 for w in top[l]) / len(top[l])
                  for k, l in (("EN", "eng_Latn"), ("ES", "spa_Latn"))}
        res["tokenizers"][name] = {
            "source": f"{repo}@{rev}" if rev else f"tiktoken=={tiktoken.__version__}:{repo}",
            "tokens": {k: int(v.sum()) for k, v in n.items()}, "ratio_es_en": r, "ci95": boot_ci(n["ES"], n["EN"]),
            "median_sentence_ratio": float(statistics.median((n["ES"] / n["EN"]).tolist())),
            "tokenizer_only_penalty": r / res["ratio_chars_es_en"], "top1000_single_token_share": single}
        if name in LANG_TOKENIZERS:
            for l in LANGS:
                langs_tokens[l][name] = int(n["ES"].sum()) if l == "spa_Latn" else int(n["EN"].sum()) if l == "eng_Latn" else int(sum(fn(data[l])))
        print(name, round(r, 4), flush=True)
    E = stats["eng_Latn"]
    langs = {}
    for l in LANGS:
        o = dict(stats[l], tokens=langs_tokens[l])
        o["char_ratio"], o["byte_ratio"] = o["chars"] / E["chars"], o["bytes"] / E["bytes"]
        o["token_ratio"] = {k: v / langs_tokens["eng_Latn"][k] for k, v in o["tokens"].items()}
        o["tok_only_bytes"] = {k: r / o["byte_ratio"] for k, r in o["token_ratio"].items()}
        o["tok_only_chars"] = {k: r / o["char_ratio"] for k, r in o["token_ratio"].items()}
        langs[l] = o
    assert all(r == 1 for r in langs["eng_Latn"]["token_ratio"].values())
    (ROOT / "results.json").write_text(json.dumps(res, indent=1, ensure_ascii=False))
    (ROOT / "langs.json").write_text(json.dumps({"tokenizers": {k: res["tokenizers"][k]["source"] for k in LANG_TOKENIZERS}, "langs": langs}, indent=1))


if __name__ == "__main__":
    main()
