nlp-sms-classifier / tokenizer.js
setariaa's picture
Publish browser BERT inference and NLP coursework
efb1307 verified
Raw History Blame Contribute Delete
1.58 kB
// BERT uncased BasicTokenizer + greedy WordPiece. No remote API calls.
export function tokenize(text,vocab,maxLength=96){
const isChinese=c=>{const n=c.codePointAt(0);return (n>=0x4e00&&n<=0x9fff)||(n>=0x3400&&n<=0x4dbf)||(n>=0x20000&&n<=0x2a6df)||(n>=0x2a700&&n<=0x2b73f)||(n>=0x2b740&&n<=0x2b81f)||(n>=0x2b820&&n<=0x2ceaf)||(n>=0xf900&&n<=0xfaff)||(n>=0x2f800&&n<=0x2fa1f)};
let clean='';
for(const c of text){
const n=c.codePointAt(0);
if(n===0||n===0xfffd||(/[\p{Cc}\p{Cf}]/u.test(c)&&!['\t','\n','\r'].includes(c)))continue;
clean+=/\s/u.test(c)?' ':isChinese(c)?` ${c} `:c;
}
const pieces=[];
for(const word of clean.trim().split(/\s+/u)){
const basic=word.toLowerCase().normalize('NFD').replace(/\p{Mn}/gu,'');let chunks=[],chunk='';
for(const c of basic){const n=c.codePointAt(0);if(/\p{P}/u.test(c)||(n>=33&&n<=47)||(n>=58&&n<=64)||(n>=91&&n<=96)||(n>=123&&n<=126)){if(chunk)chunks.push(chunk);chunk='';chunks.push(c)}else chunk+=c}
if(chunk)chunks.push(chunk);
for(const token of chunks){
const chars=Array.from(token);if(chars.length>100){pieces.push(vocab['[UNK]']);continue}
let start=0,sub=[],bad=false;
while(start<chars.length){let end=chars.length,found=null;while(start<end){let candidate=(start?'##':'')+chars.slice(start,end).join('');if(Object.hasOwn(vocab,candidate)){found=vocab[candidate];break}end--}if(found===null){bad=true;break}sub.push(found);start=end}
pieces.push(...(bad?[vocab['[UNK]']]:sub));
}
}
return [vocab['[CLS]'],...pieces.slice(0,maxLength-2),vocab['[SEP]']];
}