"""在本地训练一个极小 SentencePiece BPE 模型，仅用于观察框架边界。"""
import tempfile
from pathlib import Path
import sentencepiece as spm

with tempfile.TemporaryDirectory() as d:
    root=Path(d); corpus=root/'corpus.txt'
    corpus.write_text('hello world\nhello there\nworld hello\nhello world\n',encoding='utf-8')
    prefix=str(root/'toy')
    spm.SentencePieceTrainer.train(input=str(corpus), model_prefix=prefix, model_type='bpe', vocab_size=32, hard_vocab_limit=False, normalization_rule_name='identity', byte_fallback=False, num_threads=1, minloglevel=2)
    sp=spm.SentencePieceProcessor(model_file=prefix+'.model')
    print('sentencepiece',spm.__version__,'pieces',sp.encode('hello world',out_type=str),'ids',sp.encode('hello world'))
    for s in ['hello world','hello  world','hello 🌍']:
        ids=sp.encode(s); recovered=sp.decode(ids); print(repr(s),ids,repr(recovered))
    assert sp.decode(sp.encode('hello world'))=='hello world'
    assert sp.decode(sp.encode('hello  world'))=='hello world'
    assert sp.unk_id() in sp.encode('hello 🌍')
    # 重新训练以覆盖所有 256 个 byte fallback 槽位；保留相同空白策略。
    prefix=str(root/'byte')
    spm.SentencePieceTrainer.train(input=str(corpus),model_prefix=prefix,model_type='bpe',vocab_size=300,hard_vocab_limit=False,normalization_rule_name='identity',byte_fallback=True,num_threads=1,minloglevel=2)
    sp=spm.SentencePieceProcessor(model_file=prefix+'.model')
    s='hello 🌍'; ids=sp.encode(s)
    print('byte fallback:',sp.encode(s,out_type=str),repr(sp.decode(ids)))
    assert sp.unk_id() not in ids and sp.decode(ids)==s
    assert sp.decode(sp.encode('hello  world'))=='hello world'
    print('ALL SENTENCEPIECE ASSERTIONS PASS')
