Download training/tok.py from Reza2kn/Shenava-Rizeh-v1.5: direct link, hf CLI and curl.
- Browser
- Download file 997 Bytes
-
https://huggingface.co/Reza2kn/Shenava-Rizeh-v1.5/resolve/main/training/tok.py
- Command line
-
hf download hf://Reza2kn/Shenava-Rizeh-v1.5/training/tok.py
-
curl -L -o tok.py https://huggingface.co/Reza2kn/Shenava-Rizeh-v1.5/resolve/main/training/tok.py
997 Bytes
| """SentencePiece-BPE-style encoder for tinyasr pieces: merge adjacent symbols whose concatenation has the best (lowest) id.""" | |
| class Tok: | |
| def __init__(s,pieces,allowed): | |
| s.p={} | |
| for i in allowed: | |
| if i>0 and pieces[i] and not pieces[i].startswith('<'): s.p.setdefault(pieces[i],i) | |
| def word(s,w): | |
| sym=['▁'+w[0]]+list(w[1:]) if ('▁'+w[0]) in s.p else ['▁']+list(w) | |
| sym=list('▁'+w) | |
| while True: | |
| best=None | |
| for k in range(len(sym)-1): | |
| m=sym[k]+sym[k+1];i=s.p.get(m) | |
| if i is not None and (best is None or i<best[0]): best=(i,k) | |
| if best is None: break | |
| k=best[1];sym[k:k+2]=[sym[k]+sym[k+1]] | |
| ids=[s.p.get(x) for x in sym] | |
| return None if any(i is None for i in ids) else ids | |
| def encode(s,text): | |
| out=[] | |
| for w in text.split(): | |
| t=s.word(w) | |
| if t is None: return None | |
| out+=t | |
| return out | |