"""教学实现：不依赖模型权重；Python 3.10+，可选 SentencePiece 实验另见 sp_demo.py。"""
from collections import Counter
from math import log, isclose
import unicodedata


def merge_pair(seq, pair):
    out, i = [], 0
    while i < len(seq):
        if tuple(seq[i:i+2]) == pair:
            out.append(''.join(pair)); i += 2
        else:
            out.append(seq[i]); i += 1
    return out


def train_bpe(corpus, steps):
    # corpus: (独立文本块, 频次)。平局按 pair 字典序。
    data = [(list(word), freq) for word, freq in corpus]
    vocab = {x for seq, _ in data for x in seq}
    merges, trace = [], []
    for _ in range(steps):
        counts = Counter()
        for seq, freq in data:
            for pair in zip(seq, seq[1:]):
                counts[pair] += freq
        if not counts: break
        best = min(counts, key=lambda p: (-counts[p], p))
        trace.append((best, counts[best]))
        merges.append(best); vocab.add(''.join(best))
        data = [(merge_pair(seq, best), f) for seq, f in data]
    return vocab, merges, trace


def bpe_encode(text, merges):
    seq = list(text)
    ranks = {p: i for i, p in enumerate(merges)}
    while True:
        pairs = [p for p in zip(seq, seq[1:]) if p in ranks]
        if not pairs: return seq
        seq = merge_pair(seq, min(pairs, key=ranks.__getitem__))


def longest_match(text, vocab, prefix=''):
    # prefix='##' 模拟 WordPiece；任何位置失败则整个预分词块为 UNK。
    pieces, i = [], 0
    while i < len(text):
        for j in range(len(text), i, -1):
            p = (prefix if i else '') + text[i:j]
            if p in vocab:
                pieces.append(p); i = j; break
        else:
            return ['[UNK]']
    return pieces


def unigram_viterbi(text, probs):
    n = len(text)
    cost, back = [float('inf')] * (n+1), [None] * (n+1)
    cost[0] = 0.0
    for j in range(1, n+1):
        for i in range(j):
            p = probs.get(text[i:j], 0)
            if p > 0 and cost[i] - log(p) < cost[j]:
                cost[j], back[j] = cost[i] - log(p), i
    if back[n] is None and n: raise ValueError('no complete path')
    out, j = [], n
    while j:
        i = back[j]; out.append(text[i:j]); j = i
    return out[::-1], cost[n]


def byte_display_map():
    # 原理与 GPT-2 的可打印映射一致；不依赖 transformers。
    direct = list(range(33,127))+list(range(161,173))+list(range(174,256))
    missing = [b for b in range(256) if b not in direct]
    return {**{b: chr(b) for b in direct}, **{b: chr(256+i) for i,b in enumerate(missing)}}


def main():
    vocab, merges, trace = train_bpe([('low',5),('lower',2),('newest',6),('widest',3)],3)
    print('BPE train:', trace)
    assert trace == [(('e','s'),9),(('es','t'),9),(('l','o'),7)]
    rules = [('e','s'),('t','h'),('th','e'),('es','t'),('h','e')]
    v = set('thest') | {''.join(p) for p in rules}
    a,b = bpe_encode('thest',rules), longest_match('thest',v)
    print('BPE vs MaxMatch:',a,b); assert a==['th','est'] and b==['the','s','t']
    wp={'un','##aff','##able','##a','##f'}
    assert longest_match('unaffable',wp,'##')==['un','##aff','##able']
    assert longest_match('unaffable!',wp,'##')==['[UNK]']
    print('WordPiece:',longest_match('unaffable',wp,'##'), 'failure:',longest_match('unaffable!',wp,'##'))
    assert 40/(100*80)>100/(1000*500)
    p={'new':.30,'est':.25,'ne':.20,'west':.20, **{c:.01 for c in 'newst'}}
    assert isclose(sum(p.values()),1)
    path,cost=unigram_viterbi('newest',p)
    print('Unigram:',path,cost); assert path==['new','est'] and isclose(cost,-log(.075))
    for s in ('A','é','中','😀','café','cafe\u0301'):
        print(repr(s),len(s),s.encode().hex(' '))
    assert [len(s.encode()) for s in ('A','é','中','😀','café','cafe\u0301')]==[1,2,3,4,5,6]
    assert unicodedata.normalize('NFC','cafe\u0301')=='café'
    assert unicodedata.normalize('NFKC','²ﬁＡ')=='2fiA'
    m=byte_display_map(); inv={c:b for b,c in m.items()}
    assert len(inv)==256 and m[32]=='Ġ' and m[10]=='Ċ'
    s=' 中文😀\n'; mapped=''.join(m[b] for b in s.encode())
    assert bytes(inv[c] for c in mapped).decode()==s
    assert b'\xe4\xb8'.decode(errors='replace')=='\ufffd'
    try: b'\xe4\xb8'.decode(errors='strict')
    except UnicodeDecodeError: pass
    else: raise AssertionError('expected strict error')
    assert 151936-151669==267
    print('byte bijection and Unicode assertions: PASS')
    print('ALL ASSERTIONS PASS')

if __name__=='__main__': main()
