Reza2kn's picture
Shenava Rizeh v1.5 (fine-tuned tinyasr en-fa)
a8248a0 verified
Raw History Blame Contribute Delete
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