File size: 1,931 Bytes
8fd424f
1473218
01487a5
846a060
 
 
 
 
3dbbd34
9406201
1473218
 
 
8fd424f
9406201
 
3dbbd34
9406201
 
 
89396b9
3dbbd34
846a060
9406201
 
3dbbd34
45fc586
2f19c95
1473218
45fc586
cd7c00d
45fc586
1473218
099080c
45fc586
d65fa34
45fc586
8fd424f
1473218
45fc586
c3c041c
1473218
 
288e6a7
45fc586
1473218
45fc586
099080c
1473218
45fc586
1473218
ebde5c8
 
 
 
01487a5
02afc65
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { Tokenizer } from "https://nobsdelivr.private.coffee/npm/@huggingface/tokenizers@0.1.3";

if (localStorage.getItem("tokenizerCache")) {
  var tokenizerCache = JSON.parse(localStorage.tokenizerCache);
} else {
  var tokenizerCache = {};
  localStorage.tokenizerCache = "{}";
}
var tokenizerJSON;

let tokenizeButton = document.querySelector("#tokenize");
tokenizeButton.addEventListener("click", async () => {
  tokenizeButton.disabled = true;
  let modelId = document.querySelector("#model").value;
  
  if (modelId in tokenizerCache) {
    tokenizerJSON = tokenizerCache[modelId];
  }
  else {
    let tokenizerJSONSocket = await fetch(`https://huggingface.co/${modelId}/resolve/main/tokenizer.json`);
    tokenizerJSON = await tokenizerJSONSocket.json();
    tokenizerCache[modelId] = tokenizerJSON;
    localStorage.tokenizerCache = JSON.stringify(tokenizerCache);
  }
  
  let tokenizer = new Tokenizer(tokenizerJSON, {});
  
  let text = document.querySelector("#text").value;
  let tokenized = tokenizer.encode(text);
  
  document.querySelector("#totalLength").textContent = `Total length: ${tokenized.ids.length}`;
  
  let output = document.querySelector("#output");
  output.contentDocument.body.innerHTML = "";
  
  let colors = ["#ff00007f", "#00ff007f", "#ffff007f", "#0000ff7f"].sort(() => Math.random() - 0.5);
  
  tokenized.ids.forEach((token, index) => {
    let content = document.createElement("span");
    
    content.textContent = tokenizer.decode([token]);
    content.style.backgroundColor = colors[index % colors.length];
    content.style.fontFamily = "monospace";
    content.style.whiteSpace = "pre-wrap";
    
    content.title = token.toString();
    
    output.contentDocument.body.appendChild(content);
  });
  
  tokenizeButton.disabled = false;
});

document.querySelector("#clear-cache").addEventListener("click", () => {
  tokenizerCache = {};
  localStorage.tokenizerCache = "{}";
});